diff --git a/.gitignore b/.gitignore index 2f005a6..a9be128 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ web/.cache/ # Agent worktrees .claude/worktrees/ + +.venv-places/ diff --git a/tools/place_trails.py b/tools/place_trails.py new file mode 100644 index 0000000..8a8dbaa --- /dev/null +++ b/tools/place_trails.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Place every trail: measure tracks against published park, wilderness and range outlines. + +This tool is not part of the site build. It is the only file in the repository that may use +libraries outside the Python standard library (shapely, pyproj, pyogrio). Install them in +the venv this tool names, never system-wide: + + python3 -m venv .venv-places + .venv-places/bin/pip install -r tools/place_trails.requirements.txt + .venv-places/bin/python tools/place_trails.py --help + +A trail is in a place when at least 1 mile (1.609344 km) of its main track lies inside the +outline. Alternates never count. Outlines are downloaded into a cache outside the repo +($PLACES_CACHE, default $XDG_CACHE_HOME/longhikes-places) and are never committed. +""" +import json +import os +import sys +import tomllib + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +import check_places # noqa: E402 + +MIN_KM = 1.609344 # exactly 1 mile + +_GEOD = None +_SHAPELY = None + + +def _need_shapely(): + """Import shapely and pyproj, or exit with the install line.""" + global _GEOD, _SHAPELY + if _SHAPELY is None: + try: + import shapely + from pyproj import Geod + except ImportError: + sys.exit("place_trails.py needs shapely, pyproj and pyogrio, which the site build " + "never uses. Install them in this tool's venv:\n" + " python3 -m venv .venv-places\n" + " .venv-places/bin/pip install -r tools/place_trails.requirements.txt") + _SHAPELY = shapely + _GEOD = Geod(ellps="WGS84") + return _SHAPELY + + +def line_file_of(rec_dir): + with open(os.path.join(rec_dir, "trail.toml"), "rb") as f: + return str(tomllib.load(f).get("source", {}).get("line_file") or "") + + +def track_hash(rec_dir): + """The record's track hash: the same value the validator checks.""" + return check_places.track_hash(os.path.join(rec_dir, line_file_of(rec_dir))) + + +def main_track(rec_dir): + """The record's main track as a shapely MultiLineString, or None with no track. + + Only the file source.line_file names is read; alternates.geojson and any + line-.geojson are never touched.""" + shapely = _need_shapely() + name = line_file_of(rec_dir) + if not name: + return None + with open(os.path.join(rec_dir, name), encoding="utf-8") as f: + data = json.load(f) + lines = [] + for feat in data.get("features", []): + geom = shapely.geometry.shape(feat["geometry"]) + if geom.geom_type == "LineString": + lines.append(geom) + elif geom.geom_type == "MultiLineString": + lines.extend(geom.geoms) + elif geom.geom_type == "GeometryCollection": + lines.extend(g for g in geom.geoms if g.geom_type in ("LineString", "MultiLineString")) + if not lines: + return None + flat = [] + for g in lines: + flat.extend(g.geoms if g.geom_type == "MultiLineString" else [g]) + return shapely.geometry.MultiLineString(flat) + + +def _geodesic_km(geom): + """Length in km of every line part of a lon/lat geometry, on the WGS84 ellipsoid.""" + if geom.is_empty: + return 0.0 + if geom.geom_type == "LineString": + coords = list(geom.coords) + total = 0.0 + for (x1, y1), (x2, y2) in zip(coords, coords[1:]): + total += _GEOD.inv(x1, y1, x2, y2)[2] + return total / 1000.0 + if geom.geom_type in ("MultiLineString", "GeometryCollection"): + return sum(_geodesic_km(g) for g in geom.geoms) + return 0.0 # points where a track only touches a boundary + + +def km_inside(track, outline): + """Kilometres of `track` inside `outline`, summed over every piece, holes respected.""" + _need_shapely() + return _geodesic_km(track.intersection(outline)) + + +def box_of(outline): + """[west, south, east, north], rounded to 2 decimals as places.toml stores it.""" + return [round(float(v), 2) for v in outline.bounds] + + +HELP = __doc__ + """ +Subcommands (see the plan, Ship 1): propose, candidates, apply, stated, stamp, --check. +""" + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + if not argv or argv[0] in ("--help", "-h", "help"): + print(HELP) + return 0 + print(f"place_trails.py: no subcommand {argv[0]!r} yet", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/place_trails.requirements.txt b/tools/place_trails.requirements.txt new file mode 100644 index 0000000..509b684 --- /dev/null +++ b/tools/place_trails.requirements.txt @@ -0,0 +1,3 @@ +shapely>=2.0 +pyproj>=3.6 +pyogrio>=0.7 diff --git a/tools/tests/test_place_trails.py b/tools/tests/test_place_trails.py new file mode 100644 index 0000000..2e54f7a --- /dev/null +++ b/tools/tests/test_place_trails.py @@ -0,0 +1,94 @@ +"""Tests for tools/place_trails.py. Needs the tool's venv (.venv-places); with the system +Python the whole file is skipped, not failed. No network: synthetic outlines and tracks. + + .venv-places/bin/python -m unittest discover tools/tests -p "test_place_trails.py" +""" +import json +import os +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True +TOOLS = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +ROOT = os.path.dirname(TOOLS) +sys.path.insert(0, TOOLS) + +try: + import shapely # noqa: F401 + HAVE = True +except ImportError: + HAVE = False + +if HAVE: + from shapely.geometry import LineString, MultiLineString, Polygon + import check_places as C + import place_trails as P + +# At latitude 43, 0.0063 degrees of latitude is about 0.70 km. +BOX = None # built in setUp when shapely is there + + +def write_track(d, name, lines): + feats = [{"type": "Feature", "properties": {}, + "geometry": {"type": "LineString", "coordinates": line}} for line in lines] + with open(os.path.join(d, name), "w") as f: + json.dump({"type": "FeatureCollection", "features": feats}, f) + + +def write_record(d, line_file="line.geojson"): + with open(os.path.join(d, "trail.toml"), "w") as f: + f.write(f'id = "x"\n[source]\nline_file = "{line_file}"\n') + + +@unittest.skipUnless(HAVE, "shapely (the .venv-places venv) is not installed") +class GeometryTest(unittest.TestCase): + def setUp(self): + self.box = Polygon([(-110.0, 43.0), (-109.0, 43.0), (-109.0, 44.0), (-110.0, 44.0)]) + + def test_pieces_inside_are_summed(self): + parts = [LineString([(-109.5 + 0.1 * i, 43.5), (-109.5 + 0.1 * i, 43.5063)]) for i in range(3)] + km = P.km_inside(MultiLineString(parts), self.box) + self.assertAlmostEqual(km, 2.1, delta=0.15) + self.assertGreater(km, P.MIN_KM) + + def test_a_skimming_track_is_under_the_threshold(self): + # about 1.5 km inside + track = LineString([(-109.5, 43.5), (-109.5, 43.5135)]) + km = P.km_inside(track, self.box) + self.assertAlmostEqual(km, 1.5, delta=0.1) + self.assertLess(km, P.MIN_KM) + + def test_a_hole_is_not_inside(self): + hole = [(-109.6, 43.4), (-109.4, 43.4), (-109.4, 43.6), (-109.6, 43.6)] + outline = Polygon(self.box.exterior.coords, [hole]) + track = LineString([(-109.5, 43.45), (-109.5, 43.55)]) + self.assertEqual(P.km_inside(track, outline), 0.0) + + def test_alternates_are_ignored(self): + with tempfile.TemporaryDirectory() as d: + write_record(d) + write_track(d, "line.geojson", [[[-108.0, 43.5], [-108.0, 43.51]]]) # outside + write_track(d, "alternates.geojson", [[[-109.5, 43.1], [-109.5, 43.9]]]) # long, inside + track = P.main_track(d) + self.assertIsNotNone(track) + self.assertEqual(P.km_inside(track, self.box), 0.0) + + def test_a_record_with_no_line_file_has_no_track(self): + with tempfile.TemporaryDirectory() as d: + write_record(d, line_file="") + self.assertIsNone(P.main_track(d)) + + def test_box_of_is_west_south_east_north_rounded(self): + outline = Polygon([(-110.004, 42.501), (-108.499, 42.501), (-108.499, 43.499), (-110.004, 43.499)]) + self.assertEqual(P.box_of(outline), [-110.0, 42.5, -108.5, 43.5]) + + def test_track_hash_matches_the_validators(self): + with tempfile.TemporaryDirectory() as d: + write_record(d) + write_track(d, "line.geojson", [[[-109.5, 43.5], [-109.4, 43.5]]]) + self.assertEqual(P.track_hash(d), C.track_hash(os.path.join(d, "line.geojson"))) + + +if __name__ == "__main__": + unittest.main()