Make the monthly place check compare like with like, fail loudly on a bad outline download, and bring twelve placements up to date
The 2026-12-01 run reported 440 differences, but the outlines had not changed: a fresh download on 2026-12-03 matched the 2026-11-20 files byte for byte. The check counted every new download date as a difference, counted stated placements of trails with no track before but not after (so Zion, Arches and others read as "down to 0 trails"), and let the Montana and British Columbia Glacier parks push each other to suffixed slugs. A download date alone is no longer a difference; both sides of the 3-trail line count stated placements; Glacier National Park, Montana keeps the plain slug. An ArcGIS download now asks the service for its count and must bring exactly that many features, a service error body is raised, a source that yields no outlines is an error, and a registered place whose outline is gone stops the check naming it (exit 3), never "0 trails". The twelve real differences left are applied: ten trails gain a place the tool measures (Sheltowee Trace in Big South Fork; nine trails in the parent range left when a child range was dropped on 2026-11-20), and two wilderness twins of a same-named park are taken off the Brooks Range Traverse and the Guadalupe Ridge Trail and out of places.toml. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
05284f87a1
commit
41019c81e1
16 files changed
+402
-78
No files matched your search
+115
-35
@@ -195,33 +195,68 @@ def cache_dir():
|
||||
return d
|
||||
|
||||
|
||||
class SourceError(RuntimeError):
|
||||
"""An outline source failed, came back empty, or came back short. The check stops on
|
||||
this, naming the source: a missing outline must never read as a trail in no place."""
|
||||
|
||||
|
||||
def _download(url, dest):
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "longhikes place_trails.py"})
|
||||
got = 0
|
||||
with urllib.request.urlopen(req, timeout=600) as r, open(dest + ".part", "wb") as f:
|
||||
want = r.headers.get("Content-Length")
|
||||
while True:
|
||||
chunk = r.read(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
got += len(chunk)
|
||||
f.write(chunk)
|
||||
if got == 0 or (want and int(want) != got):
|
||||
os.remove(dest + ".part")
|
||||
raise SourceError(f"{url}: download came back with {got} bytes"
|
||||
+ (f", not the {want} the server announced" if want else ""))
|
||||
os.rename(dest + ".part", dest)
|
||||
|
||||
|
||||
def _arcgis_get(query_url, params):
|
||||
"""One ArcGIS query as JSON. ArcGIS answers some failures with HTTP 200 and an
|
||||
{"error": ...} body; that is raised, not read as no features."""
|
||||
url = query_url + "?" + urllib.parse.urlencode(params)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "longhikes place_trails.py"})
|
||||
with urllib.request.urlopen(req, timeout=300) as r:
|
||||
page = json.load(r)
|
||||
if not isinstance(page, dict) or page.get("error"):
|
||||
raise SourceError(f"{query_url}: the service answered with an error: "
|
||||
f"{(page or {}).get('error') if isinstance(page, dict) else page!r}")
|
||||
return page
|
||||
|
||||
|
||||
def _arcgis_geojson(query_url, where, out_fields, dest):
|
||||
"""Page an ArcGIS query into one cached GeoJSON file, in lon/lat."""
|
||||
"""Page an ArcGIS query into one cached GeoJSON file, in lon/lat.
|
||||
|
||||
The service is first asked how many features match; the download must bring exactly
|
||||
that many, or it raises. A page is never taken as the last one just because it is short
|
||||
(a service may cap a page below the size asked for); paging stops when a page is empty
|
||||
or the count is reached."""
|
||||
count = _arcgis_get(query_url, {"where": where, "returnCountOnly": "true", "f": "json"})
|
||||
want = count.get("count")
|
||||
if not isinstance(want, int) or want <= 0:
|
||||
raise SourceError(f"{query_url}: the service reports {want!r} features for {where!r}")
|
||||
features, offset = [], 0
|
||||
while True:
|
||||
while len(features) < want:
|
||||
params = {"where": where, "outFields": out_fields, "returnGeometry": "true",
|
||||
"outSR": "4326", "f": "geojson", "resultRecordCount": "1000",
|
||||
"resultOffset": str(offset), "orderByFields": "OBJECTID"}
|
||||
url = query_url + "?" + urllib.parse.urlencode(params)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "longhikes place_trails.py"})
|
||||
with urllib.request.urlopen(req, timeout=300) as r:
|
||||
page = json.load(r)
|
||||
got = page.get("features") or []
|
||||
features.extend(got)
|
||||
if len(got) < 1000:
|
||||
got = _arcgis_get(query_url, params).get("features") or []
|
||||
if not got:
|
||||
break
|
||||
features.extend(got)
|
||||
offset += len(got)
|
||||
if len(features) != want:
|
||||
raise SourceError(f"{query_url}: downloaded {len(features)} features, but the service "
|
||||
f"reports {want}")
|
||||
if not any(f.get("geometry") for f in features):
|
||||
raise SourceError(f"{query_url}: every feature came back with no geometry")
|
||||
with open(dest, "w", encoding="utf-8") as f:
|
||||
json.dump({"type": "FeatureCollection", "features": features}, f)
|
||||
|
||||
@@ -338,8 +373,7 @@ def _read_vector(path, columns=None, bbox=None):
|
||||
import pyogrio
|
||||
import pyogrio.raw
|
||||
from pyproj import Transformer
|
||||
from shapely import from_wkb
|
||||
from shapely.ops import transform
|
||||
from shapely import from_wkb, transform
|
||||
if str(path).endswith(".zip"):
|
||||
import zipfile
|
||||
with zipfile.ZipFile(path) as z:
|
||||
@@ -361,7 +395,7 @@ def _read_vector(path, columns=None, bbox=None):
|
||||
for row, wkb in zip(rows, geoms):
|
||||
g = from_wkb(wkb) if wkb is not None else None
|
||||
if g is not None and transformer is not None:
|
||||
g = transform(transformer.transform, g)
|
||||
g = transform(g, transformer.transform, interleaved=False)
|
||||
row["_geometry"] = g if g is None or g.is_valid else g.buffer(0)
|
||||
return rows
|
||||
|
||||
@@ -491,6 +525,9 @@ def default_allowlist_path():
|
||||
# permanent, so this is a decision made once.
|
||||
SLUG_KEEPS_PLAIN = {
|
||||
("wilderness", "wilderness-connect", "239"), # Hells Canyon Wilderness, Idaho and Oregon
|
||||
# Glacier National Park, Montana; CPCAD's "Glacier National Park Of Canada" (British
|
||||
# Columbia, no trails here) cleans to the same name and takes glacier-national-park-bc.
|
||||
("park", "nps", "GLAC"),
|
||||
}
|
||||
|
||||
|
||||
@@ -590,6 +627,15 @@ def merge_same_name(outlines):
|
||||
return out
|
||||
|
||||
|
||||
def _read_source(key, cache):
|
||||
"""A source's outlines, or SourceError when it yields none."""
|
||||
path, _ver = fetch(SOURCES[key], cache)
|
||||
rows = SOURCES[key].read(path)
|
||||
if not rows:
|
||||
raise SourceError(f"{key} ({SOURCES[key].url}): the downloaded file holds no outlines")
|
||||
return rows
|
||||
|
||||
|
||||
def catalogue(cache, allowlist=None):
|
||||
"""The outlines to measure: parks whole, wilderness whole, ranges allow-listed only."""
|
||||
allowlist = allowlist if allowlist is not None else load_allowlist(default_allowlist_path())
|
||||
@@ -598,8 +644,8 @@ def catalogue(cache, allowlist=None):
|
||||
joined = [p for p in allowlist["park"] if isinstance(p.get("source_id"), list)]
|
||||
joined_ids = {str(s) for p in joined for s in p["source_id"]}
|
||||
out = []
|
||||
path, _ver = fetch(SOURCES["nps"], cache)
|
||||
for o in SOURCES["nps"].read(path):
|
||||
nps = _read_source("nps", cache)
|
||||
for o in nps:
|
||||
if str(o.source_id) in joined_ids:
|
||||
continue
|
||||
extra = extras.get(str(o.source_id))
|
||||
@@ -610,17 +656,15 @@ def catalogue(cache, allowlist=None):
|
||||
o.where_hand = tuple(extra.get("where") or ())
|
||||
out.append(o)
|
||||
for p in joined:
|
||||
parts = [o for o in SOURCES["nps"].read(path) if str(o.source_id) in [str(s) for s in p["source_id"]]]
|
||||
parts = [o for o in nps if str(o.source_id) in [str(s) for s in p["source_id"]]]
|
||||
if parts:
|
||||
out.append(Outline("park", "nps", [str(s) for s in p["source_id"]],
|
||||
p.get("name") or parts[0].name,
|
||||
sorted({h for o in parts for h in o.state_codes_hint}),
|
||||
_union_geoms(o.geometry for o in parts),
|
||||
slug=p.get("slug") or "", where_hand=tuple(p.get("where") or ())))
|
||||
path, _ver = fetch(SOURCES["cpcad"], cache)
|
||||
out.extend(SOURCES["cpcad"].read(path))
|
||||
path, _ver = fetch(SOURCES["wilderness-connect"], cache)
|
||||
out.extend(SOURCES["wilderness-connect"].read(path))
|
||||
out.extend(_read_source("cpcad", cache))
|
||||
out.extend(_read_source("wilderness-connect", cache))
|
||||
wanted = {str(r.get("gmba_id")): r for r in allowlist["range"]}
|
||||
if wanted:
|
||||
for g in gmba_ranges(cache):
|
||||
@@ -642,8 +686,7 @@ _GMBA_CACHE = {}
|
||||
|
||||
def gmba_ranges(cache):
|
||||
if cache not in _GMBA_CACHE:
|
||||
path, _ver = fetch(SOURCES["gmba-v2"], cache)
|
||||
_GMBA_CACHE[cache] = SOURCES["gmba-v2"].read(path)
|
||||
_GMBA_CACHE[cache] = _read_source("gmba-v2", cache)
|
||||
return _GMBA_CACHE[cache]
|
||||
|
||||
|
||||
@@ -1239,22 +1282,61 @@ def stamp_none(root, rid, today):
|
||||
_save(doc, path)
|
||||
|
||||
|
||||
def missing_from_sources(entries, outlines):
|
||||
"""Registry entries measured from a track whose outline the sources no longer hold, as
|
||||
"kind/slug (source id)". An outline that went missing (a failed or short download, a
|
||||
renamed field, a moved layer) is an error to fix, never a place with no trails."""
|
||||
have = set()
|
||||
for o in outlines:
|
||||
for i in (o.source_id if isinstance(o.source_id, list) else [o.source_id]):
|
||||
have.add((o.source, str(i)))
|
||||
out = []
|
||||
for e in entries:
|
||||
if e.get("source") not in SOURCES:
|
||||
continue
|
||||
ids = e.get("source_id")
|
||||
for i in (ids if isinstance(ids, list) else [ids]):
|
||||
if (e["source"], str(i)) not in have:
|
||||
out.append(f"{e.get('kind')}/{e.get('slug')} ({e['source']} {i})")
|
||||
return out
|
||||
|
||||
|
||||
def check(root, cache, outlines=None, versions=None, records=None):
|
||||
"""Re-measure every track against the current outlines; one difference per line."""
|
||||
"""Re-measure every track against the current outlines; one difference per line.
|
||||
|
||||
A source_version that differs is not a difference: every source here is versioned by
|
||||
its download date, so a fresh download always differs. What the outline does to the
|
||||
trails is what is compared; `apply` stamps the new date when a difference is applied.
|
||||
`versions` is accepted and unused, for callers that still pass it."""
|
||||
if outlines is None:
|
||||
outlines = catalogue(cache)
|
||||
if versions is None:
|
||||
versions = source_versions(cache)
|
||||
if records is None:
|
||||
records = load_records(root)
|
||||
lost = missing_from_sources(registry_entries(root), outlines)
|
||||
if lost:
|
||||
raise SourceError("the sources no longer hold the outline of " + str(len(lost))
|
||||
+ " registered place(s): " + ", ".join(lost))
|
||||
p = propose(records, outlines, {(e.get("kind"), e.get("slug")): e.get("where")
|
||||
for e in registry_entries(root)})
|
||||
diffs = []
|
||||
current_counts = {}
|
||||
# Both counts are taken the same way: a record's places as stored (no parents), with
|
||||
# the track's measured places in place of its stored track places. Stated places (hand
|
||||
# placements from a cited page) are on both sides; a check that left them off one side
|
||||
# reported every park held up by stated trails as losing them.
|
||||
current_counts, new_counts = {}, {}
|
||||
for r in records:
|
||||
for pl in (r.get("rec") or {}).get("place") or []:
|
||||
current_counts[(pl.get("kind"), pl.get("slug"))] = \
|
||||
current_counts.get((pl.get("kind"), pl.get("slug")), 0) + 1
|
||||
rec = r.get("rec") or {}
|
||||
stored = {(pl.get("kind"), pl.get("slug")) for pl in rec.get("place") or []}
|
||||
for k in stored:
|
||||
current_counts[k] = current_counts.get(k, 0) + 1
|
||||
if r.get("track") is None:
|
||||
now = stored
|
||||
else:
|
||||
now = {(pl.get("kind"), pl.get("slug")) for pl in rec.get("place") or []
|
||||
if pl.get("basis") != "track"}
|
||||
now |= {k for k, _km in p.per_trail.get(r["id"], [])}
|
||||
for k in now:
|
||||
new_counts[k] = new_counts.get(k, 0) + 1
|
||||
for r in records:
|
||||
rec = r.get("rec") or {}
|
||||
if r.get("track") is None:
|
||||
@@ -1272,7 +1354,6 @@ def check(root, cache, outlines=None, versions=None, records=None):
|
||||
tdir = os.path.join(root, r["id"])
|
||||
if rec.get("places_track") and line_file_of(tdir) and track_hash(tdir) != rec["places_track"]:
|
||||
diffs.append(f"{r['id']}: the track has changed since its places were measured")
|
||||
new_counts = {k: len(h.trails) for k, h in p.per_place.items()}
|
||||
for k in sorted(set(current_counts) | set(new_counts)):
|
||||
was, now = current_counts.get(k, 0) >= 3, new_counts.get(k, 0) >= 3
|
||||
if was != now:
|
||||
@@ -1287,11 +1368,6 @@ def check(root, cache, outlines=None, versions=None, records=None):
|
||||
for k in sorted(doubled_places(final, shown)):
|
||||
diffs.append(f"{k[0]}/{k[1]}: holds exactly the trails of a park of the same name; "
|
||||
f"list the park only")
|
||||
for e in registry_entries(root):
|
||||
v = versions.get(e.get("source"))
|
||||
if v and e.get("source_version") and e["source_version"] != v:
|
||||
diffs.append(f"{e.get('kind')}/{e.get('slug')}: source_version changed "
|
||||
f"from {e['source_version']} to {v}")
|
||||
return diffs
|
||||
|
||||
|
||||
@@ -1393,7 +1469,11 @@ def main(argv=None):
|
||||
return 1
|
||||
return 0
|
||||
if cmd == "--check":
|
||||
diffs = check(ROOT, cache_dir())
|
||||
try:
|
||||
diffs = check(ROOT, cache_dir())
|
||||
except SourceError as e:
|
||||
print(f"place_trails.py: an outline source failed: {e}", file=sys.stderr)
|
||||
return 3
|
||||
for d in diffs:
|
||||
print(d)
|
||||
print(f"{len(diffs)} difference(s)" if diffs else "no differences")
|
||||
|
||||
Reference in new issue
Block a user