Add hiker facts and elevation to the trail records

Each record gains a [hike] table with what a person choosing a trail
wants to know: a one-sentence summary, the official page, where it
starts and ends, its shape, how many days it takes, the season, the
high point, the terrain, how much is off trail and whether a permit is
needed. Every fact names the source it came from, and the validator
rejects a fact with no source. 137 of the 138 trails have the table.

The 85 trails with a track gain elevation.json: highest and lowest
points, total climb and descent, and a profile, computed by
tools/elevation.py from the AWS Terrain Tiles.

Wording: a hiker-made trail is a "route" and its person the "author";
a trail's geometry is a "track". The README, the contributing guide and
the schema now say so, and 71 sentences in the records were rewritten
to match.

Corrections found while checking sources:
- Bartram Trail: the official link now goes to the Forest Service page,
  because the old domain serves injected spam.
- Eastern Continental Trail: ends at Cap Gaspé; Newfoundland removed
  from its regions.
- Wind River High Route (Dixon and Wilson): named for both authors.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-14 01:32:22 -07:00
1 parent 3d88004324
commit efb6164737
233 files changed
+4811 -113

No files matched your search

+5 -5
View File
@@ -189,7 +189,7 @@ def readme_table(trails):
if trail_kind(t) != DESIGNATED:
continue
src = t.get("source", {})
line = "yes" if src.get("line_file") else "no (record only)"
line = "yes" if src.get("line_file") else "no"
regions = ", ".join(t.get("regions", []))
lines.append(
f"| {t['id']} | {_cell(t['name'])} | {t['country']} | {regions} | "
@@ -234,9 +234,9 @@ def counts_line(trails):
routes = [t for t in trails if trail_kind(t) == "route"]
routes_with_line = sum(1 for t in routes if t.get("source", {}).get("line_file"))
return (
f"{total} records, {with_line} with a track, {total - with_line} records only. "
f"Of these, {len(routes)} are person-defined routes: {routes_with_line} with a track "
f"and {len(routes) - routes_with_line} records only."
f"{total} trails, {with_line} with a track and {total - with_line} with no track included. "
f"Of these, {len(routes)} are routes: {routes_with_line} with a track "
f"and {len(routes) - routes_with_line} without."
)
@@ -273,7 +273,7 @@ def main():
f.write(readme_data)
with_line = sum(1 for t in trails if t.get("source", {}).get("line_file"))
print(f"Wrote trails.csv, index.geojson and README table: "
f"{len(trails)} trails, {with_line} with a line.")
f"{len(trails)} trails, {with_line} with a track.")
return 0
+746
View File
@@ -0,0 +1,746 @@
#!/usr/bin/env python3
"""Compute each trail's elevation facts and profile from its track.
Writes <id>/elevation.json beside the record for every trail that has a
track (source.line_file). The elevation comes from the Terrain Tiles open
dataset on AWS (Mapzen "terrarium" PNG tiles; see docs/schema.md and
NOTICE.md for the sources and the credit they require).
Needs Python 3 and numpy and Pillow. Run from anywhere:
python3 tools/elevation.py every trail with a track; skips those
whose output is newer than the track
and this tool
python3 tools/elevation.py long-trail only the named trails
python3 tools/elevation.py --force recompute even if up to date
python3 tools/elevation.py --dry ID... print the figures, write nothing
Tiles are fetched a few at a time and kept in ~/.cache/longhikes-dem/
(outside the repository), so a second run needs no network.
The method, in short (docs/schema.md has the long form):
1. Join the track's pieces end to end (ends within 100 m), as the records do.
2. Sample each part every 30 m along its length. Parts are never joined to
each other; no ascent is counted across a gap.
3. Read the elevation at each sample by bilinear interpolation of the tile grid
(values below sea level are taken as 0).
4. Smooth the profile with a moving average, then count a climb or a descent
only after it exceeds a threshold (reversal threshold). This removes the
noise that makes raw elevation models report far too much ascent.
"""
import sys
sys.dont_write_bytecode = True
import datetime
import io
import json
import math
import os
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
import numpy as np
from PIL import Image
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOL = os.path.abspath(__file__)
EARTH_R = 6371008.8 # metres; the same radius the records' measured lengths use
TILE_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
USER_AGENT = "longhikes-dem/1.0 (open dataset tooling)"
CACHE_DIR = os.path.join(os.path.expanduser("~"), ".cache", "longhikes-dem")
WORKERS = 4
# Method settings. Tuned once against published figures (see the report in
# docs/schema.md), then fixed for every trail. Change them and the method
# version, and every file is recomputed.
METHOD_VERSION = 1
ZOOM = 12 # about 29 m per pixel at 40 degrees north
SPACING_M = 30.0 # distance between samples along the track
SMOOTH_M = 90.0 # moving-average window, in metres along the track
THRESHOLD_M = 5.0 # a climb or descent counts only once it exceeds this
DESPIKE_M = 100.0 # a tile pixel this far from the median of its neighbours is an
# artifact of the tile making and is replaced
JOIN_GAP_M = 100.0 # track pieces whose ends lie this close are joined
PROFILE_POINTS = 700 # most points kept in the profile
LOOP_FRACTION = 0.1 # a part whose ends are this close (as a share of its
# length) is a loop and keeps the direction it has
SOURCE_NAME = "Terrain Tiles (Mapzen terrarium), open data on AWS"
SOURCE_URL = "https://registry.opendata.aws/terrain-tiles/"
ATTRIBUTION = (
"Terrain Tiles, accessed from https://registry.opendata.aws/terrain-tiles. "
"United States 3DEP (formerly NED) and global GMTED2010 and SRTM terrain data "
"courtesy of the U.S. Geological Survey. Canada terrain data contains "
"information licensed under the Open Government Licence - Canada. ArcticDEM "
"terrain data DEM(s) were created from DigitalGlobe, Inc., imagery and funded "
"under National Science Foundation awards 1043681, 1559691, and 1542736. "
"Global ETOPO1 terrain data U.S. National Oceanic and Atmospheric "
"Administration."
)
SMOOTHING_TEXT = (
f"Moving average over {SMOOTH_M:g} m of track; ascent and descent counted with "
f"a {THRESHOLD_M:g} m reversal threshold"
)
LIMITS_TEXT = (
"Computed from a public elevation model, not measured on the ground. Highest "
"and lowest are the model's values at the sample points, with anything below "
"sea level shown as 0. Ascent and descent "
"depend on the smoothing and the threshold, and published figures for the same "
"trail can differ from them by 15 percent or more. Parts of the track are "
"never joined, so a gap is not counted."
)
# ---------------------------------------------------------------- tile maths
def lonlat_to_pixel(lon, lat, zoom):
"""Global pixel position (x, y) of longitude and latitude at a zoom level.
Web Mercator, 256-pixel tiles: the world is 256 * 2**zoom pixels wide.
Accepts numbers or numpy arrays; latitude is clipped to the Mercator limit.
"""
n = 256.0 * (2 ** zoom)
lon = np.asarray(lon, dtype=np.float64)
lat = np.clip(np.asarray(lat, dtype=np.float64), -85.0511287798, 85.0511287798)
x = (lon + 180.0) / 360.0 * n
y = (1.0 - np.arcsinh(np.tan(np.radians(lat))) / math.pi) / 2.0 * n
return x, y
def pixel_to_lonlat(x, y, zoom):
"""Inverse of lonlat_to_pixel."""
n = 256.0 * (2 ** zoom)
lon = np.asarray(x, dtype=np.float64) / n * 360.0 - 180.0
lat = np.degrees(np.arctan(np.sinh(math.pi * (1.0 - 2.0 * np.asarray(y, dtype=np.float64) / n))))
return lon, lat
def ground_m_per_pixel(lat, zoom):
"""Ground size of one pixel in metres at a latitude."""
return 2.0 * math.pi * EARTH_R * math.cos(math.radians(lat)) / (256.0 * 2 ** zoom)
def decode_terrarium(rgb):
"""Elevation in metres from a terrarium tile: (red * 256 + green + blue / 256) - 32768.
rgb is an array of shape (h, w, 3) of 0..255 values.
"""
a = np.asarray(rgb, dtype=np.float64)
return (a[..., 0] * 256.0 + a[..., 1] + a[..., 2] / 256.0 - 32768.0).astype(np.float32)
def despike(tile, threshold_m=DESPIKE_M):
"""Replace pixels that are far from their surroundings.
The tiles hold a few artifacts: lines and small patches of pixels, mostly
where a river or the coast meets sea level, with values thousands of
metres off. A pixel more than threshold_m from the median of its 3 x 3
neighbourhood is replaced by the median of the unflagged pixels in its
5 x 5 neighbourhood (or the 3 x 3 median where none is left). The pass is
repeated, up to four times, for patches that need more than one. Real
terrain at this pixel size does not change that much in one pixel.
"""
from numpy.lib.stride_tricks import sliding_window_view as windows
h, w = tile.shape
out = tile
for _ in range(4):
med3 = np.median(windows(np.pad(out, 1, mode="edge"), (3, 3)).reshape(h, w, 9), axis=2)
bad = np.abs(out - med3) > threshold_m
if not bad.any():
break
ys, xs = np.nonzero(bad)
vals = windows(np.pad(out, 2, mode="edge"), (5, 5))[ys, xs].reshape(len(ys), 25).astype(np.float64)
flags = windows(np.pad(bad, 2, mode="edge"), (5, 5))[ys, xs].reshape(len(ys), 25)
vals[flags] = np.nan
with np.errstate(all="ignore"):
fill = np.nanmedian(vals, axis=1)
fill = np.where(np.isnan(fill), med3[ys, xs], fill)
out = out.copy()
out[ys, xs] = fill
return out
def below_sea_level_to_zero(tile):
"""Raise every value below sea level to 0.
Beside a coast the tiles carry the depth of the sea, and a read near the
shore would mix it into the land. None of the trails in this dataset goes
below sea level, so a value below 0 is the sea and not the trail.
"""
return np.maximum(tile, 0.0).astype(np.float32)
def corner_pixels(px, py):
"""The four pixels a bilinear read at (px, py) uses, with their weights.
Pixel i covers [i, i + 1) and its value belongs at its centre, i + 0.5.
Returns (ix0, iy0, fx, fy): the integer pixel up and left of the point and
the fractions toward the next pixel in x and y.
"""
fx = np.asarray(px, dtype=np.float64) - 0.5
fy = np.asarray(py, dtype=np.float64) - 0.5
ix0 = np.floor(fx).astype(np.int64)
iy0 = np.floor(fy).astype(np.int64)
return ix0, iy0, fx - ix0, fy - iy0
def tiles_needed(px, py):
"""Set of (x, y) tiles that a bilinear read at every (px, py) touches."""
ix0, iy0, _, _ = corner_pixels(px, py)
pairs = np.concatenate([
np.stack([(ix0 + dx) // 256, (iy0 + dy) // 256], axis=1)
for dx in (0, 1) for dy in (0, 1)])
return {(int(a), int(b)) for a, b in np.unique(pairs, axis=0)}
def bilinear(px, py, tile_of):
"""Interpolated elevation at global pixel positions.
tile_of(tx, ty) returns the 256 x 256 float32 elevation array of a tile.
"""
ix0, iy0, fx, fy = corner_pixels(px, py)
out = np.zeros(len(ix0), dtype=np.float64)
corners = ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)),
(0, 1, (1 - fx) * fy), (1, 1, fx * fy))
for dx, dy, weight in corners:
cx, cy = ix0 + dx, iy0 + dy
tx, ty = cx // 256, cy // 256
key = tx * 4194304 + ty # unique per tile at any zoom up to 21
for k in np.unique(key):
sel = key == k
tile = tile_of(int(tx[sel][0]), int(ty[sel][0]))
out[sel] += weight[sel] * tile[cy[sel] % 256, cx[sel] % 256]
return out
# ---------------------------------------------------------------- the track
def haversine_m(lon, lat):
"""Lengths in metres of the segments between consecutive points."""
lo, la = np.radians(lon), np.radians(lat)
dlat, dlon = np.diff(la), np.diff(lo)
a = np.sin(dlat / 2) ** 2 + np.cos(la[:-1]) * np.cos(la[1:]) * np.sin(dlon / 2) ** 2
return 2 * EARTH_R * np.arcsin(np.minimum(1.0, np.sqrt(a)))
def track_parts(data):
"""LineString and MultiLineString parts of a GeoJSON track; two points or more."""
if data.get("type") == "FeatureCollection":
geoms = [(f.get("geometry") or {}) for f in data.get("features", [])]
elif data.get("type") == "Feature":
geoms = [data.get("geometry") or {}]
else:
geoms = [data]
parts = []
for geom in geoms:
if geom.get("type") == "LineString":
parts.append(geom["coordinates"])
elif geom.get("type") == "MultiLineString":
parts.extend(geom["coordinates"])
return [[(c[0], c[1]) for c in p] for p in parts if len(p) >= 2]
def _gap_m(a, b):
dx = (a[0] - b[0]) * math.cos(math.radians((a[1] + b[1]) / 2))
return math.hypot(dx, a[1] - b[1]) * math.pi / 180.0 * EARTH_R
def join_parts(parts, gap_m=JOIN_GAP_M):
"""Chain parts whose end points lie within gap_m of each other.
Greedy: a chain grows at its tail, then at its head, taking the nearest
unused part end each time (a part is reversed when its far end is the
near one). Parts that touch nothing stay as they are. This is the same
rule the records use for their `parts` count (verification.parts).
"""
if not parts:
return []
cell = max(gap_m, 1.0)
k = math.pi / 180.0 * EARTH_R
max_lat = max(abs(c[1]) for p in parts for c in (p[0], p[-1]))
scale = max(math.cos(math.radians(max_lat)), 1e-9) * k
def cell_of(c):
return (math.floor(c[0] * scale / cell), math.floor(c[1] * k / cell))
grid = {}
for i, p in enumerate(parts):
for end in (0, 1):
grid.setdefault(cell_of(p[0] if end == 0 else p[-1]), []).append((i, end))
used = [False] * len(parts)
def nearest(point):
gx, gy = cell_of(point)
best = None
for x in (gx - 1, gx, gx + 1):
for y in (gy - 1, gy, gy + 1):
for i, end in grid.get((x, y), ()):
if used[i]:
continue
d = _gap_m(point, parts[i][0] if end == 0 else parts[i][-1])
if d <= gap_m and (best is None or d < best[0]):
best = (d, i, end)
return best
out = []
for i0, first in enumerate(parts):
if used[i0]:
continue
used[i0] = True
chain = list(first)
while True:
hit = nearest(chain[-1])
if hit is None:
break
_, i, end = hit
used[i] = True
chain.extend(parts[i] if end == 0 else parts[i][::-1])
while True:
hit = nearest(chain[0])
if hit is None:
break
_, i, end = hit
used[i] = True
chain[:0] = parts[i][::-1] if end == 0 else parts[i]
out.append(chain)
return out
def orient_and_order(chains):
"""Give the parts a fixed direction and order, so the output is repeatable.
The whole track runs south to north if it is taller than it is wide, and
west to east otherwise. Each part is turned to run that way. A part that
ends close to where it starts (a loop) keeps the direction it has. Parts
are put in order along the same axis, by their centres. Returns
(chains, orientation) with orientation "south-to-north" or "west-to-east".
"""
if not chains:
return [], "west-to-east"
lons = [c[0] for ch in chains for c in ch]
lats = [c[1] for ch in chains for c in ch]
mid_lat = (min(lats) + max(lats)) / 2.0
width = (max(lons) - min(lons)) * math.cos(math.radians(mid_lat))
north = (max(lats) - min(lats)) > width
axis = 1 if north else 0
out = []
for ch in chains:
length = float(haversine_m(np.array([c[0] for c in ch]), np.array([c[1] for c in ch])).sum())
if _gap_m(ch[0], ch[-1]) > LOOP_FRACTION * length and ch[-1][axis] < ch[0][axis]:
ch = ch[::-1]
out.append(ch)
out.sort(key=lambda ch: sum(c[axis] for c in ch) / len(ch))
return out, ("south-to-north" if north else "west-to-east")
def resample(chain, spacing_m=SPACING_M):
"""Points every spacing_m along a part, from its start and ending at its end.
Returns (lon, lat, dist_m) as arrays, dist_m measured from the start of the
part. The last step is shorter than spacing_m unless the length divides it.
"""
lon = np.array([c[0] for c in chain], dtype=np.float64)
lat = np.array([c[1] for c in chain], dtype=np.float64)
cum = np.concatenate([[0.0], np.cumsum(haversine_m(lon, lat))])
total = float(cum[-1])
d = np.arange(0.0, total, spacing_m)
if total - (d[-1] if len(d) else 0.0) > 1e-6 or len(d) < 2:
d = np.append(d, total)
# np.interp needs increasing x; drop zero-length steps (repeated points)
keep = np.concatenate([[True], np.diff(cum) > 0])
cum_k, lon_k, lat_k = cum[keep], lon[keep], lat[keep]
if len(cum_k) < 2:
return lon[:1], lat[:1], np.zeros(1)
return np.interp(d, cum_k, lon_k), np.interp(d, cum_k, lat_k), d
# ---------------------------------------------------------------- the profile
def smooth(elev, window_samples):
"""Centred moving average; the window shrinks at the ends of the part."""
n = len(elev)
w = max(1, int(window_samples))
if w % 2 == 0:
w += 1
half = w // 2
if n < 2 or half == 0:
return np.asarray(elev, dtype=np.float64).copy()
c = np.concatenate([[0.0], np.cumsum(np.asarray(elev, dtype=np.float64))])
idx = np.arange(n)
lo = np.maximum(idx - half, 0)
hi = np.minimum(idx + half + 1, n)
return (c[hi] - c[lo]) / (hi - lo)
def climb(elev, threshold_m):
"""Total ascent and descent with a reversal threshold.
Find the turning points of the profile: a high point counts as a turn only
once the profile has fallen more than threshold_m below it, and a low point
only once it has risen more than threshold_m above it. Ascent and descent
are the rises and falls between successive turning points, so smaller
wiggles count for nothing. Ascent minus descent is the net change from the
first point to the last, to within threshold_m. Returns (ascent_m, descent_m).
"""
e = np.asarray(elev, dtype=np.float64)
if len(e) < 2:
return 0.0, 0.0
turns = [float(e[0])]
hi = lo = float(e[0])
mode = 0 # 0 not yet decided, 1 climbing, -1 descending
for v in e[1:]:
v = float(v)
if mode == 0:
hi, lo = max(hi, v), min(lo, v)
if v - lo > threshold_m:
turns.append(lo)
mode, hi = 1, v
elif hi - v > threshold_m:
turns.append(hi)
mode, lo = -1, v
elif mode == 1:
if v > hi:
hi = v
elif hi - v > threshold_m:
turns.append(hi)
mode, lo = -1, v
else:
if v < lo:
lo = v
elif v - lo > threshold_m:
turns.append(lo)
mode, hi = 1, v
turns.append(hi if mode == 1 else lo if mode == -1 else float(e[-1]))
d = np.diff(np.array(turns))
return float(d[d > 0].sum()), float(-d[d < 0].sum())
def thin_profile(dist, elev, max_points=PROFILE_POINTS, keep=()):
"""Indices of at most max_points points that draw the profile faithfully.
Ramer-Douglas-Peucker on elevation against distance, with the vertical
tolerance found by bisection. The first and last points and the indices in
keep (the extremes) are always kept. Deterministic.
"""
n = len(dist)
forced = sorted({0, n - 1} | {int(i) for i in keep})
if n <= max_points:
return list(range(n))
d = np.asarray(dist, dtype=np.float64)
e = np.asarray(elev, dtype=np.float64)
def rdp(tol):
marked = np.zeros(n, dtype=bool)
marked[forced] = True
stack = list(zip(forced[:-1], forced[1:]))
while stack:
a, b = stack.pop()
if b - a < 2:
continue
seg = slice(a + 1, b)
t = (d[seg] - d[a]) / (d[b] - d[a]) if d[b] > d[a] else np.zeros(b - a - 1)
dev = np.abs(e[seg] - (e[a] + t * (e[b] - e[a])))
j = int(np.argmax(dev))
if dev[j] > tol:
m = a + 1 + j
marked[m] = True
stack.append((a, m))
stack.append((m, b))
return np.flatnonzero(marked)
lo, hi = 0.0, float(np.ptp(e)) + 1.0
best = rdp(hi)
for _ in range(40):
mid = (lo + hi) / 2.0
got = rdp(mid)
if len(got) <= max_points:
best, hi = got, mid
else:
lo = mid
return [int(i) for i in best]
# ---------------------------------------------------------------- the tiles
def tile_path(cache, zoom, x, y):
return os.path.join(cache, "terrarium", str(zoom), str(x), f"{y}.png")
def fetch_tile(cache, zoom, x, y, opener=urllib.request.urlopen):
"""Path of a tile in the cache, fetching it first if it is not there."""
path = tile_path(cache, zoom, x, y)
if os.path.isfile(path):
return path
url = TILE_URL.format(z=zoom, x=x, y=y)
last = None
for attempt in range(5):
try:
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with opener(req, timeout=60) as r:
body = r.read()
Image.open(io.BytesIO(body)).verify()
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = f"{path}.{os.getpid()}.part"
with open(tmp, "wb") as f:
f.write(body)
os.replace(tmp, path)
return path
except urllib.error.HTTPError as e:
last = e
if e.code == 404:
break
except Exception as e: # noqa: BLE001 - retry any network or decode trouble
last = e
time.sleep(1.5 * (attempt + 1))
raise RuntimeError(f"could not fetch tile {zoom}/{x}/{y}: {last}")
def load_tile(path):
with Image.open(path) as im:
return below_sea_level_to_zero(despike(decode_terrarium(np.asarray(im.convert("RGB")))))
class TileStore:
"""Decoded tiles on demand; fetches the missing ones a few at a time."""
def __init__(self, zoom, cache=CACHE_DIR):
self.zoom, self.cache, self.tiles = zoom, cache, {}
self.fetched = 0
def prefetch(self, needed):
missing = [t for t in sorted(needed) if not os.path.isfile(tile_path(self.cache, self.zoom, *t))]
if missing:
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
list(pool.map(lambda t: fetch_tile(self.cache, self.zoom, *t), missing))
self.fetched += len(missing)
for t in needed:
self.get(*t)
def get(self, x, y):
if (x, y) not in self.tiles:
n = 2 ** self.zoom
if not 0 <= y < n:
raise RuntimeError(f"tile row {y} is outside the map at zoom {self.zoom}")
self.tiles[(x, y)] = load_tile(fetch_tile(self.cache, self.zoom, x % n, y))
return self.tiles[(x, y)]
def clear(self):
self.tiles = {}
# ---------------------------------------------------------------- one trail
def sample_trail(data, store, zoom=ZOOM, spacing_m=SPACING_M):
"""Resample a track and read its elevations. Returns a list of parts.
Each part is a dict of numpy arrays: lon, lat, dist_m (from the part's own
start) and elev (raw interpolated metres). Also returns the orientation.
"""
chains, orientation = orient_and_order(join_parts(track_parts(data)))
sampled = [r for r in (resample(ch, spacing_m) for ch in chains) if len(r[2]) >= 2]
pxs = [lonlat_to_pixel(lo, la, zoom) for lo, la, _ in sampled]
needed = set()
for px, py in pxs:
needed |= tiles_needed(px, py)
store.prefetch(needed)
parts = []
for (lon, lat, d), (px, py) in zip(sampled, pxs):
parts.append({"lon": lon, "lat": lat, "dist_m": d, "elev": bilinear(px, py, store.get)})
return parts, orientation
def summarise(parts, orientation, published_km, window_m=SMOOTH_M, threshold_m=THRESHOLD_M,
spacing_m=SPACING_M, max_points=PROFILE_POINTS):
"""Turn sampled parts into the facts and the profile (a dict, not yet dated)."""
window = max(1, round(window_m / spacing_m))
ascent = descent = 0.0
start = 0.0
smoothed, offsets = [], []
for p in parts:
s = smooth(p["elev"], window)
a, dn = climb(s, threshold_m)
ascent += a
descent += dn
smoothed.append(s)
offsets.append(start)
start += float(p["dist_m"][-1])
track_km = start / 1000.0
lon = np.concatenate([p["lon"] for p in parts])
lat = np.concatenate([p["lat"] for p in parts])
raw = np.concatenate([p["elev"] for p in parts])
dist = np.concatenate([p["dist_m"] + o for p, o in zip(parts, offsets)]) / 1000.0
prof = np.concatenate(smoothed)
hi, lo = int(np.argmax(raw)), int(np.argmin(raw))
# The profile follows the smoothed values but passes through the true
# extremes, so the chart agrees with the highest and lowest figures.
prof[hi], prof[lo] = raw[hi], raw[lo]
first_of_part = []
k = 0
for p in parts:
first_of_part.append(k)
k += len(p["lon"])
keep = [hi, lo] + [i for i in first_of_part] + [i - 1 for i in first_of_part if i > 0]
idx = thin_profile(dist, prof, max_points, keep)
# Round the distances; where two points round to the same value drop the
# later one, except the first point of a part, which sits at the same
# distance as the end of the part before it (the gap between parts).
starts = set(first_of_part)
kept, last = [], None
for i in idx:
r = round(float(dist[i]), 2)
if last is not None and r <= last and i not in starts:
if i in (hi, lo) and kept[-1] not in starts and kept[-1] not in (hi, lo):
kept[-1] = i # an extreme takes the place of its neighbour
continue
kept.append(i)
last = r
idx = kept
out = {
"highest": {"m": int(round(raw[hi])), "lon": round(float(lon[hi]), 5),
"lat": round(float(lat[hi]), 5)},
"lowest": {"m": int(round(raw[lo])), "lon": round(float(lon[lo]), 5),
"lat": round(float(lat[lo]), 5)},
"ascent_m": int(round(ascent)),
"descent_m": int(round(descent)),
"track_km": round(track_km, 1),
"published_km": published_km,
"coverage": round(track_km / published_km, 3) if published_km else None,
"parts": len(parts),
"orientation": orientation,
"profile": [[round(float(dist[i]), 2), int(round(prof[i]))] for i in idx],
}
if len(parts) > 1:
out["part_starts_km"] = [round(o / 1000.0, 2) for o in offsets[1:]]
return out
def build(trail_id, rec, data, store, today, zoom=ZOOM):
parts, orientation = sample_trail(data, store, zoom)
doc = summarise(parts, orientation, rec.get("length_km"))
doc["source"] = {
"model": SOURCE_NAME,
"url": SOURCE_URL,
"attribution": ATTRIBUTION,
"zoom": zoom,
"ground_m_per_pixel_at_40n": round(ground_m_per_pixel(40.0, zoom), 1),
"sample_spacing_m": SPACING_M,
"smoothing": SMOOTHING_TEXT,
"limits": LIMITS_TEXT,
"method_version": METHOD_VERSION,
"computed": today,
}
return doc
def dumps(doc):
"""Compact, sorted, repeatable JSON text."""
return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n"
def write_if_changed(path, doc):
"""Write doc; keep the old date when nothing else changed. True if written."""
if os.path.isfile(path):
try:
with open(path, encoding="utf-8") as f:
old = json.load(f)
probe = json.loads(json.dumps(doc))
probe["source"]["computed"] = old.get("source", {}).get("computed")
if dumps(probe) == dumps(old):
doc["source"]["computed"] = old["source"]["computed"]
except (ValueError, KeyError, TypeError):
pass
text = dumps(doc)
if os.path.isfile(path):
with open(path, encoding="utf-8") as f:
if f.read() == text:
os.utime(path)
return False
with open(path, "w", encoding="utf-8") as f:
f.write(text)
return True
# ---------------------------------------------------------------- the command
def load_record(trail_id):
sys.path.insert(0, os.path.join(ROOT, "tools"))
import build_index # noqa: E402
return build_index.load_toml(os.path.join(ROOT, trail_id, "trail.toml"))
def trails_with_track():
import build_index # noqa: E402
out = []
for tid in build_index.trail_dirs(ROOT):
if os.path.isfile(os.path.join(ROOT, tid, "line.geojson")):
out.append(tid)
return out
def up_to_date(trail_id):
out = os.path.join(ROOT, trail_id, "elevation.json")
if not os.path.isfile(out):
return False
t = os.path.getmtime(out)
return t > os.path.getmtime(os.path.join(ROOT, trail_id, "line.geojson")) and t > os.path.getmtime(TOOL)
def main(argv):
force = dry = False
zoom, cache, ids = ZOOM, CACHE_DIR, []
args = list(argv)
while args:
a = args.pop(0)
if a == "--force":
force = True
elif a == "--dry":
dry = True
elif a == "--zoom":
zoom = int(args.pop(0))
elif a == "--cache":
cache = os.path.expanduser(args.pop(0))
elif a in ("-h", "--help"):
print(__doc__)
return 0
else:
ids.append(a)
sys.path.insert(0, os.path.join(ROOT, "tools"))
every = trails_with_track()
for tid in ids:
if tid not in every:
print(f"ERROR {tid}: no trail with a track by that id")
return 1
todo = ids or every
today = datetime.date.today().isoformat()
store = TileStore(zoom, cache)
began = time.time()
done = skipped = 0
for tid in todo:
if not ids and not force and not dry and up_to_date(tid):
skipped += 1
continue
rec = load_record(tid)
with open(os.path.join(ROOT, tid, "line.geojson"), encoding="utf-8") as f:
data = json.load(f)
t0 = time.time()
doc = build(tid, rec, data, store, today, zoom)
store.clear()
h, lo = doc["highest"], doc["lowest"]
print(f"{tid}: high {h['m']} m, low {lo['m']} m, ascent {doc['ascent_m']} m, "
f"descent {doc['descent_m']} m, {doc['track_km']} km of {doc['published_km']} "
f"({doc['parts']} parts, {len(doc['profile'])} points) in {time.time() - t0:.1f} s",
flush=True)
if not dry:
write_if_changed(os.path.join(ROOT, tid, "elevation.json"), doc)
done += 1
print(f"{done} computed, {skipped} up to date, {store.fetched} tiles fetched, "
f"{time.time() - began:.0f} s")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+458
View File
@@ -0,0 +1,458 @@
"""Tests for tools/elevation.py: the parts that need no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import io
import json
import math
import os
import sys
import tempfile
import unittest
import urllib.error
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import numpy as np # noqa: E402
from PIL import Image # noqa: E402
import elevation as E # noqa: E402
def encode(elev):
"""Terrarium bytes for an elevation array (the inverse of decode_terrarium)."""
v = np.asarray(elev, dtype=np.float64) + 32768.0
r = np.floor(v / 256.0)
g = np.floor(v - r * 256.0)
b = np.floor((v - np.floor(v)) * 256.0)
return np.stack([r, g, b], axis=-1).astype(np.uint8)
def png_bytes(rgb):
buf = io.BytesIO()
Image.fromarray(rgb, "RGB").save(buf, "PNG")
return buf.getvalue()
class TileMaths(unittest.TestCase):
def test_origin_and_far_corner(self):
x, y = E.lonlat_to_pixel(-180.0, 85.0511287798, 3)
self.assertAlmostEqual(float(x), 0.0, places=6)
self.assertAlmostEqual(float(y), 0.0, places=3)
x, y = E.lonlat_to_pixel(180.0, -85.0511287798, 3)
self.assertAlmostEqual(float(x), 256 * 8, places=6)
self.assertAlmostEqual(float(y), 256 * 8, places=3)
def test_equator_and_prime_meridian_are_the_centre(self):
x, y = E.lonlat_to_pixel(0.0, 0.0, 5)
self.assertAlmostEqual(float(x), 256 * 16, places=6)
self.assertAlmostEqual(float(y), 256 * 16, places=6)
def test_known_tile(self):
# Mount Rainier's summit at zoom 12, by the standard slippy-map formula
lon, lat, z = -121.7603, 46.8523, 12
n = 2 ** z
want = (int((lon + 180.0) / 360.0 * n),
int((1.0 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2.0 * n))
x, y = E.lonlat_to_pixel(lon, lat, z)
self.assertEqual((int(x // 256), int(y // 256)), want)
self.assertEqual(want, (662, 1443))
def test_round_trip(self):
lon, lat = np.array([-121.7603, 10.5, 170.0]), np.array([46.8523, -33.0, 60.0])
for z in (8, 12, 14):
x, y = E.lonlat_to_pixel(lon, lat, z)
lo, la = E.pixel_to_lonlat(x, y, z)
np.testing.assert_allclose(lo, lon, atol=1e-9)
np.testing.assert_allclose(la, lat, atol=1e-9)
def test_ground_resolution(self):
self.assertAlmostEqual(E.ground_m_per_pixel(0.0, 12), 38.2, delta=0.1)
self.assertAlmostEqual(E.ground_m_per_pixel(40.0, 12), 29.3, delta=0.1)
self.assertAlmostEqual(E.ground_m_per_pixel(40.0, 13), E.ground_m_per_pixel(40.0, 12) / 2, places=6)
def test_tiles_needed_includes_neighbours_at_an_edge(self):
# a point 0.2 pixel inside tile (1, 1) uses pixels from tile (0, 0) too
tiles = E.tiles_needed(np.array([256.2]), np.array([256.2]))
self.assertEqual(tiles, {(0, 0), (1, 0), (0, 1), (1, 1)})
def test_tiles_needed_inside_one_tile(self):
self.assertEqual(E.tiles_needed(np.array([300.5]), np.array([300.5])), {(1, 1)})
class Decoding(unittest.TestCase):
def test_formula(self):
rgb = np.array([[[128, 0, 0], [129, 4, 128], [127, 255, 0], [0, 0, 0]]], dtype=np.uint8)
np.testing.assert_allclose(E.decode_terrarium(rgb)[0],
[0.0, 260.5, -1.0, -32768.0])
def test_round_trip_with_encode(self):
elev = np.array([[-86.0, 0.0, 1.5, 4009.25, 8848.0]])
np.testing.assert_allclose(E.decode_terrarium(encode(elev)), elev, atol=1 / 256)
def test_png_load(self):
elev = np.full((256, 256), 1234.5)
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "t.png")
with open(path, "wb") as f:
f.write(png_bytes(encode(elev)))
tile = E.load_tile(path)
self.assertEqual(tile.shape, (256, 256))
self.assertAlmostEqual(float(tile[10, 10]), 1234.5, places=2)
def test_despike_removes_a_bad_line_and_keeps_a_cliff(self):
t = np.full((256, 256), 100.0, dtype=np.float32)
t[:, 128:] = 600.0 # a real step: stays
t[40:44, 60] = -5400.0 # a one-pixel line of garbage: goes
out = E.despike(t)
self.assertTrue(np.all(out[40:44, 60] == 100.0))
self.assertTrue(np.all(out[:, :128] == 100.0) and np.all(out[:, 128:] == 600.0))
def test_despike_leaves_a_clean_tile_alone(self):
t = (np.linspace(0, 200, 256)[None, :] + np.zeros((256, 1))).astype(np.float32)
self.assertIs(E.despike(t), t)
class SeaLevel(unittest.TestCase):
def test_below_sea_level_is_zero(self):
t = np.array([[-50.0, 0.0, 12.5, -0.1]], dtype=np.float32)
np.testing.assert_allclose(E.below_sea_level_to_zero(t), [[0.0, 0.0, 12.5, 0.0]])
def test_load_tile_applies_it(self):
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "t.png")
with open(path, "wb") as f:
f.write(png_bytes(encode(np.full((256, 256), -20.0))))
self.assertEqual(float(E.load_tile(path).min()), 0.0)
class Bilinear(unittest.TestCase):
def test_pixel_centres_and_midpoints(self):
tile = np.zeros((256, 256), dtype=np.float32)
tile[10, 10], tile[10, 11], tile[11, 10], tile[11, 11] = 0.0, 100.0, 200.0, 300.0
get = lambda tx, ty: tile # noqa: E731
# the centre of pixel (10, 10) is at 10.5, 10.5
self.assertAlmostEqual(float(E.bilinear(np.array([10.5]), np.array([10.5]), get)[0]), 0.0)
self.assertAlmostEqual(float(E.bilinear(np.array([11.5]), np.array([10.5]), get)[0]), 100.0)
self.assertAlmostEqual(float(E.bilinear(np.array([11.0]), np.array([11.0]), get)[0]), 150.0)
def test_reads_across_a_tile_edge(self):
left = np.full((256, 256), 100.0, dtype=np.float32)
right = np.full((256, 256), 200.0, dtype=np.float32)
get = lambda tx, ty: left if tx == 0 else right # noqa: E731
# exactly on the seam: halfway between the last pixel of one tile and the first of the next
self.assertAlmostEqual(float(E.bilinear(np.array([256.0]), np.array([5.5]), get)[0]), 150.0)
self.assertAlmostEqual(float(E.bilinear(np.array([255.5]), np.array([5.5]), get)[0]), 100.0)
self.assertAlmostEqual(float(E.bilinear(np.array([256.5]), np.array([5.5]), get)[0]), 200.0)
def test_plane_is_exact(self):
yy, xx = np.mgrid[0:256, 0:256]
tile = (3.0 * xx + 7.0 * yy).astype(np.float32)
px, py = np.array([40.3, 100.9, 200.1]), np.array([12.2, 90.5, 30.7])
got = E.bilinear(px, py, lambda tx, ty: tile)
np.testing.assert_allclose(got, 3.0 * (px - 0.5) + 7.0 * (py - 0.5), atol=1e-3)
def line_km(km, lat=45.0, lon0=-110.0):
"""A west-to-east track of about km kilometres, with a point every 100 m."""
step = 0.1 / (111.195 * math.cos(math.radians(lat)))
n = int(km * 10) + 1
return [(lon0 + i * step, lat) for i in range(n)]
class Track(unittest.TestCase):
def test_haversine_one_degree_of_latitude(self):
d = E.haversine_m(np.array([0.0, 0.0]), np.array([0.0, 1.0]))
self.assertAlmostEqual(float(d[0]), 111195.0, delta=5)
def test_parts_from_geojson(self):
data = {"type": "FeatureCollection", "features": [
{"geometry": {"type": "LineString", "coordinates": [[0, 0], [1, 1]]}},
{"geometry": {"type": "MultiLineString", "coordinates": [[[2, 2], [3, 3]], [[4, 4]]]}},
{"geometry": None},
{"geometry": {"type": "Point", "coordinates": [0, 0]}},
]}
self.assertEqual(E.track_parts(data), [[(0, 0), (1, 1)], [(2, 2), (3, 3)]])
def test_join_chains_touching_ends_and_reverses(self):
a = [(0.0, 45.0), (0.01, 45.0)]
b = [(0.02, 45.0), (0.01, 45.0001)] # its far end touches a's end; stored backwards
c = [(0.5, 45.0), (0.51, 45.0)] # touches nothing
out = E.join_parts([a, b, c])
self.assertEqual(len(out), 2)
self.assertEqual(out[0][0], (0.0, 45.0))
self.assertEqual(out[0][-1], (0.02, 45.0))
self.assertEqual(out[1], c)
def test_join_does_not_invent_a_join_beyond_the_gap(self):
a = [(0.0, 45.0), (0.01, 45.0)]
b = [(0.0115, 45.0), (0.02, 45.0)] # about 120 m away
self.assertEqual(len(E.join_parts([a, b])), 2)
self.assertEqual(len(E.join_parts([a, b], gap_m=200.0)), 1)
def test_orientation_and_order_west_to_east(self):
east = [(-100.0, 45.0), (-99.9, 45.0)]
west = [(-100.2, 45.0), (-100.1, 45.0)]
out, o = E.orient_and_order([east[::-1], west])
self.assertEqual(o, "west-to-east")
self.assertEqual(out, [west, east])
def test_orientation_south_to_north(self):
a = [(-100.0, 45.0), (-100.0, 45.5)]
out, o = E.orient_and_order([a[::-1]])
self.assertEqual(o, "south-to-north")
self.assertEqual(out, [a])
def test_a_loop_keeps_its_direction(self):
ring = [(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0.0, 0.0005)]
out, _ = E.orient_and_order([ring])
self.assertEqual(out[0], ring)
def test_resample_spacing_and_ends(self):
lon, lat, d = E.resample(line_km(1.0), 30.0)
self.assertEqual(float(d[0]), 0.0)
np.testing.assert_allclose(np.diff(d)[:-1], 30.0, atol=1e-6)
self.assertLessEqual(float(np.diff(d)[-1]), 30.0 + 1e-6)
self.assertAlmostEqual(float(d[-1]), 1000.0, delta=3.0)
self.assertAlmostEqual(float(lon[-1]), line_km(1.0)[-1][0], places=6)
def test_resample_short_part_keeps_both_ends(self):
lon, lat, d = E.resample([(0.0, 0.0), (0.0001, 0.0)], 30.0)
self.assertEqual(len(d), 2)
self.assertAlmostEqual(float(d[-1]), 11.12, delta=0.05)
def test_resample_ignores_repeated_points(self):
lon, lat, d = E.resample([(0.0, 0.0), (0.0, 0.0), (0.001, 0.0)], 30.0)
self.assertAlmostEqual(float(d[-1]), 111.2, delta=0.2)
self.assertTrue(np.all(np.diff(d) > 0))
class Profile(unittest.TestCase):
def test_smooth_keeps_a_constant_and_a_line(self):
np.testing.assert_allclose(E.smooth(np.full(20, 7.0), 5), 7.0)
ramp = np.arange(20.0)
np.testing.assert_allclose(E.smooth(ramp, 5)[2:-2], ramp[2:-2])
def test_smooth_shrinks_at_the_ends(self):
out = E.smooth(np.array([0.0, 10.0, 20.0, 30.0, 40.0]), 5)
self.assertAlmostEqual(float(out[0]), 10.0) # mean of 0, 10, 20
self.assertAlmostEqual(float(out[-1]), 30.0) # mean of 20, 30, 40
def test_smooth_window_one_changes_nothing_and_even_becomes_odd(self):
x = np.array([1.0, 5.0, 2.0, 8.0])
np.testing.assert_allclose(E.smooth(x, 1), x)
np.testing.assert_allclose(E.smooth(x, 2), E.smooth(x, 3))
def test_smooth_removes_a_spike(self):
x = np.zeros(21)
x[10] = 30.0
self.assertAlmostEqual(float(E.smooth(x, 3)[10]), 10.0)
def test_climb_plain_up_and_down(self):
up = np.linspace(0, 100, 50)
self.assertEqual(E.climb(up, 5.0), (100.0, 0.0))
self.assertEqual(E.climb(up[::-1], 5.0), (0.0, 100.0))
def test_climb_ignores_wiggles_below_the_threshold(self):
wiggle = np.tile([0.0, 4.0], 100) # 4 m wiggles
a, d = E.climb(wiggle, 5.0)
self.assertLessEqual(a, 4.0)
self.assertLessEqual(d, 4.0)
a, d = E.climb(wiggle * 2, 5.0) # 8 m wiggles count in full
self.assertGreater(a, 700.0)
def test_climb_counts_every_big_hill(self):
hills = np.tile(np.concatenate([np.linspace(0, 50, 25), np.linspace(50, 0, 25)]), 4)
a, d = E.climb(hills, 10.0)
self.assertAlmostEqual(a, 200.0)
self.assertAlmostEqual(d, 200.0)
def test_climb_net_change_is_within_the_threshold(self):
rng = np.random.default_rng(3)
e = np.cumsum(rng.normal(0, 3, 500))
a, d = E.climb(e, 8.0)
self.assertLessEqual(abs((a - d) - float(e[-1] - e[0])), 8.0)
def test_climb_threshold_shrinks_total(self):
rng = np.random.default_rng(4)
e = np.cumsum(rng.normal(0, 3, 2000))
totals = [sum(E.climb(e, t)) for t in (1.0, 5.0, 20.0)]
self.assertGreater(totals[0], totals[1])
self.assertGreater(totals[1], totals[2])
def test_climb_short_input(self):
self.assertEqual(E.climb(np.array([5.0]), 5.0), (0.0, 0.0))
self.assertEqual(E.climb(np.array([]), 5.0), (0.0, 0.0))
def test_thin_keeps_everything_when_small(self):
d = np.arange(10.0)
self.assertEqual(E.thin_profile(d, d * 2, 700), list(range(10)))
def test_thin_respects_the_limit_and_keeps_ends_and_extremes(self):
n = 5000
d = np.linspace(0, 100, n)
e = 500 * np.sin(d / 7.0) + 20 * np.sin(d * 3.1)
hi, lo = int(np.argmax(e)), int(np.argmin(e))
idx = E.thin_profile(d, e, 300, keep=[hi, lo])
self.assertLessEqual(len(idx), 300)
self.assertEqual(idx[0], 0)
self.assertEqual(idx[-1], n - 1)
self.assertIn(hi, idx)
self.assertIn(lo, idx)
self.assertEqual(idx, sorted(set(idx)))
# the thinned profile stays close to the full one
back = np.interp(d, d[idx], e[idx])
self.assertLess(float(np.abs(back - e).max()), 60.0)
def test_thin_is_deterministic(self):
d = np.linspace(0, 50, 3000)
e = np.cumsum(np.random.default_rng(1).normal(0, 2, 3000))
self.assertEqual(E.thin_profile(d, e, 200), E.thin_profile(d, e, 200))
class Summary(unittest.TestCase):
def parts(self):
d = np.arange(0.0, 6000.0, 30.0)
elev = 1000 + 400 * np.sin(d / 900.0) + (np.arange(len(d)) % 2) * 3.0
lon = -110.0 + d / 78000.0
lat = np.full(len(d), 45.0)
return [{"lon": lon, "lat": lat, "dist_m": d, "elev": elev}]
def test_facts(self):
out = E.summarise(self.parts(), "west-to-east", 6)
p = self.parts()[0]
self.assertEqual(out["highest"]["m"], int(round(p["elev"].max())))
self.assertEqual(out["lowest"]["m"], int(round(p["elev"].min())))
self.assertGreaterEqual(out["highest"]["m"], out["lowest"]["m"])
self.assertAlmostEqual(out["track_km"], 5.99, delta=0.1)
self.assertAlmostEqual(out["coverage"], 1.0, delta=0.01)
self.assertEqual(out["parts"], 1)
self.assertNotIn("part_starts_km", out)
self.assertGreater(out["ascent_m"], 0)
# the 3 m zig-zag is below the threshold and adds nothing
self.assertLess(out["ascent_m"], 1400)
prof = out["profile"]
dists = [x[0] for x in prof]
self.assertEqual(dists, sorted(set(dists)))
self.assertEqual(max(x[1] for x in prof), out["highest"]["m"])
self.assertEqual(min(x[1] for x in prof), out["lowest"]["m"])
def test_two_parts_are_not_joined(self):
a, b = self.parts()[0], self.parts()[0]
b = dict(b, elev=b["elev"] + 3000.0)
out = E.summarise([a, b], "west-to-east", 12)
one = E.summarise([a], "west-to-east", 6)
# no climb across the 3000 m jump between the parts
self.assertEqual(out["ascent_m"], one["ascent_m"] * 2)
self.assertEqual(out["parts"], 2)
self.assertEqual(len(out["part_starts_km"]), 1)
self.assertAlmostEqual(out["part_starts_km"][0], one["track_km"], delta=0.05)
def test_profile_distances_increase_except_at_a_part_start(self):
a = self.parts()[0]
out = E.summarise([a, dict(a), dict(a)], "west-to-east", 18)
dists = [p[0] for p in out["profile"]]
starts = out["part_starts_km"]
for x, y in zip(dists, dists[1:]):
self.assertTrue(y > x or (y == x and y in starts))
for s in starts:
self.assertIn(s, dists)
def test_profile_is_thinned(self):
d = np.arange(0.0, 600000.0, 30.0)
elev = 1000 + 800 * np.sin(d / 20000.0) + 50 * np.sin(d / 130.0)
part = {"lon": -110 + d / 78000.0, "lat": np.full(len(d), 45.0), "dist_m": d, "elev": elev}
out = E.summarise([part], "west-to-east", 600)
self.assertLessEqual(len(out["profile"]), E.PROFILE_POINTS)
def test_json_is_compact_and_repeatable(self):
out = E.summarise(self.parts(), "west-to-east", 6)
a, b = E.dumps(out), E.dumps(json.loads(E.dumps(out)))
self.assertEqual(a, b)
self.assertNotIn(" ", a.replace("Terrain Tiles", ""))
self.assertTrue(a.endswith("\n") and a.count("\n") == 1)
class Cache(unittest.TestCase):
def test_fetch_writes_once_then_reads_the_cache(self):
png = png_bytes(encode(np.full((256, 256), 50.0)))
calls = []
class Resp(io.BytesIO):
def __enter__(self):
return self
def __exit__(self, *a):
return False
def opener(req, timeout=0):
calls.append((req.full_url, req.get_header("User-agent")))
return Resp(png)
with tempfile.TemporaryDirectory() as d:
p1 = E.fetch_tile(d, 12, 666, 1435, opener)
p2 = E.fetch_tile(d, 12, 666, 1435, opener)
self.assertEqual(p1, p2)
self.assertTrue(p1.startswith(d))
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0][0], "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/12/666/1435.png")
self.assertNotIn("@", calls[0][1])
self.assertAlmostEqual(float(E.load_tile(p1)[0, 0]), 50.0, places=2)
def test_a_missing_tile_is_an_error_not_a_retry_loop(self):
def opener(req, timeout=0):
raise urllib.error.HTTPError(req.full_url, 404, "not found", {}, None)
with tempfile.TemporaryDirectory() as d:
with self.assertRaises(RuntimeError):
E.fetch_tile(d, 12, 1, 1, opener)
def test_store_reads_tiles_from_cache_without_network(self):
with tempfile.TemporaryDirectory() as d:
path = E.tile_path(d, 12, 5, 6)
os.makedirs(os.path.dirname(path))
with open(path, "wb") as f:
f.write(png_bytes(encode(np.full((256, 256), 321.0))))
store = E.TileStore(12, d)
store.prefetch({(5, 6)})
self.assertEqual(store.fetched, 0)
self.assertAlmostEqual(float(store.get(5, 6)[3, 3]), 321.0, places=2)
class WholeTrail(unittest.TestCase):
def test_flat_world_gives_flat_answers(self):
with tempfile.TemporaryDirectory() as d:
store = E.TileStore(12, d)
store.get = lambda x, y: np.full((256, 256), 250.0, dtype=np.float32)
store.prefetch = lambda needed: None
data = {"type": "FeatureCollection", "features": [
{"geometry": {"type": "LineString", "coordinates": [list(c) for c in line_km(5.0)]}}]}
doc = E.build("t", {"length_km": 10}, data, store, "2026-01-01")
self.assertEqual(doc["highest"]["m"], 250)
self.assertEqual(doc["lowest"]["m"], 250)
self.assertEqual((doc["ascent_m"], doc["descent_m"]), (0, 0))
self.assertAlmostEqual(doc["coverage"], 0.5, delta=0.01)
self.assertEqual(doc["orientation"], "west-to-east")
self.assertEqual(doc["source"]["zoom"], 12)
self.assertEqual(doc["source"]["computed"], "2026-01-01")
class WriteIfChanged(unittest.TestCase):
def test_keeps_the_date_when_nothing_else_changed(self):
doc = {"a": 1, "source": {"computed": "2026-11-13"}}
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "elevation.json")
self.assertTrue(E.write_if_changed(path, json.loads(json.dumps(doc))))
later = {"a": 1, "source": {"computed": "2027-01-01"}}
self.assertFalse(E.write_if_changed(path, later))
self.assertEqual(later["source"]["computed"], "2026-11-13")
changed = {"a": 2, "source": {"computed": "2027-01-01"}}
self.assertTrue(E.write_if_changed(path, changed))
with open(path, encoding="utf-8") as f:
self.assertEqual(json.load(f)["source"]["computed"], "2027-01-01")
if __name__ == "__main__":
unittest.main()
+234
View File
@@ -9,6 +9,7 @@ import sys
sys.dont_write_bytecode = True
import datetime
import importlib.util
import json
import math
@@ -25,6 +26,20 @@ DATA_LICENCES = {"us-gov-public-domain", "CC-BY-4.0", "CC-BY", "ODbL-1.0"}
LINE_POLICIES = {"open", "sold", "withheld", "unclear"}
NO_LINE_POLICIES = {"sold", "withheld", "unclear"}
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
HIKE_SHAPES = {"point-to-point", "loop", "network"}
HIKE_TERRAIN = {"alpine", "forest", "desert", "coast", "prairie", "canyon", "tundra",
"lakes", "farmland"}
HIKE_FACTS = {"summary", "official_url", "start", "end", "shape", "days", "season",
"high_point", "high_point_m", "terrain", "permit", "unfinished", "caution",
"months", "travel"}
HIKE_TRAVEL = {"trail", "trail-and-road", "some-cross-country", "mostly-cross-country"}
HIKE_KEYS = HIKE_FACTS | {"checked"}
ELEVATION_KEYS = {"highest", "lowest", "ascent_m", "descent_m", "track_km", "published_km",
"coverage", "parts", "orientation", "profile", "part_starts_km", "source"}
ELEVATION_REQUIRED = ELEVATION_KEYS - {"part_starts_km"}
ELEVATION_SOURCE_REQUIRED = ("model", "attribution", "zoom", "sample_spacing_m", "smoothing",
"computed")
ELEVATION_ORIENTATIONS = {"south-to-north", "west-to-east"}
spec = importlib.util.spec_from_file_location(
"build_index", os.path.join(ROOT, "tools", "build_index.py"))
@@ -87,6 +102,222 @@ def check_geometry(geom, where, errors):
return length
def check_hike(tid, rec, errors):
"""Check the optional [hike] table and its [[hike.source]] tables."""
hike = rec.get("hike")
if hike is None:
return
if not isinstance(hike, dict):
errors.append(f"{tid}: hike must be a table")
return
def text(name):
value = hike[name]
if not isinstance(value, str) or not value.strip():
errors.append(f"{tid}: hike.{name} must be a non-empty string")
return False
return True
for name in sorted(set(hike) - HIKE_KEYS - {"source"}):
errors.append(f"{tid}: hike.{name} is not a known field")
for name in ("summary", "official_url", "start", "end", "season", "high_point",
"permit", "unfinished", "caution"):
if name in hike:
text(name)
if "official_url" in hike and not str(hike["official_url"]).startswith(("https://", "http://")):
errors.append(f"{tid}: hike.official_url must be an http(s) URL")
if "shape" in hike and hike["shape"] not in HIKE_SHAPES:
errors.append(
f"{tid}: hike.shape must be one of {', '.join(sorted(HIKE_SHAPES))}, "
f"not {hike['shape']!r}")
if "days" in hike:
days = hike["days"]
ints = (isinstance(days, list) and len(days) == 2
and all(isinstance(d, int) and not isinstance(d, bool) and d > 0 for d in days))
if not ints:
errors.append(f"{tid}: hike.days must be two positive integers [fewest, most]")
elif days[0] > days[1]:
errors.append(f"{tid}: hike.days {days} has the fewest days after the most")
if "travel" in hike and hike["travel"] not in HIKE_TRAVEL:
errors.append(
f"{tid}: hike.travel must be one of {', '.join(sorted(HIKE_TRAVEL))}, "
f"not {hike['travel']!r}")
if "months" in hike:
months = hike["months"]
ok = (isinstance(months, list) and months
and all(isinstance(m, int) and not isinstance(m, bool) and 1 <= m <= 12
for m in months))
if not ok:
errors.append(f"{tid}: hike.months must be a list of month numbers from 1 to 12")
elif len(set(months)) != len(months):
errors.append(f"{tid}: hike.months repeats a month")
if "high_point_m" in hike:
metres = hike["high_point_m"]
if (not isinstance(metres, int) or isinstance(metres, bool)
or not -100 <= metres <= 6200):
errors.append(f"{tid}: hike.high_point_m must be an integer from -100 to 6200")
if "terrain" in hike:
terrain = hike["terrain"]
if not isinstance(terrain, list) or not 1 <= len(terrain) <= 3:
errors.append(f"{tid}: hike.terrain must be a list of one to three words")
else:
for word in terrain:
if word not in HIKE_TERRAIN:
errors.append(
f"{tid}: hike.terrain word {word!r} is not one of "
f"{', '.join(sorted(HIKE_TERRAIN))}")
if len(set(terrain)) != len(terrain):
errors.append(f"{tid}: hike.terrain repeats a word")
if not DATE_RE.match(str(hike.get("checked", ""))):
errors.append(f"{tid}: hike.checked must be a date (YYYY-MM-DD)")
else:
try:
datetime.date.fromisoformat(hike["checked"])
except ValueError:
errors.append(f"{tid}: hike.checked {hike['checked']!r} is not a real date")
sources = hike.get("source")
covered = set()
if not isinstance(sources, list) or not sources:
errors.append(f"{tid}: hike is present but there is no [[hike.source]] table")
sources = []
for i, s in enumerate(sources, 1):
if not isinstance(s, dict):
errors.append(f"{tid}: hike source {i} must be a table")
continue
for name in sorted(set(s) - {"url", "publisher", "facts"}):
errors.append(f"{tid}: hike source {i} has unknown field {name}")
if not str(s.get("url", "")).startswith(("https://", "http://")):
errors.append(f"{tid}: hike source {i} url must be an http(s) URL")
if not str(s.get("publisher", "")).strip():
errors.append(f"{tid}: hike source {i} is missing publisher")
facts = s.get("facts")
if not isinstance(facts, list) or not facts:
errors.append(f"{tid}: hike source {i} facts must be a non-empty list")
continue
for fact in facts:
if fact not in HIKE_FACTS:
errors.append(f"{tid}: hike source {i} names {fact!r}, which is not a hike field")
elif fact == "high_point":
covered.update(("high_point", "high_point_m"))
else:
covered.add(fact)
for name in sorted(set(hike) & HIKE_KEYS - {"checked"}) if sources else []:
if name not in covered:
errors.append(f"{tid}: hike.{name} is not named in the facts of any hike source")
def check_elevation(tid, tdir, rec, errors):
"""Check <id>/elevation.json where it is present."""
path = os.path.join(tdir, "elevation.json")
if not os.path.isfile(path):
return
where = f"{tid}/elevation.json"
try:
with open(path, encoding="utf-8") as f:
doc = json.load(f)
except Exception as e: # noqa: BLE001
errors.append(f"{where}: does not parse: {e}")
return
if not isinstance(doc, dict):
errors.append(f"{where}: top level must be an object")
return
if not os.path.isfile(os.path.join(tdir, "line.geojson")):
errors.append(f"{where}: present but the trail has no track (line.geojson)")
for name in sorted(ELEVATION_REQUIRED - set(doc)):
errors.append(f"{where}: missing {name}")
for name in sorted(set(doc) - ELEVATION_KEYS):
errors.append(f"{where}: {name} is not a known field")
def number(value, low, high):
return (isinstance(value, (int, float)) and not isinstance(value, bool)
and low <= value <= high)
points = {}
for name in ("highest", "lowest"):
p = doc.get(name)
if name not in doc:
continue
if not isinstance(p, dict) or set(p) != {"m", "lon", "lat"}:
errors.append(f"{where}: {name} must hold m, lon and lat")
continue
if not number(p["m"], -500, 9000):
errors.append(f"{where}: {name}.m must be a number from -500 to 9000 metres")
if not number(p["lon"], -180, 180) or not number(p["lat"], -90, 90):
errors.append(f"{where}: {name} has a longitude or latitude out of range")
points[name] = p["m"]
if len(points) == 2 and number(points["highest"], -500, 9000) and number(points["lowest"], -500, 9000):
if points["highest"] < points["lowest"]:
errors.append(f"{where}: highest {points['highest']} is below lowest {points['lowest']}")
for name in ("ascent_m", "descent_m"):
if name in doc and not number(doc[name], 0, 2_000_000):
errors.append(f"{where}: {name} must be a number from 0 to 2000000")
track_km = doc.get("track_km")
if "track_km" in doc and not number(track_km, 0.01, 100_000):
errors.append(f"{where}: track_km must be a positive number of kilometres")
track_km = None
published = doc.get("published_km")
if "published_km" in doc:
if published != rec.get("length_km"):
errors.append(f"{where}: published_km {published!r} is not the record's length_km "
f"{rec.get('length_km')!r}")
elif published and track_km and "coverage" in doc:
if not number(doc["coverage"], 0, 10) or abs(doc["coverage"] - track_km / published) > 0.01:
errors.append(f"{where}: coverage {doc['coverage']!r} is not track_km / published_km")
parts = doc.get("parts")
if "parts" in doc and (not isinstance(parts, int) or isinstance(parts, bool) or parts < 1):
errors.append(f"{where}: parts must be a whole number of 1 or more")
parts = None
if doc.get("orientation") not in ELEVATION_ORIENTATIONS and "orientation" in doc:
errors.append(f"{where}: orientation must be one of "
f"{', '.join(sorted(ELEVATION_ORIENTATIONS))}")
if "part_starts_km" in doc:
starts = doc["part_starts_km"]
if (not isinstance(starts, list) or not all(number(x, 0, 100_000) for x in starts)
or starts != sorted(starts)
or (parts is not None and len(starts) != parts - 1)):
errors.append(f"{where}: part_starts_km must be a list, never decreasing, with one "
"entry for each part after the first")
elif parts and parts > 1:
errors.append(f"{where}: {parts} parts but no part_starts_km")
profile = doc.get("profile")
if "profile" in doc:
ok = (isinstance(profile, list) and 2 <= len(profile) <= 1500
and all(isinstance(p, list) and len(p) == 2 and number(p[0], 0, 100_000)
and number(p[1], -500, 9000) for p in profile))
if not ok:
errors.append(f"{where}: profile must be 2 to 1500 [distance_km, elevation_m] pairs")
else:
dists = [p[0] for p in profile]
starts = doc.get("part_starts_km") if isinstance(doc.get("part_starts_km"), list) else []
# distances increase; the first point of a later part may repeat the
# distance of the point before it (the gap between two parts)
if any(b < a or (b == a and b not in starts) for a, b in zip(dists, dists[1:])):
errors.append(f"{where}: profile distances must increase")
if track_km and dists[-1] > track_km + 0.1:
errors.append(f"{where}: profile runs past track_km")
if len(points) == 2:
top, bottom = max(p[1] for p in profile), min(p[1] for p in profile)
if top > points["highest"] + 1 or bottom < points["lowest"] - 1:
errors.append(f"{where}: profile lies outside the highest and lowest points")
src = doc.get("source")
if "source" in doc:
if not isinstance(src, dict):
errors.append(f"{where}: source must be an object")
else:
for name in ELEVATION_SOURCE_REQUIRED:
if src.get(name) in (None, ""):
errors.append(f"{where}: source.{name} is missing")
if not isinstance(src.get("zoom"), int) or not 0 <= src.get("zoom", -1) <= 15:
errors.append(f"{where}: source.zoom must be a whole number from 0 to 15")
if not number(src.get("sample_spacing_m"), 1, 1000):
errors.append(f"{where}: source.sample_spacing_m must be a number of metres")
if not DATE_RE.match(str(src.get("computed", ""))):
errors.append(f"{where}: source.computed must be a date (YYYY-MM-DD)")
def main():
errors = []
trail_ids = build_index.trail_dirs(ROOT)
@@ -258,6 +489,9 @@ def main():
if guides:
errors.append(f"{tid}: [[guide]] present but kind is not \"route\"")
check_hike(tid, rec, errors)
check_elevation(tid, tdir, rec, errors)
for dirpath, dirnames, filenames in os.walk(ROOT):
if ".git" in dirpath:
dirnames[:] = []