Add the season research brief and the batches

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 09:51:51 -07:00
1 parent 03c2611036
commit 157f268974
3 files changed
+276

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""List the trails with no season and split them into batches for researchers.
Python 3 standard library only. Run from the repository root:
python3 tools/season_batches.py [--n 10] [--dir DIR]
Writes <staging>/season/batches/season-NN.txt, one trail id per line, and prints
the batch count and the number of trails. A batch holds trails of one region
group; a group of more than the batch size is split, and a leftover of fewer
than five joins a neighbouring batch that has room.
See docs/superpowers/plans/2026-11-20-season-on-every-trail.md.
"""
import sys
sys.dont_write_bytecode = True
import argparse
import os
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import refresh # noqa: E402
# Ordered so that neighbouring groups are neighbours on the map.
REGION_GROUPS = {
"west coast": ("CA", "OR", "WA", "AK", "HI"),
"interior west": ("ID", "NV", "UT"),
"southwest": ("AZ", "NM", "TX"),
"Rockies": ("CO", "WY", "MT"),
"plains and midwest": ("ND", "SD", "NE", "KS", "OK", "MN", "IA", "MO", "WI", "IL", "IN", "MI", "OH"),
"northeast": ("ME", "NH", "VT", "MA", "RI", "CT", "NY", "NJ", "PA", "DE", "MD", "DC", "WV"),
"southeast": ("VA", "NC", "SC", "GA", "FL", "AL", "MS", "TN", "KY", "LA", "AR"),
"Canada west": ("BC", "AB", "SK", "MB", "YT"),
"Canada east and north": ("ON", "QC", "NB", "NS", "PE", "NL", "NT", "NU"),
}
OTHER = "other"
MIN_BATCH = 5
def group_of(rec):
"""The region group of a record's first region code (OTHER when unknown)."""
for code in rec.get("regions") or []:
for name, codes in REGION_GROUPS.items():
if code in codes:
return name
break
return OTHER
def _records(root):
for tid in refresh.trail_ids(root):
yield tid, refresh.load_toml(os.path.join(root, tid, "trail.toml"))
def missing_ids(root):
"""Ids of the records with no hike.season, sorted."""
return sorted(tid for tid, rec in _records(root) if not (rec.get("hike") or {}).get("season"))
def batches(root, size=10):
by_group = {}
for tid, rec in _records(root):
if not (rec.get("hike") or {}).get("season"):
by_group.setdefault(group_of(rec), []).append(tid)
chunks = []
for name in list(REGION_GROUPS) + [OTHER]:
ids = sorted(by_group.get(name, []))
chunks += [ids[i:i + size] for i in range(0, len(ids), size)]
out = []
carry = None # a small chunk waiting for the next one to absorb it
for chunk in chunks:
if carry is not None:
if len(carry) + len(chunk) <= size:
chunk = carry + chunk
else:
out.append(carry)
carry = None
if len(chunk) < MIN_BATCH:
if out and len(out[-1]) + len(chunk) <= size:
out[-1] = out[-1] + chunk
else:
carry = chunk
else:
out.append(chunk)
if carry is not None:
out.append(carry)
return out
def write_batches(root, size, given_dir=None):
staging = refresh.staging_dir(root, given_dir, create=True)
d = os.path.join(staging, "season", "batches")
os.makedirs(d, exist_ok=True)
for name in os.listdir(d):
if name.startswith("season-") and name.endswith(".txt"):
os.remove(os.path.join(d, name))
got = batches(root, size)
for n, ids in enumerate(got, 1):
with open(os.path.join(d, f"season-{n:02d}.txt"), "w", encoding="utf-8") as f:
f.write("\n".join(ids) + "\n")
return d, got
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--n", type=int, default=10, help="trails per batch")
parser.add_argument("--dir", default=None, help="staging directory")
args = parser.parse_args(argv)
d, got = write_batches(os.path.dirname(HERE), args.n, args.dir)
print(f"{len(got)} batches, {sum(len(b) for b in got)} trails, written to {d}")
return 0
if __name__ == "__main__":
sys.exit(main())
+93
View File
@@ -0,0 +1,93 @@
"""Tests for tools/season_batches.py and the researchers' brief.
Run from the repository root:
python3 -m unittest discover tools/tests -p "test_season_batches.py"
"""
import math
import os
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import refresh # noqa: E402
import season_batches as B # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def write(root, tid, regions, season=None):
os.makedirs(os.path.join(root, tid))
hike = '[hike]\nshape = "loop"\n' + (f'season = "{season}"\nmonths = [6, 7]\n' if season else "")
with open(os.path.join(root, tid, "trail.toml"), "w", encoding="utf-8") as f:
f.write(f'name = "{tid}"\ncountry = "US"\nregions = {regions!r}\n\n'.replace("'", '"') + hike)
class BatchesTest(unittest.TestCase):
def test_missing_ids_are_the_records_without_a_season(self):
with tempfile.TemporaryDirectory() as root:
write(root, "b-trail", ["CA"], season="June to July")
write(root, "c-trail", ["CA"])
write(root, "a-trail", ["WY"])
self.assertEqual(B.missing_ids(root), ["a-trail", "c-trail"])
def test_batches_are_at_most_the_size_and_cover_every_id_once(self):
with tempfile.TemporaryDirectory() as root:
for i in range(23):
write(root, f"ca-{i:02d}", ["CA"])
for i in range(7):
write(root, f"pa-{i:02d}", ["PA"])
got = B.batches(root, 10)
flat = [x for b in got for x in b]
self.assertEqual(sorted(flat), B.missing_ids(root))
self.assertEqual(len(flat), len(set(flat)))
self.assertTrue(all(0 < len(b) <= 10 for b in got))
def test_a_batch_stays_in_one_region_group_unless_joined(self):
with tempfile.TemporaryDirectory() as root:
for i in range(23):
write(root, f"ca-{i:02d}", ["CA"])
for i in range(3):
write(root, f"pa-{i:02d}", ["PA"])
got = B.batches(root, 10)
west = [b for b in got if all(x.startswith("ca-") for x in b)]
self.assertEqual([len(b) for b in west], [10, 10])
# the leftover 3 and the 3 Pennsylvania trails are each fewer than 5, so they share a batch
mixed = [b for b in got if b not in west]
self.assertEqual([len(b) for b in mixed], [6])
def test_a_small_leftover_joins_a_neighbour_with_room(self):
with tempfile.TemporaryDirectory() as root:
for i in range(12):
write(root, f"ca-{i:02d}", ["CA"]) # 10 and 2
for i in range(4):
write(root, f"or-{i:02d}", ["OR"]) # same group as CA
got = B.batches(root, 10)
self.assertEqual(sorted(len(b) for b in got), [6, 10])
def test_real_count(self):
n = len(B.missing_ids(ROOT))
recs = [t for t in refresh.trail_ids(ROOT)
if not (refresh.load_toml(os.path.join(ROOT, t, "trail.toml")).get("hike") or {}).get("season")]
self.assertEqual(n, len(recs))
got = B.batches(ROOT)
# each region group can leave one part-full batch
self.assertGreaterEqual(len(got), math.ceil(n / 10))
self.assertLessEqual(len(got), math.ceil(n / 10) + len(B.REGION_GROUPS))
self.assertEqual(sorted(x for b in got for x in b), B.missing_ids(ROOT))
def test_every_region_code_in_the_records_has_a_group(self):
for tid in refresh.trail_ids(ROOT):
rec = refresh.load_toml(os.path.join(ROOT, tid, "trail.toml"))
self.assertNotEqual(B.group_of(rec), B.OTHER, tid)
def test_the_brief_names_what_a_researcher_records(self):
text = open(os.path.join(ROOT, "docs", "season-research.md"), encoding="utf-8").read()
for want in ("hike.season_basis", "hike.months", "quote", "not-found", "publisher"):
self.assertIn(want, text)
if __name__ == "__main__":
unittest.main()