From 15dbf07603226f5df02ced1a9b5baf1582c3b8a7 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 10:16:19 -0700
Subject: [PATCH 01/30] Add season arcs, grades, phrases and the method
sentence
---
tools/season.py | 108 +++++++++++++++++++++++++++++
tools/tests/test_season_helpers.py | 81 ++++++++++++++++++++++
2 files changed, 189 insertions(+)
create mode 100644 tools/tests/test_season_helpers.py
diff --git a/tools/season.py b/tools/season.py
index 3844d46..eb3c7d9 100644
--- a/tools/season.py
+++ b/tools/season.py
@@ -68,3 +68,111 @@ def check_season(tid, hike, errors):
errors.append(
f"{tid}: hike.season_basis \"estimate\" needs exactly one source naming "
"season or months")
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers for the checker and the estimator. Months are a set on a
+# circle: a season may wrap the year end (November to March), so spans,
+# grades and phrases are all circular.
+
+MONTH_NAMES = ("January", "February", "March", "April", "May", "June",
+ "July", "August", "September", "October", "November", "December")
+
+
+def _months(months):
+ got = sorted({int(m) for m in months})
+ if not got or got[0] < 1 or got[-1] > 12:
+ raise ValueError(f"not a set of months: {months!r}")
+ return got
+
+
+def span(months):
+ """The smallest circular arc covering the months, as (first, last).
+
+ December to February is one arc, (12, 2). Two separate windows give the
+ arc covering both. All twelve months give (1, 12).
+ """
+ got = _months(months)
+ if len(got) == 1:
+ return (got[0], got[0])
+ best_gap, first = -1, got[0]
+ for i, month in enumerate(got):
+ nxt = got[(i + 1) % len(got)]
+ gap = (nxt - month) % 12
+ if gap == 0:
+ gap = 12
+ # The arc starts after the largest gap. Ties go to the gap whose
+ # following month is smallest, so all twelve months give (1, 12).
+ if gap > best_gap or (gap == best_gap and nxt < first):
+ best_gap, first = gap, nxt
+ i = got.index(first)
+ return (first, got[i - 1])
+
+
+def _circ_distance(a, b):
+ d = abs(a - b)
+ return min(d, 12 - d)
+
+
+def grade(estimated, sourced):
+ """How well an estimated season matches a sourced one.
+
+ "exact" when the arcs have the same first and last month, "within1"
+ when each end is within one month (counted on the circle), else "worse".
+ """
+ if not estimated or not sourced:
+ return "worse"
+ est_first, est_last = span(estimated)
+ src_first, src_last = span(sourced)
+ if (est_first, est_last) == (src_first, src_last):
+ return "exact"
+ if (_circ_distance(est_first, src_first) <= 1
+ and _circ_distance(est_last, src_last) <= 1):
+ return "within1"
+ return "worse"
+
+
+def phrase_for(months):
+ """The plain season phrase built from months, for an estimate.
+
+ One run reads "June to September", a run over the year end reads
+ "November to March", separate runs are joined with "and", one month
+ reads "July" and twelve read "All year".
+ """
+ got = _months(months)
+ if len(got) == 12:
+ return "All year"
+ runs = []
+ start = prev = got[0]
+ for month in got[1:]:
+ if month == prev + 1:
+ prev = month
+ else:
+ runs.append((start, prev))
+ start = prev = month
+ runs.append((start, prev))
+ if len(runs) > 1 and runs[0][0] == 1 and runs[-1][1] == 12:
+ runs = [(runs[-1][0], runs[0][1])] + runs[1:-1]
+ first = span(got)[0]
+ while runs and runs[0][0] != first:
+ runs.append(runs.pop(0))
+
+ def words(run):
+ a, b = run
+ if a == b:
+ return MONTH_NAMES[a - 1]
+ return f"{MONTH_NAMES[a - 1]} to {MONTH_NAMES[b - 1]}"
+
+ return " and ".join(words(run) for run in runs)
+
+
+def method_sentence(dataset, period, n_points, kind, rule_version):
+ """The one fixed sentence an estimated season carries as its method."""
+ where = {
+ "track": "along the track",
+ "ends": "at the trail ends",
+ "place": "at the place centre",
+ }.get(kind, kind)
+ noun = "point" if n_points == 1 else "points"
+ return (f"Estimated from {dataset} monthly climate ({period}) at "
+ f"{n_points} {noun} {where}; rule version {rule_version}.")
diff --git a/tools/tests/test_season_helpers.py b/tools/tests/test_season_helpers.py
new file mode 100644
index 0000000..0e8dd25
--- /dev/null
+++ b/tools/tests/test_season_helpers.py
@@ -0,0 +1,81 @@
+"""Tests for the shared season helpers in tools/season.py.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import os
+import sys
+import unittest
+
+sys.dont_write_bytecode = True
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import season # noqa: E402
+
+
+class SpanTest(unittest.TestCase):
+ def test_span_wraps_the_year(self):
+ self.assertEqual(season.span([11, 12, 1, 2, 3]), (11, 3))
+
+ def test_span_of_two_windows_covers_both(self):
+ self.assertEqual(season.span([4, 5, 9, 10]), (4, 10))
+
+ def test_span_of_one_month(self):
+ self.assertEqual(season.span([7]), (7, 7))
+
+ def test_span_of_all_year(self):
+ self.assertEqual(season.span(list(range(1, 13))), (1, 12))
+
+ def test_span_is_order_independent(self):
+ self.assertEqual(season.span([3, 1, 12, 2, 11]), (11, 3))
+
+
+class GradeTest(unittest.TestCase):
+ def test_grade_exact(self):
+ self.assertEqual(season.grade([6, 7, 8, 9], [6, 7, 8, 9]), "exact")
+ self.assertEqual(season.grade([11, 12, 1, 2], [11, 12, 1, 2]), "exact")
+
+ def test_grade_within_one_at_each_end(self):
+ self.assertEqual(season.grade([5, 6, 7, 8, 9], [6, 7, 8]), "within1")
+
+ def test_grade_worse(self):
+ self.assertEqual(season.grade([6, 7], [9, 10]), "worse")
+
+ def test_grade_across_the_year_end(self):
+ self.assertEqual(season.grade([12, 1, 2], [1, 2, 3]), "within1")
+
+ def test_grade_two_months_off_at_one_end_is_worse(self):
+ self.assertEqual(season.grade([4, 5, 6, 7, 8], [6, 7, 8]), "worse")
+
+
+class PhraseTest(unittest.TestCase):
+ def test_phrase_runs(self):
+ self.assertEqual(season.phrase_for([6, 7, 8, 9]), "June to September")
+ self.assertEqual(season.phrase_for([11, 12, 1, 2, 3]), "November to March")
+ self.assertEqual(season.phrase_for([4, 5, 9, 10]),
+ "April to May and September to October")
+ self.assertEqual(season.phrase_for([7]), "July")
+ self.assertEqual(season.phrase_for(list(range(1, 13))), "All year")
+
+ def test_phrase_two_month_run(self):
+ self.assertEqual(season.phrase_for([7, 8]), "July to August")
+ self.assertEqual(season.phrase_for([12, 1]), "December to January")
+
+
+class MethodSentenceTest(unittest.TestCase):
+ def test_method_sentence_names_dataset_period_and_points(self):
+ text = season.method_sentence("ERA5-Land via Open-Meteo", "2011-2020", 5, "track", 1)
+ self.assertIn("ERA5-Land via Open-Meteo", text)
+ self.assertIn("2011-2020", text)
+ self.assertIn("5", text)
+ self.assertTrue(text.endswith("."))
+ self.assertLess(len(text), 400)
+
+ def test_method_sentence_for_each_kind(self):
+ for kind in ("track", "ends", "place"):
+ text = season.method_sentence("Dataset", "2011-2020", 1, kind, 1)
+ self.assertIn("Dataset", text)
+
+
+if __name__ == "__main__":
+ unittest.main()
From 91c2bd1c47659cbe38e3d1bdfdd1fc9d7f7d4518 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 10:24:42 -0700
Subject: [PATCH 02/30] Add the climate download, cached outside the
repository, and record the source chosen
---
NOTICE.md | 4 +
tools/season_climate.py | 485 ++++++++++++++++++
.../fixtures/season/eccc_normals.geojson | 1 +
.../fixtures/season/noaa_USW00000001.csv | 13 +
.../fixtures/season/noaa_USW00000002.csv | 13 +
.../fixtures/season/noaa_USW00000003.csv | 13 +
tools/tests/fixtures/season/noaa_stations.txt | 3 +
.../fixtures/season/open_meteo_alpine.json | 1 +
.../fixtures/season/open_meteo_coast.json | 1 +
.../fixtures/season/open_meteo_desert.json | 1 +
.../fixtures/season/open_meteo_nodata.json | 1 +
tools/tests/test_season_climate.py | 154 ++++++
12 files changed, 690 insertions(+)
create mode 100644 tools/season_climate.py
create mode 100644 tools/tests/fixtures/season/eccc_normals.geojson
create mode 100644 tools/tests/fixtures/season/noaa_USW00000001.csv
create mode 100644 tools/tests/fixtures/season/noaa_USW00000002.csv
create mode 100644 tools/tests/fixtures/season/noaa_USW00000003.csv
create mode 100644 tools/tests/fixtures/season/noaa_stations.txt
create mode 100644 tools/tests/fixtures/season/open_meteo_alpine.json
create mode 100644 tools/tests/fixtures/season/open_meteo_coast.json
create mode 100644 tools/tests/fixtures/season/open_meteo_desert.json
create mode 100644 tools/tests/fixtures/season/open_meteo_nodata.json
create mode 100644 tools/tests/test_season_climate.py
diff --git a/NOTICE.md b/NOTICE.md
index 71ed40b..5cdecc2 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -27,3 +27,7 @@ The files `elevation.json` in the trail directories are computed from each trail
- 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.
- Terrain Tiles was accessed from https://registry.opendata.aws/terrain-tiles.
+
+## Climate
+
+A season marked as estimated is worked out from monthly climate at the trail's elevation. The climate values are monthly means for 2011 to 2020 computed by `tools/season_climate.py` from daily ERA5-Land data served by Open-Meteo.com (https://open-meteo.com/en/docs/historical-weather-api). Weather data by Open-Meteo.com, offered under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/); the reanalysis behind it is the Copernicus Climate Change Service's. Only the estimated seasons derive from it. Each estimated record names it in its sources, and the estimates themselves say they are estimates wherever they are shown.
diff --git a/tools/season_climate.py b/tools/season_climate.py
new file mode 100644
index 0000000..be9e556
--- /dev/null
+++ b/tools/season_climate.py
@@ -0,0 +1,485 @@
+"""Monthly climate normals for a point, downloaded once and cached.
+
+Python 3 standard library only. The estimator (tools/estimate_season.py)
+asks this module for the normals at a trail's sample points. Network use
+happens only when the cache lacks a point. Every response is cached
+outside the repository, requests go one at a time with a short pause, and
+the same point is never requested twice (a point with no data is cached
+as having no data). Run the trial with:
+
+ python3 tools/estimate_season.py trial
+
+Source chosen
+=============
+ERA5-Land through the Open-Meteo Historical Weather API: daily maximum
+temperature and daily maximum snow depth, averaged by month over
+2011-2020, at the elevation asked for (the API adjusts both values to
+that elevation). SOURCE below names it for the record entries.
+
+Licences, read on each publisher's own terms page (2026-11-20):
+
+- Open-Meteo licence page, https://open-meteo.com/en/licence:
+ "API data are offered under Attribution 4.0 International (CC BY 4.0)".
+ Its terms page, https://open-meteo.com/en/terms, adds for the free
+ API: "You may only use the free API services for non-commercial
+ purposes." and "Less than 10'000 API calls per day, 5'000 per hour
+ and 600 per minute." This dataset is a public, non-commercial one, and
+ the CC BY 4.0 data licence is met by the attribution in NOTICE.md and
+ the source entry on each estimated record. The rate limit is why the
+ period is the last ten years of the normals period and not all
+ thirty: one point for 1991-2020 costs about 156 of the 600 units
+ allowed per minute, so the roughly 900 sample points would need about
+ five hours of throttled requests; ten years cost about 52 units a
+ point. The rule's thresholds are fitted on the same ten years, so a
+ steady offset between the decade and the thirty year normals is
+ mostly absorbed by the fit. Widening the period later only refills
+ the cache.
+- NOAA (US only), https://www.weather.gov/disclaimer: "The information
+ on National Weather Service (NWS) Web pages are in the public domain,
+ unless specifically noted otherwise, and may be used without charge
+ for any lawful purpose". The 1991-2020 monthly normals are station
+ values, and the product carries temperature and precipitation only:
+ its station files have no snow depth variable, so the snow test
+ would be dropped. SNODAS snow depth is a separate daily US grid with
+ no point service.
+- Environment and Climate Change Canada (Canada only), normals under
+ the Open Government Licence, Canada,
+ https://open.canada.ca/en/open-government-licence-canada: "The
+ Information Provider grants you a worldwide, royalty-free, perpetual,
+ non-exclusive licence to use the Information, including for
+ commercial purposes", with acknowledgement of the source. The MSC
+ GeoMet normals collection trialled here is the 1981-2010 station
+ normals. It has mean daily maximum temperature but no snow depth
+ (total snowfall is not depth), and its features carry no station
+ elevation, so no lapse adjustment to a trail's high ground is
+ possible.
+
+Why the others lost: neither station product covers both countries,
+neither gives snow depth, and neither gives values at the elevation of
+a trail's high ground, which is what decides when an alpine trail
+opens. Stations also thin out exactly where trails are wildest (the
+trial's far north point has no station in range). Open-Meteo returns
+temperature and snow depth at the elevation asked for, for every
+trial trail in both countries. Its weakness is the free API's
+non-commercial access term, recorded above for the owner.
+
+Trial (twelve sourced trails, 2026-11-20, one coarse default rule
+for every candidate: the high point at least 5 C and at most 10 cm of
+snow where snow exists, the low point at most 32 C; high and low track
+points only, place centres for akshayuk-pass and
+desert-winter-thru-hike, which have no track or ends; rerun with the
+trial command above once the estimator exists). The akshayuk-pass
+place centre falls in water, where the land model has no values, and
+no station is in range, so every candidate lacks data there. NOAA
+reached west-coast-trail across the border from a US station.
+
+ open-meteo: trail (sourced months) gives estimated months, grade
+ akshayuk-pass (7,8): no data
+ great-divide-trail (7,8,9): 7,8,9, exact
+ west-coast-trail (5,6,7,8,9): all year, worse
+ john-muir (7,8,9): 6,7,8,9, within1
+ colorado-trail (7,8,9): 7,8,9, exact
+ uinta-highline (7,8,9): 7,8,9, exact
+ desert-winter-thru-hike (12,1,2): 1,2,3,4,5,8,9,10,11,12, worse
+ arizona (2,3,9,10): 3,4,10,11, within1
+ florida (10,11,12,1,2,3,4): all year, worse
+ washington-coast-trail (5,6,7,8,9): all year, worse
+ maah-daah-hey (all year): 3,4,5,6,7,8,9,10,11, worse
+ superior-hiking (6,7,8,9): 5,6,7,8,9,10, within1
+ Data for 11 of 12, exact or within one month for 6 of the 11.
+
+ noaa: trail (sourced months) gives estimated months, grade
+ akshayuk-pass (7,8): no data
+ great-divide-trail (7,8,9): no data
+ west-coast-trail (5,6,7,8,9): all year, worse
+ john-muir (7,8,9): 5,6,7,8,9,10, worse
+ colorado-trail (7,8,9): 5,6,7,8,9,10, worse
+ uinta-highline (7,8,9): 5,6,7,8,9, worse
+ desert-winter-thru-hike (12,1,2): 1,2,3,4,5,9,10,11,12, worse
+ arizona (2,3,9,10): 4,10, worse
+ florida (10,11,12,1,2,3,4): all year, worse
+ washington-coast-trail (5,6,7,8,9): all year, worse
+ maah-daah-hey (all year): 3,4,5,6,7,8,9,10,11, worse
+ superior-hiking (6,7,8,9): 4,5,6,7,8,9,10, worse
+ Data for 10 of 12, exact or within one month for 0 of the 10. With
+ no snow measure the alpine seasons all open about two months early.
+
+ eccc: trail (sourced months) gives estimated months, grade
+ akshayuk-pass (7,8): no data
+ great-divide-trail (7,8,9): 4,5,6,7,8,9,10, worse
+ west-coast-trail (5,6,7,8,9): all year, worse
+ john-muir (7,8,9): no data
+ colorado-trail (7,8,9): no data
+ uinta-highline (7,8,9): no data
+ desert-winter-thru-hike (12,1,2): no data
+ arizona (2,3,9,10): no data
+ florida (10,11,12,1,2,3,4): no data
+ washington-coast-trail (5,6,7,8,9): partial data
+ maah-daah-hey (all year): no data
+ superior-hiking (6,7,8,9): partial data
+ Data for 2 of 12 (the Canadian trails), exact or within one month
+ for 0 of the 2.
+"""
+import sys
+
+sys.dont_write_bytecode = True
+
+import csv
+import io
+import json
+import math
+import os
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+
+CACHE_DIR = os.environ.get("LONGHIKES_CLIMATE_CACHE") or os.path.join(
+ os.path.expanduser("~"), ".cache", "longhikes-climate")
+
+SOURCE = {
+ "name": "ERA5-Land via Open-Meteo",
+ "publisher": "Open-Meteo.com",
+ "url": "https://open-meteo.com/en/docs/historical-weather-api",
+ "licence": "CC BY 4.0",
+ "period": "2011-2020",
+}
+
+USER_AGENT = "Mozilla/5.0"
+DELAY_S = 0.15
+LAPSE_C_PER_KM = 6.5
+ERA5_YEARS = (2011, 2020)
+NOAA_MAX_KM = 150.0
+ECCC_MAX_KM = 250.0
+
+_LAST_AT = [0.0]
+_REMAINING = [None]
+
+
+@dataclass(frozen=True)
+class PointNormals:
+ """Monthly normals at one point: twelve mean daily highs in degrees
+ C and, when the source has one, twelve mean snow depths in cm."""
+
+ lat: float
+ lon: float
+ elev_m: float
+ tmax_c: tuple
+ snow_cm: tuple = None
+
+
+def haversine_km(lat1, lon1, lat2, lon2):
+ radius = 6371.0088
+ p1, p2 = math.radians(lat1), math.radians(lat2)
+ dphi = math.radians(lat2 - lat1)
+ dlmb = math.radians(lon2 - lon1)
+ h = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
+ return 2 * radius * math.asin(math.sqrt(h))
+
+
+def _pace():
+ """One request at a time, a short pause, and respect for the free
+ API's per-minute allowance when it reports one."""
+ if _REMAINING[0] is not None and _REMAINING[0] < 60:
+ time.sleep(61)
+ _REMAINING[0] = None
+ wait = DELAY_S - (time.time() - _LAST_AT[0])
+ if wait > 0:
+ time.sleep(wait)
+
+
+def _get_bytes(url, opener, timeout=180):
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
+ for attempt in range(4):
+ _pace()
+ try:
+ with opener(req, timeout=timeout) as resp:
+ raw = resp.read()
+ headers = getattr(resp, "headers", None) or {}
+ try:
+ _REMAINING[0] = float(headers.get("X-RateLimit-Remaining"))
+ except (TypeError, ValueError):
+ pass
+ _LAST_AT[0] = time.time()
+ return raw
+ except urllib.error.HTTPError as exc:
+ _LAST_AT[0] = time.time()
+ if exc.code == 429 and attempt < 3:
+ time.sleep(65)
+ continue
+ raise
+
+
+def _cache_path(cache, source, lat, lon, elev_m):
+ elev_key = "cell" if elev_m is None else str(int(round(elev_m)))
+ return os.path.join(cache, f"{source}_{lat:.3f}_{lon:.3f}_{elev_key}.json")
+
+
+def _read_cache(path):
+ """(True, normals or None) when cached, else (False, None). A cached
+ None means the source had no data for the point."""
+ if not os.path.exists(path):
+ return False, None
+ with open(path, encoding="utf-8") as f:
+ doc = json.load(f)
+ if doc.get("no_data"):
+ return True, None
+ snow = doc.get("snow_cm")
+ return True, PointNormals(
+ lat=float(doc["lat"]), lon=float(doc["lon"]), elev_m=float(doc["elev_m"]),
+ tmax_c=tuple(float(v) for v in doc["tmax_c"]),
+ snow_cm=None if snow is None else tuple(float(v) for v in snow))
+
+
+def _write_cache(path, normals):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ if normals is None:
+ doc = {"no_data": True}
+ else:
+ doc = {"lat": normals.lat, "lon": normals.lon, "elev_m": normals.elev_m,
+ "tmax_c": list(normals.tmax_c),
+ "snow_cm": None if normals.snow_cm is None else list(normals.snow_cm)}
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(doc, f, sort_keys=True)
+ f.write("\n")
+
+
+def _rounded(lat, lon):
+ return round(float(lat), 3), round(float(lon), 3)
+
+
+# ---------------------------------------------------------------------------
+# Open-Meteo (ERA5-Land), the chosen source.
+
+def _open_meteo_url(lat, lon, elev_m):
+ params = {
+ "latitude": lat, "longitude": lon,
+ "start_date": f"{ERA5_YEARS[0]}-01-01", "end_date": f"{ERA5_YEARS[1]}-12-31",
+ "daily": "temperature_2m_max,snow_depth_max",
+ "timezone": "UTC", "models": "era5_land",
+ }
+ if elev_m is not None:
+ params["elevation"] = int(round(elev_m))
+ return ("https://archive-api.open-meteo.com/v1/archive?"
+ + urllib.parse.urlencode(params))
+
+
+def parse_open_meteo(raw, lat, lon, elev_m):
+ """Daily ERA5-Land values averaged by month, or None. Snow depths
+ arrive in metres and leave in cm. A month with no temperature value
+ at all is missing data, never zero; a point whose snow values are
+ absent (open water) keeps its temperatures with snow_cm None."""
+ try:
+ doc = json.loads(raw.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError):
+ return None
+ daily = doc.get("daily") or {}
+ days = daily.get("time") or []
+ tmax = daily.get("temperature_2m_max") or []
+ snow = daily.get("snow_depth_max") or []
+ if not days or len(tmax) != len(days):
+ return None
+ by_month_t = [[] for _ in range(12)]
+ by_month_s = [[] for _ in range(12)]
+ for i, day in enumerate(days):
+ try:
+ month = int(day[5:7])
+ except (TypeError, ValueError, IndexError):
+ return None
+ if tmax[i] is not None:
+ by_month_t[month - 1].append(float(tmax[i]))
+ if i < len(snow) and snow[i] is not None:
+ by_month_s[month - 1].append(float(snow[i]))
+ if any(not values for values in by_month_t):
+ return None
+ tmax_c = tuple(round(sum(v) / len(v), 1) for v in by_month_t)
+ if all(by_month_s):
+ snow_cm = tuple(round(sum(v) / len(v) * 100.0, 1) for v in by_month_s)
+ else:
+ snow_cm = None
+ elev = float(elev_m) if elev_m is not None else float(doc.get("elevation") or 0.0)
+ return PointNormals(lat=lat, lon=lon, elev_m=elev, tmax_c=tmax_c, snow_cm=snow_cm)
+
+
+def fetch_open_meteo(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
+ lat, lon = _rounded(lat, lon)
+ path = _cache_path(cache, "open-meteo", lat, lon, elev_m)
+ hit, got = _read_cache(path)
+ if hit:
+ return got
+ raw = _get_bytes(_open_meteo_url(lat, lon, elev_m), opener)
+ got = parse_open_meteo(raw, lat, lon, elev_m)
+ _write_cache(path, got)
+ return got
+
+
+# ---------------------------------------------------------------------------
+# NOAA 1991-2020 monthly station normals (US only, temperature only).
+
+NOAA_STATIONS_URL = "https://www.ncei.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt"
+NOAA_NORMALS_URL = ("https://www.ncei.noaa.gov/data/normals-monthly/"
+ "1991-2020/access/{sid}.csv")
+
+
+def _noaa_stations(cache, opener):
+ path = os.path.join(cache, "noaa_ghcnd-stations.txt")
+ if not os.path.exists(path):
+ raw = _get_bytes(NOAA_STATIONS_URL, opener)
+ os.makedirs(cache, exist_ok=True)
+ with open(path, "wb") as f:
+ f.write(raw)
+ stations = []
+ with open(path, encoding="utf-8", errors="replace") as f:
+ for line in f:
+ parts = line.split()
+ if len(parts) < 4 or not parts[0].startswith("US"):
+ continue
+ try:
+ stations.append((parts[0], float(parts[1]), float(parts[2]),
+ float(parts[3])))
+ except ValueError:
+ continue
+ return stations
+
+
+def parse_noaa_csv(raw, lat, lon, elev_m):
+ """MLY-TMAX-NORMAL is in degrees F. Temperatures are lapse adjusted
+ from the station elevation to the elevation asked for. The product
+ has no snow depth, so snow_cm is None."""
+ text = raw.decode("utf-8", errors="replace")
+ rows = {}
+ station_elev = None
+ for row in csv.DictReader(io.StringIO(text)):
+ try:
+ month = int(row.get("month") or 0)
+ value = float(row.get("MLY-TMAX-NORMAL") or "")
+ station_elev = float(row.get("ELEVATION") or 0.0)
+ except ValueError:
+ continue
+ if 1 <= month <= 12:
+ rows[month] = value
+ if len(rows) != 12 or station_elev is None:
+ return None
+ lapse = 0.0
+ if elev_m is not None:
+ lapse = LAPSE_C_PER_KM * (float(elev_m) - station_elev) / 1000.0
+ tmax_c = tuple(round((rows[m] - 32.0) * 5.0 / 9.0 - lapse, 1)
+ for m in range(1, 13))
+ elev = float(elev_m) if elev_m is not None else station_elev
+ return PointNormals(lat=lat, lon=lon, elev_m=elev, tmax_c=tmax_c, snow_cm=None)
+
+
+def fetch_noaa(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
+ lat, lon = _rounded(lat, lon)
+ path = _cache_path(cache, "noaa", lat, lon, elev_m)
+ hit, got = _read_cache(path)
+ if hit:
+ return got
+ near = sorted(
+ ((haversine_km(lat, lon, slat, slon), sid)
+ for sid, slat, slon, _selev in _noaa_stations(cache, opener)),
+ )
+ got = None
+ tried = 0
+ # Most GHCN stations have no normals file, so walk past the ones
+ # that answer 404; the nearest normals station is rarely the
+ # nearest station of any kind.
+ for dist, sid in near:
+ if dist > NOAA_MAX_KM or tried >= 30:
+ break
+ tried += 1
+ csv_path = os.path.join(cache, f"noaa_{sid}.csv")
+ if os.path.exists(csv_path):
+ with open(csv_path, "rb") as f:
+ raw = f.read()
+ else:
+ try:
+ raw = _get_bytes(NOAA_NORMALS_URL.format(sid=sid), opener)
+ except urllib.error.HTTPError:
+ continue
+ os.makedirs(cache, exist_ok=True)
+ with open(csv_path, "wb") as f:
+ f.write(raw)
+ got = parse_noaa_csv(raw, lat, lon, elev_m)
+ if got is not None:
+ break
+ _write_cache(path, got)
+ return got
+
+
+# ---------------------------------------------------------------------------
+# MSC GeoMet climate normals (Canada only, 1981-2010 stations).
+
+ECCC_ELEMENT = "Mean daily max temperature deg C"
+ECCC_URL = "https://api.weather.gc.ca/collections/climate-normals/items"
+
+
+def _eccc_url(lat, lon):
+ bbox = f"{lon - 1.5},{lat - 1.0},{lon + 1.5},{lat + 1.0}"
+ params = {"bbox": bbox, "limit": 10000, "f": "json",
+ "E_NORMAL_ELEMENT_NAME": ECCC_ELEMENT}
+ return ECCC_URL + "?" + urllib.parse.urlencode(params)
+
+
+def parse_eccc(raw, lat, lon, elev_m):
+ """The nearest station with all twelve months of mean daily maximum
+ temperature. The features carry no station elevation and no snow
+ depth, so neither can be given."""
+ try:
+ doc = json.loads(raw.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError):
+ return None
+ stations = {}
+ for feat in doc.get("features") or []:
+ props = feat.get("properties") or {}
+ if props.get("E_NORMAL_ELEMENT_NAME") != ECCC_ELEMENT:
+ continue
+ try:
+ month = int(props.get("MONTH") or 0)
+ value = float(props.get("VALUE"))
+ slon, slat = (feat.get("geometry") or {}).get("coordinates") or (None, None)
+ slat, slon = float(slat), float(slon)
+ except (TypeError, ValueError):
+ continue
+ if not 1 <= month <= 12:
+ continue
+ entry = stations.setdefault(props.get("STN_ID"), (slat, slon, {}))
+ entry[2][month] = value
+ best = None
+ for slat, slon, months in stations.values():
+ if len(months) != 12:
+ continue
+ dist = haversine_km(lat, lon, slat, slon)
+ if best is None or dist < best[0]:
+ best = (dist, months)
+ if best is None or best[0] > ECCC_MAX_KM:
+ return None
+ tmax_c = tuple(round(best[1][m], 1) for m in range(1, 13))
+ elev = float(elev_m) if elev_m is not None else 0.0
+ return PointNormals(lat=lat, lon=lon, elev_m=elev, tmax_c=tmax_c, snow_cm=None)
+
+
+def fetch_eccc(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
+ lat, lon = _rounded(lat, lon)
+ path = _cache_path(cache, "eccc", lat, lon, elev_m)
+ hit, got = _read_cache(path)
+ if hit:
+ return got
+ raw = _get_bytes(_eccc_url(lat, lon), opener)
+ got = parse_eccc(raw, lat, lon, elev_m)
+ _write_cache(path, got)
+ return got
+
+
+def fetch_normals(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
+ """Normals from the chosen source (see SOURCE), or None when it has
+ no data for the point. Never returns invented zeros."""
+ return fetch_open_meteo(lat, lon, elev_m, cache=cache, opener=opener)
+
+
+CANDIDATES = {
+ "open-meteo": fetch_open_meteo,
+ "noaa": fetch_noaa,
+ "eccc": fetch_eccc,
+}
diff --git a/tools/tests/fixtures/season/eccc_normals.geojson b/tools/tests/fixtures/season/eccc_normals.geojson
new file mode 100644
index 0000000..23aabef
--- /dev/null
+++ b/tools/tests/fixtures/season/eccc_normals.geojson
@@ -0,0 +1 @@
+{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 1, "VALUE": 6.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 2, "VALUE": 8.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 3, "VALUE": 11.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 4, "VALUE": 14.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 5, "VALUE": 18.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 6, "VALUE": 21.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 7, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 8, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 9, "VALUE": 20.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 10, "VALUE": 14.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 11, "VALUE": 9.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 12, "VALUE": 6.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 1, "VALUE": -2.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 2, "VALUE": 0.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 3, "VALUE": 5.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 4, "VALUE": 11.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 5, "VALUE": 17.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 6, "VALUE": 21.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 7, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 8, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 9, "VALUE": 19.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 10, "VALUE": 12.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 11, "VALUE": 3.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 12, "VALUE": -2.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}], "numberReturned": 24}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/noaa_USW00000001.csv b/tools/tests/fixtures/season/noaa_USW00000001.csv
new file mode 100644
index 0000000..07bc636
--- /dev/null
+++ b/tools/tests/fixtures/season/noaa_USW00000001.csv
@@ -0,0 +1,13 @@
+"STATION","DATE","LATITUDE","LONGITUDE","ELEVATION","NAME","month","MLY-TMAX-NORMAL"
+"USW00000001","01","37.7","-119.5","1500.0","FIXTURE","01","50.0"
+"USW00000001","02","37.7","-119.5","1500.0","FIXTURE","02","54.0"
+"USW00000001","03","37.7","-119.5","1500.0","FIXTURE","03","59.0"
+"USW00000001","04","37.7","-119.5","1500.0","FIXTURE","04","64.0"
+"USW00000001","05","37.7","-119.5","1500.0","FIXTURE","05","72.0"
+"USW00000001","06","37.7","-119.5","1500.0","FIXTURE","06","82.0"
+"USW00000001","07","37.7","-119.5","1500.0","FIXTURE","07","90.0"
+"USW00000001","08","37.7","-119.5","1500.0","FIXTURE","08","89.0"
+"USW00000001","09","37.7","-119.5","1500.0","FIXTURE","09","82.0"
+"USW00000001","10","37.7","-119.5","1500.0","FIXTURE","10","71.0"
+"USW00000001","11","37.7","-119.5","1500.0","FIXTURE","11","58.0"
+"USW00000001","12","37.7","-119.5","1500.0","FIXTURE","12","50.0"
diff --git a/tools/tests/fixtures/season/noaa_USW00000002.csv b/tools/tests/fixtures/season/noaa_USW00000002.csv
new file mode 100644
index 0000000..3c79ce1
--- /dev/null
+++ b/tools/tests/fixtures/season/noaa_USW00000002.csv
@@ -0,0 +1,13 @@
+"STATION","DATE","LATITUDE","LONGITUDE","ELEVATION","NAME","month","MLY-TMAX-NORMAL"
+"USW00000002","01","32.2","-110.9","800.0","FIXTURE","01","66.0"
+"USW00000002","02","32.2","-110.9","800.0","FIXTURE","02","70.0"
+"USW00000002","03","32.2","-110.9","800.0","FIXTURE","03","77.0"
+"USW00000002","04","32.2","-110.9","800.0","FIXTURE","04","85.0"
+"USW00000002","05","32.2","-110.9","800.0","FIXTURE","05","94.0"
+"USW00000002","06","32.2","-110.9","800.0","FIXTURE","06","104.0"
+"USW00000002","07","32.2","-110.9","800.0","FIXTURE","07","103.0"
+"USW00000002","08","32.2","-110.9","800.0","FIXTURE","08","101.0"
+"USW00000002","09","32.2","-110.9","800.0","FIXTURE","09","97.0"
+"USW00000002","10","32.2","-110.9","800.0","FIXTURE","10","88.0"
+"USW00000002","11","32.2","-110.9","800.0","FIXTURE","11","75.0"
+"USW00000002","12","32.2","-110.9","800.0","FIXTURE","12","66.0"
diff --git a/tools/tests/fixtures/season/noaa_USW00000003.csv b/tools/tests/fixtures/season/noaa_USW00000003.csv
new file mode 100644
index 0000000..1a89a7e
--- /dev/null
+++ b/tools/tests/fixtures/season/noaa_USW00000003.csv
@@ -0,0 +1,13 @@
+"STATION","DATE","LATITUDE","LONGITUDE","ELEVATION","NAME","month","MLY-TMAX-NORMAL"
+"USW00000003","01","47.6","-122.3","10.0","FIXTURE","01","47.0"
+"USW00000003","02","47.6","-122.3","10.0","FIXTURE","02","50.0"
+"USW00000003","03","47.6","-122.3","10.0","FIXTURE","03","54.0"
+"USW00000003","04","47.6","-122.3","10.0","FIXTURE","04","59.0"
+"USW00000003","05","47.6","-122.3","10.0","FIXTURE","05","65.0"
+"USW00000003","06","47.6","-122.3","10.0","FIXTURE","06","70.0"
+"USW00000003","07","47.6","-122.3","10.0","FIXTURE","07","76.0"
+"USW00000003","08","47.6","-122.3","10.0","FIXTURE","08","77.0"
+"USW00000003","09","47.6","-122.3","10.0","FIXTURE","09","72.0"
+"USW00000003","10","47.6","-122.3","10.0","FIXTURE","10","62.0"
+"USW00000003","11","47.6","-122.3","10.0","FIXTURE","11","52.0"
+"USW00000003","12","47.6","-122.3","10.0","FIXTURE","12","47.0"
diff --git a/tools/tests/fixtures/season/noaa_stations.txt b/tools/tests/fixtures/season/noaa_stations.txt
new file mode 100644
index 0000000..7edfcdb
--- /dev/null
+++ b/tools/tests/fixtures/season/noaa_stations.txt
@@ -0,0 +1,3 @@
+USW00000001 37.7000 -119.5000 1500.0 CA FIXTURE SIERRA
+USW00000002 32.2000 -110.9000 800.0 AZ FIXTURE DESERT
+USW00000003 47.6000 -122.3000 10.0 WA FIXTURE COAST
diff --git a/tools/tests/fixtures/season/open_meteo_alpine.json b/tools/tests/fixtures/season/open_meteo_alpine.json
new file mode 100644
index 0000000..cf54b50
--- /dev/null
+++ b/tools/tests/fixtures/season/open_meteo_alpine.json
@@ -0,0 +1 @@
+{"latitude": 37.7, "longitude": -119.5, "elevation": 3400.0, "daily_units": {"time": "iso8601", "temperature_2m_max": "\u00b0C", "snow_depth_max": "m"}, "daily": {"time": ["2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08", "2015-01-09", "2015-01-10", "2015-01-11", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15", "2015-01-16", "2015-01-17", "2015-01-18", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22", "2015-01-23", "2015-01-24", "2015-01-25", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29", "2015-01-30", "2015-01-31", "2015-02-01", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05", "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20", "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26", "2015-02-27", "2015-02-28", "2015-03-01", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05", "2015-03-06", "2015-03-07", "2015-03-08", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20", "2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04", "2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09", "2015-04-10", "2015-04-11", "2015-04-12", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16", "2015-04-17", "2015-04-18", "2015-04-19", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23", "2015-04-24", "2015-04-25", "2015-04-26", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30", "2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09", "2015-05-10", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14", "2015-05-15", "2015-05-16", "2015-05-17", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21", "2015-05-22", "2015-05-23", "2015-05-24", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28", "2015-05-29", "2015-05-30", "2015-05-31", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04", "2015-06-05", "2015-06-06", "2015-06-07", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11", "2015-06-12", "2015-06-13", "2015-06-14", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18", "2015-06-19", "2015-06-20", "2015-06-21", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25", "2015-06-26", "2015-06-27", "2015-06-28", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02", "2015-07-03", "2015-07-04", "2015-07-05", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09", "2015-07-10", "2015-07-11", "2015-07-12", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16", "2015-07-17", "2015-07-18", "2015-07-19", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23", "2015-07-24", "2015-07-25", "2015-07-26", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01", "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06", "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20", "2015-08-21", "2015-08-22", "2015-08-23", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03", "2015-09-04", "2015-09-05", "2015-09-06", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10", "2015-09-11", "2015-09-12", "2015-09-13", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17", "2015-09-18", "2015-09-19", "2015-09-20", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24", "2015-09-25", "2015-09-26", "2015-09-27", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08", "2015-10-09", "2015-10-10", "2015-10-11", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15", "2015-10-16", "2015-10-17", "2015-10-18", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22", "2015-10-23", "2015-10-24", "2015-10-25", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29", "2015-10-30", "2015-10-31", "2015-11-01", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05", "2015-11-06", "2015-11-07", "2015-11-08", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12", "2015-11-13", "2015-11-14", "2015-11-15", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28", "2015-11-29", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03", "2015-12-04", "2015-12-05", "2015-12-06", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10", "2015-12-11", "2015-12-12", "2015-12-13", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17", "2015-12-18", "2015-12-19", "2015-12-20", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24", "2015-12-25", "2015-12-26", "2015-12-27", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31"], "temperature_2m_max": [-2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0], "snow_depth_max": [1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]}}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/open_meteo_coast.json b/tools/tests/fixtures/season/open_meteo_coast.json
new file mode 100644
index 0000000..443e60b
--- /dev/null
+++ b/tools/tests/fixtures/season/open_meteo_coast.json
@@ -0,0 +1 @@
+{"latitude": 37.7, "longitude": -119.5, "elevation": 20.0, "daily_units": {"time": "iso8601", "temperature_2m_max": "\u00b0C", "snow_depth_max": "m"}, "daily": {"time": ["2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08", "2015-01-09", "2015-01-10", "2015-01-11", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15", "2015-01-16", "2015-01-17", "2015-01-18", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22", "2015-01-23", "2015-01-24", "2015-01-25", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29", "2015-01-30", "2015-01-31", "2015-02-01", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05", "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20", "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26", "2015-02-27", "2015-02-28", "2015-03-01", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05", "2015-03-06", "2015-03-07", "2015-03-08", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20", "2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04", "2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09", "2015-04-10", "2015-04-11", "2015-04-12", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16", "2015-04-17", "2015-04-18", "2015-04-19", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23", "2015-04-24", "2015-04-25", "2015-04-26", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30", "2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09", "2015-05-10", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14", "2015-05-15", "2015-05-16", "2015-05-17", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21", "2015-05-22", "2015-05-23", "2015-05-24", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28", "2015-05-29", "2015-05-30", "2015-05-31", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04", "2015-06-05", "2015-06-06", "2015-06-07", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11", "2015-06-12", "2015-06-13", "2015-06-14", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18", "2015-06-19", "2015-06-20", "2015-06-21", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25", "2015-06-26", "2015-06-27", "2015-06-28", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02", "2015-07-03", "2015-07-04", "2015-07-05", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09", "2015-07-10", "2015-07-11", "2015-07-12", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16", "2015-07-17", "2015-07-18", "2015-07-19", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23", "2015-07-24", "2015-07-25", "2015-07-26", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01", "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06", "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20", "2015-08-21", "2015-08-22", "2015-08-23", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03", "2015-09-04", "2015-09-05", "2015-09-06", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10", "2015-09-11", "2015-09-12", "2015-09-13", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17", "2015-09-18", "2015-09-19", "2015-09-20", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24", "2015-09-25", "2015-09-26", "2015-09-27", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08", "2015-10-09", "2015-10-10", "2015-10-11", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15", "2015-10-16", "2015-10-17", "2015-10-18", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22", "2015-10-23", "2015-10-24", "2015-10-25", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29", "2015-10-30", "2015-10-31", "2015-11-01", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05", "2015-11-06", "2015-11-07", "2015-11-08", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12", "2015-11-13", "2015-11-14", "2015-11-15", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28", "2015-11-29", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03", "2015-12-04", "2015-12-05", "2015-12-06", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10", "2015-12-11", "2015-12-12", "2015-12-13", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17", "2015-12-18", "2015-12-19", "2015-12-20", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24", "2015-12-25", "2015-12-26", "2015-12-27", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31"], "temperature_2m_max": [9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0], "snow_depth_max": [0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]}}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/open_meteo_desert.json b/tools/tests/fixtures/season/open_meteo_desert.json
new file mode 100644
index 0000000..14d6e8c
--- /dev/null
+++ b/tools/tests/fixtures/season/open_meteo_desert.json
@@ -0,0 +1 @@
+{"latitude": 37.7, "longitude": -119.5, "elevation": 400.0, "daily_units": {"time": "iso8601", "temperature_2m_max": "\u00b0C", "snow_depth_max": "m"}, "daily": {"time": ["2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08", "2015-01-09", "2015-01-10", "2015-01-11", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15", "2015-01-16", "2015-01-17", "2015-01-18", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22", "2015-01-23", "2015-01-24", "2015-01-25", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29", "2015-01-30", "2015-01-31", "2015-02-01", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05", "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20", "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26", "2015-02-27", "2015-02-28", "2015-03-01", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05", "2015-03-06", "2015-03-07", "2015-03-08", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20", "2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04", "2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09", "2015-04-10", "2015-04-11", "2015-04-12", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16", "2015-04-17", "2015-04-18", "2015-04-19", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23", "2015-04-24", "2015-04-25", "2015-04-26", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30", "2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09", "2015-05-10", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14", "2015-05-15", "2015-05-16", "2015-05-17", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21", "2015-05-22", "2015-05-23", "2015-05-24", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28", "2015-05-29", "2015-05-30", "2015-05-31", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04", "2015-06-05", "2015-06-06", "2015-06-07", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11", "2015-06-12", "2015-06-13", "2015-06-14", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18", "2015-06-19", "2015-06-20", "2015-06-21", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25", "2015-06-26", "2015-06-27", "2015-06-28", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02", "2015-07-03", "2015-07-04", "2015-07-05", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09", "2015-07-10", "2015-07-11", "2015-07-12", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16", "2015-07-17", "2015-07-18", "2015-07-19", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23", "2015-07-24", "2015-07-25", "2015-07-26", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01", "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06", "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20", "2015-08-21", "2015-08-22", "2015-08-23", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03", "2015-09-04", "2015-09-05", "2015-09-06", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10", "2015-09-11", "2015-09-12", "2015-09-13", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17", "2015-09-18", "2015-09-19", "2015-09-20", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24", "2015-09-25", "2015-09-26", "2015-09-27", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08", "2015-10-09", "2015-10-10", "2015-10-11", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15", "2015-10-16", "2015-10-17", "2015-10-18", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22", "2015-10-23", "2015-10-24", "2015-10-25", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29", "2015-10-30", "2015-10-31", "2015-11-01", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05", "2015-11-06", "2015-11-07", "2015-11-08", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12", "2015-11-13", "2015-11-14", "2015-11-15", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28", "2015-11-29", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03", "2015-12-04", "2015-12-05", "2015-12-06", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10", "2015-12-11", "2015-12-12", "2015-12-13", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17", "2015-12-18", "2015-12-19", "2015-12-20", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24", "2015-12-25", "2015-12-26", "2015-12-27", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31"], "temperature_2m_max": [19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0], "snow_depth_max": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/open_meteo_nodata.json b/tools/tests/fixtures/season/open_meteo_nodata.json
new file mode 100644
index 0000000..a6e84c4
--- /dev/null
+++ b/tools/tests/fixtures/season/open_meteo_nodata.json
@@ -0,0 +1 @@
+{"error": true, "reason": "No data"}
\ No newline at end of file
diff --git a/tools/tests/test_season_climate.py b/tools/tests/test_season_climate.py
new file mode 100644
index 0000000..28f2f0b
--- /dev/null
+++ b/tools/tests/test_season_climate.py
@@ -0,0 +1,154 @@
+"""Tests for tools/season_climate.py. All offline: an injected opener
+serves the canned responses in fixtures/season/.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import io
+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 season_climate as C # noqa: E402
+import validate as V # noqa: E402
+
+FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "season")
+
+
+def fixture_bytes(name):
+ with open(os.path.join(FIX, name), "rb") as f:
+ return f.read()
+
+
+class FakeResponse(io.BytesIO):
+ headers = {}
+
+
+class FakeOpener:
+ """Routes by address to a fixture and counts the calls."""
+
+ def __init__(self, open_meteo="open_meteo_alpine.json"):
+ self.calls = []
+ self.open_meteo = open_meteo
+
+ def __call__(self, req, timeout=None):
+ url = req.full_url if hasattr(req, "full_url") else str(req)
+ self.calls.append(url)
+ if "archive-api.open-meteo.com" in url:
+ return FakeResponse(fixture_bytes(self.open_meteo))
+ if "ghcnd-stations.txt" in url:
+ return FakeResponse(fixture_bytes("noaa_stations.txt"))
+ if "normals-monthly" in url:
+ for sid in ("USW00000001", "USW00000002", "USW00000003"):
+ if sid in url:
+ return FakeResponse(fixture_bytes(f"noaa_{sid}.csv"))
+ raise AssertionError(url)
+ if "api.weather.gc.ca" in url:
+ return FakeResponse(fixture_bytes("eccc_normals.geojson"))
+ raise AssertionError(url)
+
+
+class OpenMeteoTest(unittest.TestCase):
+ def setUp(self):
+ C.DELAY_S = 0
+
+ def test_a_fixture_response_becomes_point_normals(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache, opener=FakeOpener())
+ self.assertIsNotNone(got)
+ self.assertEqual(len(got.tmax_c), 12)
+ self.assertEqual(len(got.snow_cm), 12)
+ self.assertEqual(got.tmax_c[0], -2.0) # January, degrees C
+ self.assertEqual(got.tmax_c[6], 21.0) # July
+ self.assertEqual(got.snow_cm[0], 120.0) # 1.2 metres of snow, in cm
+ self.assertEqual(got.snow_cm[7], 0.0)
+
+ def test_values_are_rounded_to_a_tenth(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_normals(37.7, -119.5, None, cache=cache, opener=FakeOpener())
+ for value in list(got.tmax_c) + list(got.snow_cm):
+ self.assertEqual(value, round(value, 1))
+
+ def test_cell_elevation_is_used_when_none_is_asked_for(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_normals(37.7, -119.5, None, cache=cache, opener=FakeOpener())
+ self.assertEqual(got.elev_m, 3400.0)
+
+ def test_a_second_call_reads_the_cache_not_the_network(self):
+ opener = FakeOpener()
+ with tempfile.TemporaryDirectory() as cache:
+ first = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache, opener=opener)
+ second = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache, opener=opener)
+ self.assertEqual(first, second)
+ self.assertEqual(len(opener.calls), 1)
+
+ def test_a_point_with_no_data_returns_none_not_zeros(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_normals(0.0, 0.0, None, cache=cache,
+ opener=FakeOpener("open_meteo_nodata.json"))
+ self.assertIsNone(got)
+
+ def test_the_desert_and_coast_fixtures_parse(self):
+ with tempfile.TemporaryDirectory() as cache:
+ desert = C.fetch_normals(32.2, -110.9, 800.0, cache=cache,
+ opener=FakeOpener("open_meteo_desert.json"))
+ coast = C.fetch_normals(47.6, -122.3, 10.0, cache=cache,
+ opener=FakeOpener("open_meteo_coast.json"))
+ self.assertEqual(desert.tmax_c[6], 44.0)
+ self.assertTrue(all(v == 0.0 for v in desert.snow_cm))
+ self.assertEqual(coast.tmax_c[0], 9.0)
+
+
+class NoaaTest(unittest.TestCase):
+ def setUp(self):
+ C.DELAY_S = 0
+
+ def test_noaa_fixture_becomes_point_normals(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_noaa(37.71, -119.51, 1500.0, cache=cache, opener=FakeOpener())
+ self.assertIsNotNone(got)
+ self.assertEqual(len(got.tmax_c), 12)
+ self.assertEqual(got.tmax_c[0], 10.0) # 50 F in C, no lapse change
+ self.assertIsNone(got.snow_cm) # the normals carry no snow depth
+
+ def test_noaa_lapse_adjusts_to_the_point_elevation(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_noaa(37.71, -119.51, 2500.0, cache=cache, opener=FakeOpener())
+ self.assertEqual(got.tmax_c[0], 3.5) # 10 C less 6.5 C for 1000 m
+
+ def test_noaa_returns_none_far_from_any_station(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_noaa(66.5, -65.0, None, cache=cache, opener=FakeOpener())
+ self.assertIsNone(got)
+
+
+class EcccTest(unittest.TestCase):
+ def setUp(self):
+ C.DELAY_S = 0
+
+ def test_eccc_fixture_becomes_point_normals(self):
+ with tempfile.TemporaryDirectory() as cache:
+ got = C.fetch_eccc(49.25, -123.05, None, cache=cache, opener=FakeOpener())
+ self.assertIsNotNone(got)
+ self.assertEqual(got.tmax_c[0], 6.0) # the nearer of the two stations
+ self.assertEqual(got.tmax_c[6], 24.0)
+ self.assertIsNone(got.snow_cm)
+
+
+class SourceTest(unittest.TestCase):
+ def test_the_cache_is_outside_the_repository(self):
+ self.assertFalse(os.path.abspath(C.CACHE_DIR).startswith(os.path.abspath(V.ROOT)))
+
+ def test_the_source_says_its_licence_and_period(self):
+ for key in ("name", "publisher", "url", "licence", "period"):
+ self.assertIn(key, C.SOURCE)
+ self.assertTrue(str(C.SOURCE[key]).strip())
+ self.assertIn("CC BY 4.0", C.SOURCE["licence"])
+
+
+if __name__ == "__main__":
+ unittest.main()
From 2f4bc6862ec144376987a4b081465601c5dbaf7e Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 10:25:39 -0700
Subject: [PATCH 03/30] Add the season rule as a pure function over monthly
normals
---
tools/estimate_season.py | 131 ++++++++++++++++++++++++++++
tools/tests/test_estimate_season.py | 86 ++++++++++++++++++
2 files changed, 217 insertions(+)
create mode 100644 tools/estimate_season.py
create mode 100644 tools/tests/test_estimate_season.py
diff --git a/tools/estimate_season.py b/tools/estimate_season.py
new file mode 100644
index 0000000..6c734c9
--- /dev/null
+++ b/tools/estimate_season.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Estimate a hiking season from climate, for trails no page gives one.
+
+Python 3 standard library only. The rule is a pure function over monthly
+normals (tools/season_climate.py does the downloading, cached outside
+the repository), so its tests run with no network. See
+docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md.
+
+A month is in season when the trail's high ground is normally free of
+deep snow and not bitterly cold, and its low ground is not dangerously
+hot: over the high-ground points (at or above the upper quartile of
+the sample elevations), the median mean daily high is at least
+cold_c_min and the median mean snow depth is at most snow_cm_max, and
+over the low-ground points (at or below the median elevation) the
+median mean daily high is at most heat_c_max. When no high-ground
+point has a snow measure the snow test is dropped and the cold test
+stands in for it. That gives alpine trails a summer season, desert
+trails a winter one that wraps the year end, and mild trails all
+twelve months. It cannot know that some trails are walked in snow by
+choice; the fit against sourced seasons says how often that matters.
+
+Commands are added by the plan's later tasks (fit, propose, check).
+"""
+import sys
+
+sys.dont_write_bytecode = True
+
+import statistics
+from dataclasses import dataclass
+
+RULE_VERSION = 1
+
+
+@dataclass(frozen=True)
+class SamplePoint:
+ lat: float
+ lon: float
+ elev_m: float = None
+ km: float = None
+
+
+@dataclass(frozen=True)
+class Params:
+ snow_cm_max: float
+ cold_c_min: float
+ heat_c_max: float
+
+
+def _usable(points):
+ """The points as a list, or None when any point lacks data. A trail
+ with a gap in its climate data is unestimable, never filled in."""
+ if not points:
+ return None
+ got = list(points)
+ for point in got:
+ if point is None or len(getattr(point, "tmax_c", ()) or ()) != 12:
+ return None
+ if point.snow_cm is not None and len(point.snow_cm) != 12:
+ return None
+ return got
+
+
+def _high_low(points):
+ """Split points into high ground (at or above the upper quartile of
+ the elevations, at least one point) and low ground (at or below
+ the median). A single point is both."""
+ elevs = sorted(p.elev_m for p in points)
+ if len(elevs) == 1:
+ return points, points
+ upper = statistics.quantiles(elevs, n=4, method="inclusive")[2]
+ median = statistics.median(elevs)
+ high = [p for p in points if p.elev_m >= upper]
+ low = [p for p in points if p.elev_m <= median]
+ if not high:
+ high = [max(points, key=lambda p: p.elev_m)]
+ if not low:
+ low = [min(points, key=lambda p: p.elev_m)]
+ return high, low
+
+
+def _median_at(points, month, attr):
+ values = [getattr(p, attr)[month] for p in points
+ if getattr(p, attr) is not None]
+ if not values:
+ return None
+ return round(statistics.median(values), 1)
+
+
+def _month_passes(high, low, month, params):
+ high_tmax = _median_at(high, month, "tmax_c")
+ if high_tmax is None or high_tmax < params.cold_c_min:
+ return False
+ snow = _median_at(high, month, "snow_cm")
+ if snow is not None and snow > params.snow_cm_max:
+ return False
+ low_tmax = _median_at(low, month, "tmax_c")
+ if low_tmax is None or low_tmax > params.heat_c_max:
+ return False
+ return True
+
+
+def months_in_season(points, params):
+ """Sorted month numbers in season, or None. None means either some
+ point has no data or no month qualifies; why_not says which. An
+ empty list is never returned."""
+ got = _usable(points)
+ if got is None:
+ return None
+ high, low = _high_low(got)
+ months = [m + 1 for m in range(12) if _month_passes(high, low, m, params)]
+ return months or None
+
+
+def why_not(points, params):
+ """Why months_in_season returned None, or "" when it did not."""
+ got = _usable(points)
+ if got is None:
+ return "no data for one of the sample points"
+ if months_in_season(got, params) is not None:
+ return ""
+ high, low = _high_low(got)
+ cold_ok = sum(1 for m in range(12)
+ if (_median_at(high, m, "tmax_c") or -999) >= params.cold_c_min)
+ snow_ok = sum(1 for m in range(12)
+ if (_median_at(high, m, "snow_cm") is None
+ or _median_at(high, m, "snow_cm") <= params.snow_cm_max))
+ heat_ok = sum(1 for m in range(12)
+ if (_median_at(low, m, "tmax_c") or 999) <= params.heat_c_max)
+ return (f"no month passes the cold, snow and heat tests together "
+ f"(cold passes in {cold_ok} months, snow in {snow_ok}, "
+ f"heat in {heat_ok})")
diff --git a/tools/tests/test_estimate_season.py b/tools/tests/test_estimate_season.py
new file mode 100644
index 0000000..fd20612
--- /dev/null
+++ b/tools/tests/test_estimate_season.py
@@ -0,0 +1,86 @@
+"""Tests for tools/estimate_season.py. The rule tests use hand-made
+normals, so they run with no network.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import os
+import sys
+import unittest
+
+sys.dont_write_bytecode = True
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import estimate_season as E # noqa: E402
+import season_climate as C # noqa: E402
+
+PARAMS = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
+
+
+def normals(elev, tmax, snow=None):
+ return C.PointNormals(lat=45.0, lon=-110.0, elev_m=float(elev),
+ tmax_c=tuple(float(v) for v in tmax),
+ snow_cm=None if snow is None
+ else tuple(float(v) for v in snow))
+
+
+class RuleTest(unittest.TestCase):
+ def test_a_cold_high_point_closes_the_winter(self):
+ point = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1],
+ snow=[0] * 12)
+ self.assertEqual(E.months_in_season([point], PARAMS),
+ [4, 5, 6, 7, 8, 9, 10])
+
+ def test_snow_over_the_limit_closes_a_month(self):
+ point = normals(3000, [10] * 12,
+ snow=[50, 50, 50, 50, 50, 50, 0, 0, 0, 0, 0, 0])
+ self.assertEqual(E.months_in_season([point], PARAMS),
+ [7, 8, 9, 10, 11, 12])
+
+ def test_heat_at_the_low_ground_closes_a_summer_month(self):
+ desert = normals(400, [19, 22, 26, 31, 36, 42, 44, 43, 39, 32, 24, 19],
+ snow=[0] * 12)
+ got = E.months_in_season([desert], PARAMS)
+ self.assertEqual(set(got), {10, 11, 12, 1, 2, 3, 4})
+ self.assertEqual(got, [1, 2, 3, 4, 10, 11, 12])
+
+ def test_high_ground_is_the_upper_quartile_of_points(self):
+ low = [normals(e, [15] * 12, snow=[0] * 12) for e in (100, 200, 300)]
+ top_snow = [0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0]
+ high = normals(400, [15] * 12, snow=top_snow)
+ got = E.months_in_season(low + [high], PARAMS)
+ self.assertNotIn(6, got) # only the highest point has June snow
+ self.assertEqual(len(got), 11)
+
+ def test_no_snow_measure_uses_temperature_alone(self):
+ point = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1],
+ snow=None)
+ self.assertEqual(E.months_in_season([point], PARAMS),
+ [4, 5, 6, 7, 8, 9, 10])
+
+ def test_a_wrapped_season_is_returned_sorted(self):
+ point = normals(400, [15, 15, 15, 15, 15, 40, 40, 40, 40, 40, 15, 15],
+ snow=[0] * 12)
+ self.assertEqual(E.months_in_season([point], PARAMS),
+ [1, 2, 3, 4, 5, 11, 12])
+
+ def test_no_qualifying_month_is_none_with_a_reason(self):
+ arctic = normals(500, [-5] * 12, snow=[30] * 12)
+ self.assertIsNone(E.months_in_season([arctic], PARAMS))
+ self.assertIn("no month", E.why_not([arctic], PARAMS))
+
+ def test_all_twelve_months_is_allowed(self):
+ coast = normals(20, [15] * 12, snow=[0] * 12)
+ self.assertEqual(E.months_in_season([coast], PARAMS), list(range(1, 13)))
+ self.assertEqual(E.why_not([coast], PARAMS), "")
+
+ def test_a_point_with_missing_data_makes_the_trail_unestimable(self):
+ point = normals(20, [15] * 12, snow=[0] * 12)
+ self.assertIsNone(E.months_in_season([point, None], PARAMS))
+ self.assertIn("no data", E.why_not([point, None], PARAMS))
+ self.assertIsNone(E.months_in_season([], PARAMS))
+ self.assertIn("no data", E.why_not([], PARAMS))
+
+
+if __name__ == "__main__":
+ unittest.main()
From f7e2757e2b5665e83e99398c5d2bdda68c70c9dc Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 10:28:52 -0700
Subject: [PATCH 04/30] Sample points along a track, from the ends, or from the
place
---
tools/estimate_season.py | 267 +++++++++++++++++++++++++++-
tools/tests/test_estimate_season.py | 118 ++++++++++++
2 files changed, 384 insertions(+), 1 deletion(-)
diff --git a/tools/estimate_season.py b/tools/estimate_season.py
index 6c734c9..d1bdc2c 100644
--- a/tools/estimate_season.py
+++ b/tools/estimate_season.py
@@ -25,8 +25,18 @@ import sys
sys.dont_write_bytecode = True
+import bisect
+import json
+import math
+import os
import statistics
-from dataclasses import dataclass
+import tomllib
+from dataclasses import dataclass, replace
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+
+import season_climate # noqa: E402 (types and distance only; no network)
RULE_VERSION = 1
@@ -129,3 +139,258 @@ def why_not(points, params):
return (f"no month passes the cold, snow and heat tests together "
f"(cold passes in {cold_ok} months, snow in {snow_ok}, "
f"heat in {heat_ok})")
+
+
+# ---------------------------------------------------------------------------
+# Sample points from a record. Track pieces are joined and oriented with
+# the same rule tools/elevation.py uses to build elevation.json (ends
+# within 100 m join, the whole track runs south to north or west to
+# east, parts in order along that axis, gaps between parts not counted
+# in the distance), reimplemented here with the standard library only,
+# so a sample point's kilometre matches the profile's kilometre and its
+# elevation can be read from the profile.
+
+EARTH_R_M = 6371008.8
+JOIN_GAP_M = 100.0
+LOOP_FRACTION = 0.1
+SAMPLE_KM = 50.0
+MIN_POINTS = 3
+MAX_POINTS = 12
+
+
+def _track_parts(data):
+ 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 [[(float(c[0]), float(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_M
+
+
+def _seg_km(a, b):
+ return season_climate.haversine_km(a[1], a[0], b[1], b[0])
+
+
+def _join_parts(parts, gap_m=JOIN_GAP_M):
+ if not parts:
+ return []
+ cell = max(gap_m, 1.0)
+ k = math.pi / 180.0 * EARTH_R_M
+ 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(chains):
+ """Chains turned to run south to north or west to east and put in
+ order along that axis, as tools/elevation.py does."""
+ if not chains:
+ return []
+ 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))
+ axis = 1 if (max(lats) - min(lats)) > width else 0
+ out = []
+ for ch in chains:
+ length_km = sum(_seg_km(a, b) for a, b in zip(ch, ch[1:]))
+ if (_gap_m(ch[0], ch[-1]) > LOOP_FRACTION * length_km * 1000.0
+ 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
+
+
+def _ordered_track(path):
+ """(vertices, cumulative km) along the joined, oriented track.
+ The first vertex of each part sits at the same distance as the last
+ vertex of the part before it: gaps are not counted."""
+ with open(path, encoding="utf-8") as f:
+ data = json.load(f)
+ chains = _orient(_join_parts(_track_parts(data)))
+ verts, cum = [], []
+ total = 0.0
+ for chain in chains:
+ for j, vertex in enumerate(chain):
+ if j:
+ total += _seg_km(chain[j - 1], vertex)
+ verts.append(vertex)
+ cum.append(total)
+ return verts, cum
+
+
+def _point_at(verts, cum, target_km):
+ i = bisect.bisect_right(cum, target_km) - 1
+ i = max(0, min(i, len(verts) - 2))
+ span = cum[i + 1] - cum[i]
+ frac = 0.0 if span <= 0 else (target_km - cum[i]) / span
+ frac = max(0.0, min(1.0, frac))
+ lon = verts[i][0] + frac * (verts[i + 1][0] - verts[i][0])
+ lat = verts[i][1] + frac * (verts[i + 1][1] - verts[i][1])
+ if target_km >= cum[-1]:
+ lon, lat = verts[-1]
+ return lat, lon
+
+
+def _profile_elev(profile, km):
+ """Elevation in metres from an elevation.json profile at km."""
+ if not profile:
+ return None
+ kms = [float(p[0]) for p in profile]
+ i = bisect.bisect_right(kms, km) - 1
+ if i < 0:
+ return float(profile[0][1])
+ if i >= len(profile) - 1:
+ return float(profile[-1][1])
+ km0, el0 = float(profile[i][0]), float(profile[i][1])
+ km1, el1 = float(profile[i + 1][0]), float(profile[i + 1][1])
+ if km1 <= km0:
+ return el1
+ return el0 + (km - km0) / (km1 - km0) * (el1 - el0)
+
+
+def _load_profile(root, tid):
+ path = os.path.join(root, tid, "elevation.json")
+ if not os.path.exists(path):
+ return None, None
+ with open(path, encoding="utf-8") as f:
+ doc = json.load(f)
+ return doc.get("profile") or None, (doc.get("highest") or None)
+
+
+def _give_high_point(points, hike, highest):
+ """With no profile, one point carries high_point_m so the high
+ ground is represented at all: the point nearest the profile's
+ highest place when that is known, else the first point."""
+ high_m = hike.get("high_point_m")
+ if high_m is None or not points:
+ return points
+ idx = 0
+ if highest and highest.get("lat") is not None:
+ idx = min(range(len(points)),
+ key=lambda i: season_climate.haversine_km(
+ points[i].lat, points[i].lon,
+ float(highest["lat"]), float(highest["lon"])))
+ return [replace(p, elev_m=float(high_m)) if i == idx else p
+ for i, p in enumerate(points)]
+
+
+def sample_points(root, rec):
+ """Sample points for a record and how they were got: "track" (one
+ per 50 km of track, at least 3, at most 12, evenly spaced, with
+ elevations from the profile), "ends" (hike.start_lonlat and
+ hike.end_lonlat), or "place" (the centre of the first region's box
+ in web/place-bounds.toml). An elevation of None lets the climate
+ source supply its own cell elevation. With no profile, one point
+ carries hike.high_point_m when the record has one."""
+ tid = rec.get("id") or ""
+ hike = rec.get("hike") or {}
+ line_file = (rec.get("source") or {}).get("line_file") or "line.geojson"
+ line_path = os.path.join(root, tid, line_file)
+ if tid and os.path.exists(line_path):
+ try:
+ verts, cum = _ordered_track(line_path)
+ except (OSError, ValueError, KeyError, TypeError, IndexError):
+ verts, cum = [], []
+ if len(verts) >= 2 and cum and cum[-1] > 0:
+ total = cum[-1]
+ n = min(MAX_POINTS, max(MIN_POINTS, int(round(total / SAMPLE_KM)) + 1))
+ profile, highest = _load_profile(root, tid)
+ points = []
+ for i in range(n):
+ target = total * i / (n - 1)
+ lat, lon = _point_at(verts, cum, target)
+ elev = _profile_elev(profile, target)
+ points.append(SamplePoint(lat=lat, lon=lon, elev_m=elev,
+ km=round(target, 2)))
+ if not profile:
+ points = _give_high_point(points, hike, highest)
+ return points, "track"
+
+ ends = []
+ for key in ("start_lonlat", "end_lonlat"):
+ value = hike.get(key)
+ if value and len(value) == 2:
+ ends.append(SamplePoint(lat=float(value[1]), lon=float(value[0]),
+ elev_m=None, km=None))
+ if ends:
+ if hike.get("high_point_m") is not None:
+ ends[0] = replace(ends[0], elev_m=float(hike["high_point_m"]))
+ return ends, "ends"
+
+ regions = rec.get("regions") or []
+ country = rec.get("country") or ""
+ bounds_path = os.path.join(root, "web", "place-bounds.toml")
+ if regions and os.path.exists(bounds_path):
+ with open(bounds_path, "rb") as f:
+ boxes = (tomllib.load(f) or {}).get("box") or {}
+ box = boxes.get(f"{country}-{regions[0]}")
+ if box is None:
+ for key, value in boxes.items():
+ if key.endswith("-" + str(regions[0])):
+ box = value
+ break
+ if box and len(box) == 4:
+ elev = hike.get("high_point_m")
+ return [SamplePoint(lat=(float(box[1]) + float(box[3])) / 2,
+ lon=(float(box[0]) + float(box[2])) / 2,
+ elev_m=None if elev is None else float(elev),
+ km=None)], "place"
+ return [], "place"
diff --git a/tools/tests/test_estimate_season.py b/tools/tests/test_estimate_season.py
index fd20612..a1bc3e2 100644
--- a/tools/tests/test_estimate_season.py
+++ b/tools/tests/test_estimate_season.py
@@ -82,5 +82,123 @@ class RuleTest(unittest.TestCase):
self.assertIn("no data", E.why_not([], PARAMS))
+class SamplePointsTest(unittest.TestCase):
+ def make_root(self, td, parts=None, profile=None, multi=False):
+ import json
+ import tempfile # noqa: F401 (td is made by the caller)
+ d = os.path.join(td, "trail-x")
+ os.makedirs(os.path.join(td, "web"))
+ os.makedirs(d)
+ with open(os.path.join(td, "web", "place-bounds.toml"), "w") as f:
+ f.write('[box]\n"US-VT" = [-73.5, 42.7, -71.5, 45.0]\n')
+ if parts is not None:
+ if multi:
+ geom = {"type": "MultiLineString", "coordinates": parts}
+ else:
+ geom = {"type": "LineString", "coordinates": parts[0]}
+ doc = {"type": "FeatureCollection",
+ "features": [{"type": "Feature", "geometry": geom}]}
+ with open(os.path.join(d, "line.geojson"), "w") as f:
+ json.dump(doc, f)
+ if profile is not None:
+ with open(os.path.join(d, "elevation.json"), "w") as f:
+ json.dump({"profile": profile}, f)
+ return td
+
+ @staticmethod
+ def meridian(lat0, lat1, step=0.1, lon=-110.0):
+ n = int(round((lat1 - lat0) / step))
+ return [[lon, lat0 + i * step] for i in range(n + 1)]
+
+ def rec(self, **hike):
+ base = {"summary": "x", "checked": "2026-01-01", "source": []}
+ base.update(hike)
+ return {"id": "trail-x", "country": "US", "regions": ["VT"],
+ "source": {"line_file": "line.geojson"}, "hike": base}
+
+ def test_a_track_gives_points_spaced_along_it(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td, parts=[self.meridian(43.0, 44.8)],
+ profile=[[0, 1000], [200, 1000]])
+ points, kind = E.sample_points(root, self.rec())
+ self.assertEqual(kind, "track")
+ self.assertEqual(len(points), 5) # about 200 km, one per 50 km
+ self.assertEqual(points[0].km, 0.0)
+ self.assertAlmostEqual(points[0].lat, 43.0, places=3)
+ self.assertLess(abs(points[-1].km - 200.15), 50)
+ self.assertAlmostEqual(points[-1].lat, 44.8, places=3)
+
+ def test_a_short_track_still_gets_three_points(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td, parts=[self.meridian(43.0, 43.09, 0.03)],
+ profile=[[0, 500], [10, 500]])
+ points, kind = E.sample_points(root, self.rec())
+ self.assertEqual(len(points), 3)
+
+ def test_a_very_long_track_is_capped_at_twelve(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td, parts=[self.meridian(35.0, 45.0, 0.5)],
+ profile=[[0, 500], [1112, 500]])
+ points, kind = E.sample_points(root, self.rec())
+ self.assertEqual(len(points), 12)
+
+ def test_a_multipart_track_is_sampled_along_all_parts(self):
+ import tempfile
+ parts = [self.meridian(43.0, 43.9), self.meridian(44.1, 45.0)]
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td, parts=parts, multi=True,
+ profile=[[0, 500], [200, 500]])
+ points, kind = E.sample_points(root, self.rec())
+ self.assertEqual(kind, "track")
+ self.assertTrue(any(p.lat > 44.1 for p in points))
+ self.assertTrue(any(p.lat < 43.9 for p in points))
+
+ def test_elevation_comes_from_the_profile_by_distance(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td, parts=[self.meridian(43.0, 44.8)],
+ profile=[[0, 1000], [100, 2000], [200, 1500]])
+ points, kind = E.sample_points(root, self.rec())
+ middle = points[len(points) // 2]
+ self.assertLess(abs(middle.elev_m - 2000), 30)
+ self.assertLess(abs(points[0].elev_m - 1000), 30)
+
+ def test_a_track_without_a_profile_uses_the_high_point_for_the_top_only(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td, parts=[self.meridian(43.0, 44.8)])
+ points, kind = E.sample_points(root, self.rec(high_point_m=3000))
+ elevs = [p.elev_m for p in points]
+ self.assertEqual(elevs.count(3000), 1)
+ self.assertEqual(elevs.count(None), len(elevs) - 1)
+
+ def test_no_track_uses_the_two_ends(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td)
+ points, kind = E.sample_points(
+ root, self.rec(start_lonlat=[-110.0, 43.0],
+ end_lonlat=[-109.0, 44.0]))
+ self.assertEqual(kind, "ends")
+ self.assertEqual(len(points), 2)
+ self.assertEqual((points[0].lat, points[0].lon), (43.0, -110.0))
+ self.assertEqual((points[1].lat, points[1].lon), (44.0, -109.0))
+
+ def test_no_track_and_no_ends_uses_the_place_centre(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ root = self.make_root(td)
+ points, kind = E.sample_points(root, self.rec())
+ self.assertEqual(kind, "place")
+ self.assertEqual(len(points), 1)
+ self.assertTrue(-73.5 <= points[0].lon <= -71.5)
+ self.assertTrue(42.7 <= points[0].lat <= 45.0)
+ self.assertAlmostEqual(points[0].lon, -72.5)
+ self.assertAlmostEqual(points[0].lat, 43.85)
+
+
if __name__ == "__main__":
unittest.main()
From 987a25c6cbc6afeacb0dc74386ce50f4195ee5d9 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 10:50:09 -0700
Subject: [PATCH 05/30] Shorten the climate period to what the free hourly
limit allows, and wait out that limit
---
NOTICE.md | 2 +-
tools/season_climate.py | 59 +++++++++++++++++++++---------
tools/tests/test_season_climate.py | 20 ++++++++++
3 files changed, 63 insertions(+), 18 deletions(-)
diff --git a/NOTICE.md b/NOTICE.md
index 5cdecc2..263bec8 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -30,4 +30,4 @@ The files `elevation.json` in the trail directories are computed from each trail
## Climate
-A season marked as estimated is worked out from monthly climate at the trail's elevation. The climate values are monthly means for 2011 to 2020 computed by `tools/season_climate.py` from daily ERA5-Land data served by Open-Meteo.com (https://open-meteo.com/en/docs/historical-weather-api). Weather data by Open-Meteo.com, offered under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/); the reanalysis behind it is the Copernicus Climate Change Service's. Only the estimated seasons derive from it. Each estimated record names it in its sources, and the estimates themselves say they are estimates wherever they are shown.
+A season marked as estimated is worked out from monthly climate at the trail's elevation. The climate values are monthly means for 2018 to 2020 computed by `tools/season_climate.py` from daily ERA5-Land data served by Open-Meteo.com (https://open-meteo.com/en/docs/historical-weather-api). Weather data by Open-Meteo.com, offered under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/); the reanalysis behind it is the Copernicus Climate Change Service's. Only the estimated seasons derive from it. Each estimated record names it in its sources, and the estimates themselves say they are estimates wherever they are shown.
diff --git a/tools/season_climate.py b/tools/season_climate.py
index be9e556..973be73 100644
--- a/tools/season_climate.py
+++ b/tools/season_climate.py
@@ -13,8 +13,13 @@ Source chosen
=============
ERA5-Land through the Open-Meteo Historical Weather API: daily maximum
temperature and daily maximum snow depth, averaged by month over
-2011-2020, at the elevation asked for (the API adjusts both values to
-that elevation). SOURCE below names it for the record entries.
+2018-2020, at the elevation asked for (the API adjusts both values to
+that elevation). SOURCE below names it for the record entries. The
+three years are a limit of the free API, not a preference; see the
+licence note below. The trial tables at the end were run on 2011-2020
+means, before that limit was measured. The choice does not turn on
+the years: the losing sources lack snow depth, values at the asked
+elevation and the other country on any years.
Licences, read on each publisher's own terms page (2026-11-20):
@@ -25,15 +30,20 @@ Licences, read on each publisher's own terms page (2026-11-20):
purposes." and "Less than 10'000 API calls per day, 5'000 per hour
and 600 per minute." This dataset is a public, non-commercial one, and
the CC BY 4.0 data licence is met by the attribution in NOTICE.md and
- the source entry on each estimated record. The rate limit is why the
- period is the last ten years of the normals period and not all
- thirty: one point for 1991-2020 costs about 156 of the 600 units
- allowed per minute, so the roughly 900 sample points would need about
- five hours of throttled requests; ten years cost about 52 units a
- point. The rule's thresholds are fitted on the same ten years, so a
- steady offset between the decade and the thirty year normals is
- mostly absorbed by the fit. Widening the period later only refills
- the cache.
+ the source entry on each estimated record. The binding limit in
+ practice is the hourly one the API reports on a refusal: 5000
+ weighted units an hour, where one point costs about 5 units per
+ year of daily data for the two measures. All thirty normals years
+ for the roughly 900 sample points would cost about 139000 units,
+ some 28 hours of throttled requests, and ten years about 9 hours,
+ so the period is three years (about 14000 units, under 3 hours from
+ an empty cache, and nothing once cached). The rule's thresholds are
+ fitted on the same three years, so a steady offset between those
+ years and the thirty year normals is mostly absorbed by the fit.
+ Widening the period later only refills the cache, which is keyed
+ by period so the two never mix. Requests that meet the hourly
+ limit wait as long as the API asks and then retry, so a long run
+ pauses instead of failing.
- NOAA (US only), https://www.weather.gov/disclaimer: "The information
on National Weather Service (NWS) Web pages are in the public domain,
unless specifically noted otherwise, and may be used without charge
@@ -143,13 +153,13 @@ SOURCE = {
"publisher": "Open-Meteo.com",
"url": "https://open-meteo.com/en/docs/historical-weather-api",
"licence": "CC BY 4.0",
- "period": "2011-2020",
+ "period": "2018-2020",
}
USER_AGENT = "Mozilla/5.0"
DELAY_S = 0.15
LAPSE_C_PER_KM = 6.5
-ERA5_YEARS = (2011, 2020)
+ERA5_YEARS = (2018, 2020)
NOAA_MAX_KM = 150.0
ECCC_MAX_KM = 250.0
@@ -189,9 +199,17 @@ def _pace():
time.sleep(wait)
+def _retry_after_s(exc):
+ headers = getattr(exc, "headers", None) or getattr(exc, "hdrs", None) or {}
+ try:
+ return max(5.0, min(float(headers.get("Retry-After")), 1200.0))
+ except (TypeError, ValueError):
+ return 65.0
+
+
def _get_bytes(url, opener, timeout=180):
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
- for attempt in range(4):
+ for attempt in range(20):
_pace()
try:
with opener(req, timeout=timeout) as resp:
@@ -205,8 +223,12 @@ def _get_bytes(url, opener, timeout=180):
return raw
except urllib.error.HTTPError as exc:
_LAST_AT[0] = time.time()
- if exc.code == 429 and attempt < 3:
- time.sleep(65)
+ if exc.code == 429 and attempt < 19:
+ # The hourly allowance refills as old requests age out.
+ # Wait as long as the API asks, then try the same
+ # request again; the point is fetched once either way.
+ _REMAINING[0] = None
+ time.sleep(_retry_after_s(exc) + 5)
continue
raise
@@ -304,7 +326,10 @@ def parse_open_meteo(raw, lat, lon, elev_m):
def fetch_open_meteo(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
lat, lon = _rounded(lat, lon)
- path = _cache_path(cache, "open-meteo", lat, lon, elev_m)
+ # The years are in the cache name so a widened period later never
+ # reads means computed over different years.
+ path = _cache_path(cache, f"open-meteo-{ERA5_YEARS[0]}-{ERA5_YEARS[1]}",
+ lat, lon, elev_m)
hit, got = _read_cache(path)
if hit:
return got
diff --git a/tools/tests/test_season_climate.py b/tools/tests/test_season_climate.py
index 28f2f0b..7d4d4bc 100644
--- a/tools/tests/test_season_climate.py
+++ b/tools/tests/test_season_climate.py
@@ -92,6 +92,26 @@ class OpenMeteoTest(unittest.TestCase):
opener=FakeOpener("open_meteo_nodata.json"))
self.assertIsNone(got)
+ def test_a_429_is_retried_after_a_pause(self):
+ import urllib.error
+ from unittest import mock
+ calls = []
+
+ def flaky(req, timeout=None):
+ calls.append(req.full_url)
+ if len(calls) == 1:
+ raise urllib.error.HTTPError(
+ req.full_url, 429, "Too Many Requests",
+ {"Retry-After": "0"}, None)
+ return FakeResponse(fixture_bytes("open_meteo_alpine.json"))
+
+ with tempfile.TemporaryDirectory() as cache:
+ with mock.patch.object(C.time, "sleep", lambda s: None):
+ got = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache,
+ opener=flaky)
+ self.assertIsNotNone(got)
+ self.assertEqual(len(calls), 2)
+
def test_the_desert_and_coast_fixtures_parse(self):
with tempfile.TemporaryDirectory() as cache:
desert = C.fetch_normals(32.2, -110.9, 800.0, cache=cache,
From a2423e0ba5593a9cc632968799a5a3e7b92681ec Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 11:34:19 -0700
Subject: [PATCH 06/30] Read climate normals from the CHELSA grids in place,
with ETOPO elevation, instead of the rate-limited API
Co-Authored-By: Claude Sonnet 5.5
---
NOTICE.md | 2 +-
tools/season_climate.py | 783 ++++++++----------
.../fixtures/season/eccc_normals.geojson | 1 -
.../fixtures/season/noaa_USW00000001.csv | 13 -
.../fixtures/season/noaa_USW00000002.csv | 13 -
.../fixtures/season/noaa_USW00000003.csv | 13 -
tools/tests/fixtures/season/noaa_stations.txt | 3 -
.../fixtures/season/open_meteo_alpine.json | 1 -
.../fixtures/season/open_meteo_coast.json | 1 -
.../fixtures/season/open_meteo_desert.json | 1 -
.../fixtures/season/open_meteo_nodata.json | 1 -
tools/tests/test_season_climate.py | 323 +++++---
12 files changed, 570 insertions(+), 585 deletions(-)
delete mode 100644 tools/tests/fixtures/season/eccc_normals.geojson
delete mode 100644 tools/tests/fixtures/season/noaa_USW00000001.csv
delete mode 100644 tools/tests/fixtures/season/noaa_USW00000002.csv
delete mode 100644 tools/tests/fixtures/season/noaa_USW00000003.csv
delete mode 100644 tools/tests/fixtures/season/noaa_stations.txt
delete mode 100644 tools/tests/fixtures/season/open_meteo_alpine.json
delete mode 100644 tools/tests/fixtures/season/open_meteo_coast.json
delete mode 100644 tools/tests/fixtures/season/open_meteo_desert.json
delete mode 100644 tools/tests/fixtures/season/open_meteo_nodata.json
diff --git a/NOTICE.md b/NOTICE.md
index 263bec8..f550a51 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -30,4 +30,4 @@ The files `elevation.json` in the trail directories are computed from each trail
## Climate
-A season marked as estimated is worked out from monthly climate at the trail's elevation. The climate values are monthly means for 2018 to 2020 computed by `tools/season_climate.py` from daily ERA5-Land data served by Open-Meteo.com (https://open-meteo.com/en/docs/historical-weather-api). Weather data by Open-Meteo.com, offered under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/); the reanalysis behind it is the Copernicus Climate Change Service's. Only the estimated seasons derive from it. Each estimated record names it in its sources, and the estimates themselves say they are estimates wherever they are shown.
+A season marked as estimated is worked out from monthly climate at the trail's elevation. The climate values are monthly means of daily maximum temperature for 1981 to 2010 from CHELSA V2.1 (https://www.chelsa-climate.org/datasets/chelsa_climatologies, released under CC0 1.0), read by `tools/season_climate.py`, with grid elevation from NOAA's ETOPO 2022 relief model (unrestricted version, https://www.ncei.noaa.gov/products/etopo-global-relief-model). CHELSA asks for this citation: Karger, D. N., Conrad, O., Boehner, J., Kawohl, T., Kreft, H., Soria-Auza, R. W., Zimmermann, N. E., Linder, H. P., Kessler, M. (2017). Climatologies at high resolution for the earth's land surface areas. Scientific Data 4, 170122, https://doi.org/10.1038/sdata.2017.122. Only the estimated seasons derive from it. Each estimated record names it in its sources, and the estimates themselves say they are estimates wherever they are shown.
diff --git a/tools/season_climate.py b/tools/season_climate.py
index 973be73..35f1104 100644
--- a/tools/season_climate.py
+++ b/tools/season_climate.py
@@ -1,170 +1,108 @@
-"""Monthly climate normals for a point, downloaded once and cached.
+"""Monthly climate normals for a point, read from bulk gridded files.
Python 3 standard library only. The estimator (tools/estimate_season.py)
-asks this module for the normals at a trail's sample points. Network use
-happens only when the cache lacks a point. Every response is cached
-outside the repository, requests go one at a time with a short pause, and
-the same point is never requested twice (a point with no data is cached
-as having no data). Run the trial with:
-
- python3 tools/estimate_season.py trial
+asks this module for the normals at a trail's sample points. The grids
+are large public files read in place: only the 512 pixel tiles that
+cover a point are fetched (HTTP range requests), each tile is cached
+outside the repository once, and the values for a point are cached as
+one small file. There is no rate limit to wait out; a tile is never
+fetched twice, and an interrupted run resumes from the cache.
Source chosen
=============
-ERA5-Land through the Open-Meteo Historical Weather API: daily maximum
-temperature and daily maximum snow depth, averaged by month over
-2018-2020, at the elevation asked for (the API adjusts both values to
-that elevation). SOURCE below names it for the record entries. The
-three years are a limit of the free API, not a preference; see the
-licence note below. The trial tables at the end were run on 2011-2020
-means, before that limit was measured. The choice does not turn on
-the years: the losing sources lack snow depth, values at the asked
-elevation and the other country on any years.
+CHELSA V2.1 climatologies (monthly mean daily maximum near-surface air
+temperature, 1981-2010, about 1 km, global land), from WSL, with the
+elevation of the grid cell taken from NOAA's ETOPO 2022 relief model
+(60 arc second, unrestricted version). The temperature at a trail's own
+elevation is the cell's value plus a lapse rate of 6.5 C per km times
+the cell's elevation minus the trail's. The source carries no snow
+variable, so snow-free months are derived from the temperature at the
+trail's high ground (the rule's cold limit stands in for snow) and the
+estimate says so.
-Licences, read on each publisher's own terms page (2026-11-20):
+Why the first choice was dropped. The previous choice was ERA5-Land
+served by the Open-Meteo Historical Weather API. Its free tier
+allows 5000 weighted units an hour, and one point-year of daily data
+for two variables costs about 5 units, so a thirty year normal for the
+roughly 900 sample points needs about 139000 units (some 28 hours) and
+ten years about 9 hours; only three years fit in about three hours, and
+three years is too short to call a normal. Its terms also limit the
+free tier to non-commercial use. A bulk grid read locally has no such
+limit.
-- Open-Meteo licence page, https://open-meteo.com/en/licence:
- "API data are offered under Attribution 4.0 International (CC BY 4.0)".
- Its terms page, https://open-meteo.com/en/terms, adds for the free
- API: "You may only use the free API services for non-commercial
- purposes." and "Less than 10'000 API calls per day, 5'000 per hour
- and 600 per minute." This dataset is a public, non-commercial one, and
- the CC BY 4.0 data licence is met by the attribution in NOTICE.md and
- the source entry on each estimated record. The binding limit in
- practice is the hourly one the API reports on a refusal: 5000
- weighted units an hour, where one point costs about 5 units per
- year of daily data for the two measures. All thirty normals years
- for the roughly 900 sample points would cost about 139000 units,
- some 28 hours of throttled requests, and ten years about 9 hours,
- so the period is three years (about 14000 units, under 3 hours from
- an empty cache, and nothing once cached). The rule's thresholds are
- fitted on the same three years, so a steady offset between those
- years and the thirty year normals is mostly absorbed by the fit.
- Widening the period later only refills the cache, which is keyed
- by period so the two never mix. Requests that meet the hourly
- limit wait as long as the API asks and then retry, so a long run
- pauses instead of failing.
-- NOAA (US only), https://www.weather.gov/disclaimer: "The information
- on National Weather Service (NWS) Web pages are in the public domain,
- unless specifically noted otherwise, and may be used without charge
- for any lawful purpose". The 1991-2020 monthly normals are station
- values, and the product carries temperature and precipitation only:
- its station files have no snow depth variable, so the snow test
- would be dropped. SNODAS snow depth is a separate daily US grid with
- no point service.
-- Environment and Climate Change Canada (Canada only), normals under
- the Open Government Licence, Canada,
- https://open.canada.ca/en/open-government-licence-canada: "The
- Information Provider grants you a worldwide, royalty-free, perpetual,
- non-exclusive licence to use the Information, including for
- commercial purposes", with acknowledgement of the source. The MSC
- GeoMet normals collection trialled here is the 1981-2010 station
- normals. It has mean daily maximum temperature but no snow depth
- (total snowfall is not depth), and its features carry no station
- elevation, so no lapse adjustment to a trail's high ground is
- possible.
+Why not the other bulk grids. WorldClim 2.1 (monthly 1970-2000, free
+download) states at https://www.worldclim.org/about.html: "The data are
+freely available for academic use and other non-commercial use.
+Redistribution or commercial use is not allowed without prior
+permission." That fails the public domain or open licence test. NOAA
+and Environment Canada station normals lack the coverage of both
+countries and a value at a trail's elevation (see the earlier trial in
+the repository history).
-Why the others lost: neither station product covers both countries,
-neither gives snow depth, and neither gives values at the elevation of
-a trail's high ground, which is what decides when an alpine trail
-opens. Stations also thin out exactly where trails are wildest (the
-trial's far north point has no station in range). Open-Meteo returns
-temperature and snow depth at the elevation asked for, for every
-trial trail in both countries. Its weakness is the free API's
-non-commercial access term, recorded above for the owner.
+Licences, read on each publisher's own page (2026-11-20):
-Trial (twelve sourced trails, 2026-11-20, one coarse default rule
-for every candidate: the high point at least 5 C and at most 10 cm of
-snow where snow exists, the low point at most 32 C; high and low track
-points only, place centres for akshayuk-pass and
-desert-winter-thru-hike, which have no track or ends; rerun with the
-trial command above once the estimator exists). The akshayuk-pass
-place centre falls in water, where the land model has no values, and
-no station is in range, so every candidate lacks data there. NOAA
-reached west-coast-trail across the border from a US station.
+- CHELSA, https://www.chelsa-climate.org/datasets/chelsa_climatologies,
+ field License: "Creative Commons Zero - No Rights Reserved (CC0 1.0)".
+ The same page asks for the citation: Karger, D. N., Conrad, O.,
+ Boehner, J., Kawohl, T., Kreft, H., Soria-Auza, R. W., Zimmermann,
+ N. E., Linder, H. P., Kessler, M. (2017). Climatologies at high
+ resolution for the earth's land surface areas. Scientific Data 4,
+ 170122. https://doi.org/10.1038/sdata.2017.122. It is credited in
+ NOTICE.md although CC0 does not require it.
+- ETOPO 2022, https://www.ncei.noaa.gov/products/etopo-global-relief-model:
+ the Unrestricted version is described as "Full global coverage, no
+ copyright or security distribution restrictions". NOAA NCEI, DOI
+ 10.25921/fd45-gt74.
- open-meteo: trail (sourced months) gives estimated months, grade
- akshayuk-pass (7,8): no data
- great-divide-trail (7,8,9): 7,8,9, exact
- west-coast-trail (5,6,7,8,9): all year, worse
- john-muir (7,8,9): 6,7,8,9, within1
- colorado-trail (7,8,9): 7,8,9, exact
- uinta-highline (7,8,9): 7,8,9, exact
- desert-winter-thru-hike (12,1,2): 1,2,3,4,5,8,9,10,11,12, worse
- arizona (2,3,9,10): 3,4,10,11, within1
- florida (10,11,12,1,2,3,4): all year, worse
- washington-coast-trail (5,6,7,8,9): all year, worse
- maah-daah-hey (all year): 3,4,5,6,7,8,9,10,11, worse
- superior-hiking (6,7,8,9): 5,6,7,8,9,10, within1
- Data for 11 of 12, exact or within one month for 6 of the 11.
-
- noaa: trail (sourced months) gives estimated months, grade
- akshayuk-pass (7,8): no data
- great-divide-trail (7,8,9): no data
- west-coast-trail (5,6,7,8,9): all year, worse
- john-muir (7,8,9): 5,6,7,8,9,10, worse
- colorado-trail (7,8,9): 5,6,7,8,9,10, worse
- uinta-highline (7,8,9): 5,6,7,8,9, worse
- desert-winter-thru-hike (12,1,2): 1,2,3,4,5,9,10,11,12, worse
- arizona (2,3,9,10): 4,10, worse
- florida (10,11,12,1,2,3,4): all year, worse
- washington-coast-trail (5,6,7,8,9): all year, worse
- maah-daah-hey (all year): 3,4,5,6,7,8,9,10,11, worse
- superior-hiking (6,7,8,9): 4,5,6,7,8,9,10, worse
- Data for 10 of 12, exact or within one month for 0 of the 10. With
- no snow measure the alpine seasons all open about two months early.
-
- eccc: trail (sourced months) gives estimated months, grade
- akshayuk-pass (7,8): no data
- great-divide-trail (7,8,9): 4,5,6,7,8,9,10, worse
- west-coast-trail (5,6,7,8,9): all year, worse
- john-muir (7,8,9): no data
- colorado-trail (7,8,9): no data
- uinta-highline (7,8,9): no data
- desert-winter-thru-hike (12,1,2): no data
- arizona (2,3,9,10): no data
- florida (10,11,12,1,2,3,4): no data
- washington-coast-trail (5,6,7,8,9): partial data
- maah-daah-hey (all year): no data
- superior-hiking (6,7,8,9): partial data
- Data for 2 of 12 (the Canadian trails), exact or within one month
- for 0 of the 2.
+Reading the files. Both are tiled GeoTIFFs. CHELSA's tiles are LZW with a
+horizontal predictor, 16 bit unsigned, value times 0.1 in kelvin; ETOPO's
+are deflate with the floating point predictor. The small readers below
+handle exactly those two layouts and refuse anything else, so no library
+is needed in CI or in `web/`.
"""
import sys
sys.dont_write_bytecode = True
-import csv
-import io
+import array
+import hashlib
import json
import math
import os
+import re
+import struct
+import tempfile
+import threading
import time
import urllib.error
-import urllib.parse
import urllib.request
+import zlib
from dataclasses import dataclass
CACHE_DIR = os.environ.get("LONGHIKES_CLIMATE_CACHE") or os.path.join(
os.path.expanduser("~"), ".cache", "longhikes-climate")
SOURCE = {
- "name": "ERA5-Land via Open-Meteo",
- "publisher": "Open-Meteo.com",
- "url": "https://open-meteo.com/en/docs/historical-weather-api",
- "licence": "CC BY 4.0",
- "period": "2018-2020",
+ "name": "CHELSA V2.1 climatologies, with ETOPO 2022 elevation",
+ "publisher": "WSL (CHELSA) and NOAA NCEI (ETOPO)",
+ "url": "https://www.chelsa-climate.org/datasets/chelsa_climatologies",
+ "licence": "CC0 1.0 (CHELSA); NOAA ETOPO 2022 unrestricted",
+ "period": "1981-2010",
}
-USER_AGENT = "Mozilla/5.0"
-DELAY_S = 0.15
-LAPSE_C_PER_KM = 6.5
-ERA5_YEARS = (2018, 2020)
-NOAA_MAX_KM = 150.0
-ECCC_MAX_KM = 250.0
+CHELSA_URL = ("https://os.unil.cloud.switch.ch/chelsa02/chelsa/global/"
+ "climatologies/tasmax/1981-2010/"
+ "CHELSA_tasmax_{month:02d}_1981-2010_V.2.1.tif")
+ETOPO_URL = ("https://www.ngdc.noaa.gov/mgg/global/relief/ETOPO2022/data/"
+ "60s/60s_surface_elev_gtif/"
+ "ETOPO_2022_v1_60s_N90W180_surface.tif")
-_LAST_AT = [0.0]
-_REMAINING = [None]
+USER_AGENT = "Mozilla/5.0"
+LAPSE_C_PER_KM = 6.5
+HEADER_BYTES = 65536
+SEARCH_RADIUS = 3 # cells to look for land when the nearest cell is sea
+
+_LOCK = threading.RLock()
@dataclass(frozen=True)
@@ -188,54 +126,268 @@ def haversine_km(lat1, lon1, lat2, lon2):
return 2 * radius * math.asin(math.sqrt(h))
-def _pace():
- """One request at a time, a short pause, and respect for the free
- API's per-minute allowance when it reports one."""
- if _REMAINING[0] is not None and _REMAINING[0] < 60:
- time.sleep(61)
- _REMAINING[0] = None
- wait = DELAY_S - (time.time() - _LAST_AT[0])
- if wait > 0:
- time.sleep(wait)
+# ---------------------------------------------------------------------------
+# Range reads, cached on disk.
-
-def _retry_after_s(exc):
- headers = getattr(exc, "headers", None) or getattr(exc, "hdrs", None) or {}
- try:
- return max(5.0, min(float(headers.get("Retry-After")), 1200.0))
- except (TypeError, ValueError):
- return 65.0
-
-
-def _get_bytes(url, opener, timeout=180):
- req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
- for attempt in range(20):
- _pace()
+def default_getter(url, start, end):
+ req = urllib.request.Request(url, headers={
+ "User-Agent": USER_AGENT, "Range": f"bytes={start}-{end}"})
+ last = None
+ for attempt in range(6):
try:
- with opener(req, timeout=timeout) as resp:
- raw = resp.read()
- headers = getattr(resp, "headers", None) or {}
- try:
- _REMAINING[0] = float(headers.get("X-RateLimit-Remaining"))
- except (TypeError, ValueError):
- pass
- _LAST_AT[0] = time.time()
- return raw
- except urllib.error.HTTPError as exc:
- _LAST_AT[0] = time.time()
- if exc.code == 429 and attempt < 19:
- # The hourly allowance refills as old requests age out.
- # Wait as long as the API asks, then try the same
- # request again; the point is fetched once either way.
- _REMAINING[0] = None
- time.sleep(_retry_after_s(exc) + 5)
- continue
- raise
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ return resp.read()
+ except (urllib.error.URLError, OSError) as exc:
+ last = exc
+ if isinstance(exc, urllib.error.HTTPError) and exc.code in (403, 404):
+ raise
+ time.sleep(2 * (attempt + 1))
+ raise last
-def _cache_path(cache, source, lat, lon, elev_m):
+class Source:
+ """One tiled GeoTIFF read by range requests."""
+
+ def __init__(self, url, cache=CACHE_DIR, getter=default_getter):
+ self.url = url
+ self.cache = os.path.join(cache, "tiles")
+ self.getter = getter
+ self._tiles = {}
+ self._ready = False
+
+ # -- cached ranges
+ def _range(self, start, end):
+ key = hashlib.sha256(f"{self.url}|{start}|{end}".encode()).hexdigest()[:40]
+ path = os.path.join(self.cache, key[:2], key + ".bin")
+ if os.path.exists(path):
+ with open(path, "rb") as f:
+ return f.read()
+ raw = self.getter(self.url, start, end)
+ if len(raw) != end - start + 1 and start != 0:
+ raise OSError(f"short read {len(raw)} of {end - start + 1} at {start}")
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path))
+ with os.fdopen(fd, "wb") as f:
+ f.write(raw)
+ os.replace(tmp, path)
+ return raw
+
+ # -- header
+ def _load(self):
+ with _LOCK:
+ if self._ready:
+ return
+ head = self._range(0, HEADER_BYTES - 1)
+ if head[:4] != b"II*\x00":
+ raise ValueError("not a little-endian classic TIFF: " + self.url)
+ off = struct.unpack("]*>([^<]+)<', meta)
+ self.scale = float(m.group(1)) if m else 1.0
+ m = re.search(r'name="OFFSET"[^>]*>([^<]+)<', meta)
+ self.offset = float(m.group(1)) if m else 0.0
+ nd = tags.get(42113)
+ self.nodata = float(nd) if nd not in (None, "") else None
+ self.tiles_across = (self.width + self.tw - 1) // self.tw
+ if self.compression not in (5, 8):
+ raise ValueError("unsupported compression %d" % self.compression)
+ self._ready = True
+
+ # -- tile decoding
+ def _decode(self, idx):
+ with _LOCK:
+ got = self._tiles.get(idx)
+ if got is not None:
+ return got
+ raw = self._range(self.offsets[idx], self.offsets[idx] + self.counts[idx] - 1)
+ data = lzw_decode(raw) if self.compression == 5 else zlib.decompress(raw)
+ tile = self._to_values(data)
+ with _LOCK:
+ if len(self._tiles) > 24:
+ self._tiles.clear()
+ self._tiles[idx] = tile
+ return tile
+
+ def _to_values(self, data):
+ w, h = self.tw, self.th
+ if self.sampleformat == 3 and self.bits == 32 and self.predictor == 3:
+ out = array.array("f")
+ for r in range(h):
+ row = bytearray(data[r * w * 4:(r + 1) * w * 4])
+ acc = 0
+ for i in range(len(row)):
+ acc = (acc + row[i]) & 255
+ row[i] = acc
+ be = bytearray(w * 4)
+ for k in range(4):
+ be[k::4] = row[k * w:(k + 1) * w]
+ out.extend(struct.unpack(">%df" % w, bytes(be)))
+ return out
+ if self.bits == 16 and self.sampleformat in (1, 2):
+ code = "H" if self.sampleformat == 1 else "h"
+ out = array.array(code)
+ out.frombytes(data[: w * h * 2])
+ if sys.byteorder != "little":
+ out.byteswap()
+ if self.predictor == 2:
+ for r in range(h):
+ acc = 0
+ base = r * w
+ for i in range(w):
+ acc = (acc + out[base + i]) & 0xFFFF
+ out[base + i] = acc
+ elif self.predictor != 1:
+ raise ValueError("unsupported predictor")
+ return out
+ raise ValueError("unsupported sample layout")
+
+ # -- pixels
+ def pixel(self, col, row):
+ """Raw value at an integer cell, or None for outside or nodata."""
+ self._load()
+ if row < 0 or row >= self.height:
+ return None
+ col %= self.width
+ idx = (row // self.th) * self.tiles_across + col // self.tw
+ tile = self._decode(idx)
+ v = tile[(row % self.th) * self.tw + (col % self.tw)]
+ if self.nodata is not None and v == self.nodata:
+ return None
+ return v
+
+ def value_nearest(self, lon, lat):
+ """Scaled value of the nearest cell that has data, searching a
+ few cells outward when the nearest is sea; None if none."""
+ self._load()
+ col = int(math.floor((lon - self.x0) / self.xres + 0.5))
+ row = int(math.floor((self.y0 - lat) / self.yres + 0.5))
+ for radius in range(SEARCH_RADIUS + 1):
+ best = None
+ for dr in range(-radius, radius + 1):
+ for dc in range(-radius, radius + 1):
+ if max(abs(dr), abs(dc)) != radius:
+ continue
+ v = self.pixel(col + dc, row + dr)
+ if v is None:
+ continue
+ d = dr * dr + dc * dc
+ if best is None or d < best[0]:
+ best = (d, v)
+ if best is not None:
+ return best[1] * self.scale + self.offset
+ return None
+
+ def value_bilinear(self, lon, lat):
+ self._load()
+ fx = (lon - self.x0) / self.xres
+ fy = (self.y0 - lat) / self.yres
+ c0, r0 = int(math.floor(fx)), int(math.floor(fy))
+ tx, ty = fx - c0, fy - r0
+ total = weight = 0.0
+ for dr, wy in ((0, 1 - ty), (1, ty)):
+ for dc, wx in ((0, 1 - tx), (1, tx)):
+ v = self.pixel(c0 + dc, r0 + dr)
+ if v is None:
+ continue
+ total += v * wx * wy
+ weight += wx * wy
+ if weight <= 0:
+ return None
+ return (total / weight) * self.scale + self.offset
+
+
+def lzw_decode(data):
+ """TIFF LZW (MSB first, early change)."""
+ out = []
+ base = [bytes([i]) for i in range(256)] + [b"", b""]
+ table = list(base)
+ bits = 9
+ buf = nb = pos = 0
+ n = len(data)
+ prev = None
+ while True:
+ while nb < bits:
+ if pos >= n:
+ return b"".join(out)
+ buf = (buf << 8) | data[pos]
+ pos += 1
+ nb += 8
+ code = (buf >> (nb - bits)) & ((1 << bits) - 1)
+ nb -= bits
+ buf &= (1 << nb) - 1
+ if code == 257:
+ break
+ if code == 256:
+ table = list(base)
+ bits = 9
+ prev = None
+ continue
+ if prev is None:
+ entry = table[code]
+ elif code < len(table):
+ entry = table[code]
+ table.append(prev + entry[:1])
+ else:
+ entry = prev + prev[:1]
+ table.append(entry)
+ out.append(entry)
+ prev = entry
+ ln = len(table)
+ bits = 12 if ln >= 2047 else 11 if ln >= 1023 else 10 if ln >= 511 else 9
+ return b"".join(out)
+
+
+# ---------------------------------------------------------------------------
+# Normals for a point.
+
+_SOURCES = {}
+
+
+def _sources(cache, getter):
+ key = (cache, id(getter))
+ with _LOCK:
+ if key not in _SOURCES:
+ _SOURCES[key] = (
+ [Source(CHELSA_URL.format(month=m), cache, getter) for m in range(1, 13)],
+ Source(ETOPO_URL, cache, getter))
+ return _SOURCES[key]
+
+
+def _cache_path(cache, lat, lon, elev_m):
elev_key = "cell" if elev_m is None else str(int(round(elev_m)))
- return os.path.join(cache, f"{source}_{lat:.3f}_{lon:.3f}_{elev_key}.json")
+ return os.path.join(cache, "points", f"chelsa_{lat:.3f}_{lon:.3f}_{elev_key}.json")
def _read_cache(path):
@@ -262,249 +414,42 @@ def _write_cache(path, normals):
doc = {"lat": normals.lat, "lon": normals.lon, "elev_m": normals.elev_m,
"tmax_c": list(normals.tmax_c),
"snow_cm": None if normals.snow_cm is None else list(normals.snow_cm)}
- with open(path, "w", encoding="utf-8") as f:
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path))
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(doc, f, sort_keys=True)
f.write("\n")
+ os.replace(tmp, path)
-def _rounded(lat, lon):
- return round(float(lat), 3), round(float(lon), 3)
-
-
-# ---------------------------------------------------------------------------
-# Open-Meteo (ERA5-Land), the chosen source.
-
-def _open_meteo_url(lat, lon, elev_m):
- params = {
- "latitude": lat, "longitude": lon,
- "start_date": f"{ERA5_YEARS[0]}-01-01", "end_date": f"{ERA5_YEARS[1]}-12-31",
- "daily": "temperature_2m_max,snow_depth_max",
- "timezone": "UTC", "models": "era5_land",
- }
- if elev_m is not None:
- params["elevation"] = int(round(elev_m))
- return ("https://archive-api.open-meteo.com/v1/archive?"
- + urllib.parse.urlencode(params))
-
-
-def parse_open_meteo(raw, lat, lon, elev_m):
- """Daily ERA5-Land values averaged by month, or None. Snow depths
- arrive in metres and leave in cm. A month with no temperature value
- at all is missing data, never zero; a point whose snow values are
- absent (open water) keeps its temperatures with snow_cm None."""
- try:
- doc = json.loads(raw.decode("utf-8"))
- except (ValueError, UnicodeDecodeError):
- return None
- daily = doc.get("daily") or {}
- days = daily.get("time") or []
- tmax = daily.get("temperature_2m_max") or []
- snow = daily.get("snow_depth_max") or []
- if not days or len(tmax) != len(days):
- return None
- by_month_t = [[] for _ in range(12)]
- by_month_s = [[] for _ in range(12)]
- for i, day in enumerate(days):
- try:
- month = int(day[5:7])
- except (TypeError, ValueError, IndexError):
- return None
- if tmax[i] is not None:
- by_month_t[month - 1].append(float(tmax[i]))
- if i < len(snow) and snow[i] is not None:
- by_month_s[month - 1].append(float(snow[i]))
- if any(not values for values in by_month_t):
- return None
- tmax_c = tuple(round(sum(v) / len(v), 1) for v in by_month_t)
- if all(by_month_s):
- snow_cm = tuple(round(sum(v) / len(v) * 100.0, 1) for v in by_month_s)
+def fetch_normals(lat, lon, elev_m, cache=CACHE_DIR, opener=None, getter=None):
+ """Normals at the point, at elev_m (the grid cell's own elevation
+ when None), or None when the grid has no land value there. Never
+ returns invented zeros. `getter(url, start, end)` replaces the
+ network for tests; `opener` is accepted and ignored."""
+ lat, lon = round(float(lat), 3), round(float(lon), 3)
+ path = _cache_path(cache, lat, lon, elev_m)
+ found, normals = _read_cache(path)
+ if found:
+ return normals
+ months, dem = _sources(cache, getter or default_getter)
+ cell_elev = dem.value_bilinear(lon, lat)
+ values = []
+ for src in months:
+ v = src.value_nearest(lon, lat)
+ if v is None:
+ values = None
+ break
+ values.append(v - 273.15)
+ if values is None or cell_elev is None:
+ normals = None
else:
- snow_cm = None
- elev = float(elev_m) if elev_m is not None else float(doc.get("elevation") or 0.0)
- return PointNormals(lat=lat, lon=lon, elev_m=elev, tmax_c=tmax_c, snow_cm=snow_cm)
+ use = cell_elev if elev_m is None else float(elev_m)
+ shift = LAPSE_C_PER_KM * (cell_elev - use) / 1000.0
+ normals = PointNormals(
+ lat=lat, lon=lon, elev_m=use,
+ tmax_c=tuple(round(v + shift, 1) for v in values), snow_cm=None)
+ _write_cache(path, normals)
+ return normals
-def fetch_open_meteo(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
- lat, lon = _rounded(lat, lon)
- # The years are in the cache name so a widened period later never
- # reads means computed over different years.
- path = _cache_path(cache, f"open-meteo-{ERA5_YEARS[0]}-{ERA5_YEARS[1]}",
- lat, lon, elev_m)
- hit, got = _read_cache(path)
- if hit:
- return got
- raw = _get_bytes(_open_meteo_url(lat, lon, elev_m), opener)
- got = parse_open_meteo(raw, lat, lon, elev_m)
- _write_cache(path, got)
- return got
-
-
-# ---------------------------------------------------------------------------
-# NOAA 1991-2020 monthly station normals (US only, temperature only).
-
-NOAA_STATIONS_URL = "https://www.ncei.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt"
-NOAA_NORMALS_URL = ("https://www.ncei.noaa.gov/data/normals-monthly/"
- "1991-2020/access/{sid}.csv")
-
-
-def _noaa_stations(cache, opener):
- path = os.path.join(cache, "noaa_ghcnd-stations.txt")
- if not os.path.exists(path):
- raw = _get_bytes(NOAA_STATIONS_URL, opener)
- os.makedirs(cache, exist_ok=True)
- with open(path, "wb") as f:
- f.write(raw)
- stations = []
- with open(path, encoding="utf-8", errors="replace") as f:
- for line in f:
- parts = line.split()
- if len(parts) < 4 or not parts[0].startswith("US"):
- continue
- try:
- stations.append((parts[0], float(parts[1]), float(parts[2]),
- float(parts[3])))
- except ValueError:
- continue
- return stations
-
-
-def parse_noaa_csv(raw, lat, lon, elev_m):
- """MLY-TMAX-NORMAL is in degrees F. Temperatures are lapse adjusted
- from the station elevation to the elevation asked for. The product
- has no snow depth, so snow_cm is None."""
- text = raw.decode("utf-8", errors="replace")
- rows = {}
- station_elev = None
- for row in csv.DictReader(io.StringIO(text)):
- try:
- month = int(row.get("month") or 0)
- value = float(row.get("MLY-TMAX-NORMAL") or "")
- station_elev = float(row.get("ELEVATION") or 0.0)
- except ValueError:
- continue
- if 1 <= month <= 12:
- rows[month] = value
- if len(rows) != 12 or station_elev is None:
- return None
- lapse = 0.0
- if elev_m is not None:
- lapse = LAPSE_C_PER_KM * (float(elev_m) - station_elev) / 1000.0
- tmax_c = tuple(round((rows[m] - 32.0) * 5.0 / 9.0 - lapse, 1)
- for m in range(1, 13))
- elev = float(elev_m) if elev_m is not None else station_elev
- return PointNormals(lat=lat, lon=lon, elev_m=elev, tmax_c=tmax_c, snow_cm=None)
-
-
-def fetch_noaa(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
- lat, lon = _rounded(lat, lon)
- path = _cache_path(cache, "noaa", lat, lon, elev_m)
- hit, got = _read_cache(path)
- if hit:
- return got
- near = sorted(
- ((haversine_km(lat, lon, slat, slon), sid)
- for sid, slat, slon, _selev in _noaa_stations(cache, opener)),
- )
- got = None
- tried = 0
- # Most GHCN stations have no normals file, so walk past the ones
- # that answer 404; the nearest normals station is rarely the
- # nearest station of any kind.
- for dist, sid in near:
- if dist > NOAA_MAX_KM or tried >= 30:
- break
- tried += 1
- csv_path = os.path.join(cache, f"noaa_{sid}.csv")
- if os.path.exists(csv_path):
- with open(csv_path, "rb") as f:
- raw = f.read()
- else:
- try:
- raw = _get_bytes(NOAA_NORMALS_URL.format(sid=sid), opener)
- except urllib.error.HTTPError:
- continue
- os.makedirs(cache, exist_ok=True)
- with open(csv_path, "wb") as f:
- f.write(raw)
- got = parse_noaa_csv(raw, lat, lon, elev_m)
- if got is not None:
- break
- _write_cache(path, got)
- return got
-
-
-# ---------------------------------------------------------------------------
-# MSC GeoMet climate normals (Canada only, 1981-2010 stations).
-
-ECCC_ELEMENT = "Mean daily max temperature deg C"
-ECCC_URL = "https://api.weather.gc.ca/collections/climate-normals/items"
-
-
-def _eccc_url(lat, lon):
- bbox = f"{lon - 1.5},{lat - 1.0},{lon + 1.5},{lat + 1.0}"
- params = {"bbox": bbox, "limit": 10000, "f": "json",
- "E_NORMAL_ELEMENT_NAME": ECCC_ELEMENT}
- return ECCC_URL + "?" + urllib.parse.urlencode(params)
-
-
-def parse_eccc(raw, lat, lon, elev_m):
- """The nearest station with all twelve months of mean daily maximum
- temperature. The features carry no station elevation and no snow
- depth, so neither can be given."""
- try:
- doc = json.loads(raw.decode("utf-8"))
- except (ValueError, UnicodeDecodeError):
- return None
- stations = {}
- for feat in doc.get("features") or []:
- props = feat.get("properties") or {}
- if props.get("E_NORMAL_ELEMENT_NAME") != ECCC_ELEMENT:
- continue
- try:
- month = int(props.get("MONTH") or 0)
- value = float(props.get("VALUE"))
- slon, slat = (feat.get("geometry") or {}).get("coordinates") or (None, None)
- slat, slon = float(slat), float(slon)
- except (TypeError, ValueError):
- continue
- if not 1 <= month <= 12:
- continue
- entry = stations.setdefault(props.get("STN_ID"), (slat, slon, {}))
- entry[2][month] = value
- best = None
- for slat, slon, months in stations.values():
- if len(months) != 12:
- continue
- dist = haversine_km(lat, lon, slat, slon)
- if best is None or dist < best[0]:
- best = (dist, months)
- if best is None or best[0] > ECCC_MAX_KM:
- return None
- tmax_c = tuple(round(best[1][m], 1) for m in range(1, 13))
- elev = float(elev_m) if elev_m is not None else 0.0
- return PointNormals(lat=lat, lon=lon, elev_m=elev, tmax_c=tmax_c, snow_cm=None)
-
-
-def fetch_eccc(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
- lat, lon = _rounded(lat, lon)
- path = _cache_path(cache, "eccc", lat, lon, elev_m)
- hit, got = _read_cache(path)
- if hit:
- return got
- raw = _get_bytes(_eccc_url(lat, lon), opener)
- got = parse_eccc(raw, lat, lon, elev_m)
- _write_cache(path, got)
- return got
-
-
-def fetch_normals(lat, lon, elev_m, cache=CACHE_DIR, opener=urllib.request.urlopen):
- """Normals from the chosen source (see SOURCE), or None when it has
- no data for the point. Never returns invented zeros."""
- return fetch_open_meteo(lat, lon, elev_m, cache=cache, opener=opener)
-
-
-CANDIDATES = {
- "open-meteo": fetch_open_meteo,
- "noaa": fetch_noaa,
- "eccc": fetch_eccc,
-}
+CANDIDATES = {"chelsa": fetch_normals}
diff --git a/tools/tests/fixtures/season/eccc_normals.geojson b/tools/tests/fixtures/season/eccc_normals.geojson
deleted file mode 100644
index 23aabef..0000000
--- a/tools/tests/fixtures/season/eccc_normals.geojson
+++ /dev/null
@@ -1 +0,0 @@
-{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 1, "VALUE": 6.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 2, "VALUE": 8.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 3, "VALUE": 11.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 4, "VALUE": 14.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 5, "VALUE": 18.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 6, "VALUE": 21.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 7, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 8, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 9, "VALUE": 20.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 10, "VALUE": 14.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 11, "VALUE": 9.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-123.1, 49.2]}, "properties": {"STN_ID": 1111, "STATION_NAME": "FIXTURE 1111", "MONTH": 12, "VALUE": 6.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 1, "VALUE": -2.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 2, "VALUE": 0.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 3, "VALUE": 5.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 4, "VALUE": 11.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 5, "VALUE": 17.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 6, "VALUE": 21.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 7, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 8, "VALUE": 24.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 9, "VALUE": 19.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 10, "VALUE": 12.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 11, "VALUE": 3.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}, {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-114.0, 51.0]}, "properties": {"STN_ID": 2222, "STATION_NAME": "FIXTURE 2222", "MONTH": 12, "VALUE": -2.0, "E_NORMAL_ELEMENT_NAME": "Mean daily max temperature deg C"}}], "numberReturned": 24}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/noaa_USW00000001.csv b/tools/tests/fixtures/season/noaa_USW00000001.csv
deleted file mode 100644
index 07bc636..0000000
--- a/tools/tests/fixtures/season/noaa_USW00000001.csv
+++ /dev/null
@@ -1,13 +0,0 @@
-"STATION","DATE","LATITUDE","LONGITUDE","ELEVATION","NAME","month","MLY-TMAX-NORMAL"
-"USW00000001","01","37.7","-119.5","1500.0","FIXTURE","01","50.0"
-"USW00000001","02","37.7","-119.5","1500.0","FIXTURE","02","54.0"
-"USW00000001","03","37.7","-119.5","1500.0","FIXTURE","03","59.0"
-"USW00000001","04","37.7","-119.5","1500.0","FIXTURE","04","64.0"
-"USW00000001","05","37.7","-119.5","1500.0","FIXTURE","05","72.0"
-"USW00000001","06","37.7","-119.5","1500.0","FIXTURE","06","82.0"
-"USW00000001","07","37.7","-119.5","1500.0","FIXTURE","07","90.0"
-"USW00000001","08","37.7","-119.5","1500.0","FIXTURE","08","89.0"
-"USW00000001","09","37.7","-119.5","1500.0","FIXTURE","09","82.0"
-"USW00000001","10","37.7","-119.5","1500.0","FIXTURE","10","71.0"
-"USW00000001","11","37.7","-119.5","1500.0","FIXTURE","11","58.0"
-"USW00000001","12","37.7","-119.5","1500.0","FIXTURE","12","50.0"
diff --git a/tools/tests/fixtures/season/noaa_USW00000002.csv b/tools/tests/fixtures/season/noaa_USW00000002.csv
deleted file mode 100644
index 3c79ce1..0000000
--- a/tools/tests/fixtures/season/noaa_USW00000002.csv
+++ /dev/null
@@ -1,13 +0,0 @@
-"STATION","DATE","LATITUDE","LONGITUDE","ELEVATION","NAME","month","MLY-TMAX-NORMAL"
-"USW00000002","01","32.2","-110.9","800.0","FIXTURE","01","66.0"
-"USW00000002","02","32.2","-110.9","800.0","FIXTURE","02","70.0"
-"USW00000002","03","32.2","-110.9","800.0","FIXTURE","03","77.0"
-"USW00000002","04","32.2","-110.9","800.0","FIXTURE","04","85.0"
-"USW00000002","05","32.2","-110.9","800.0","FIXTURE","05","94.0"
-"USW00000002","06","32.2","-110.9","800.0","FIXTURE","06","104.0"
-"USW00000002","07","32.2","-110.9","800.0","FIXTURE","07","103.0"
-"USW00000002","08","32.2","-110.9","800.0","FIXTURE","08","101.0"
-"USW00000002","09","32.2","-110.9","800.0","FIXTURE","09","97.0"
-"USW00000002","10","32.2","-110.9","800.0","FIXTURE","10","88.0"
-"USW00000002","11","32.2","-110.9","800.0","FIXTURE","11","75.0"
-"USW00000002","12","32.2","-110.9","800.0","FIXTURE","12","66.0"
diff --git a/tools/tests/fixtures/season/noaa_USW00000003.csv b/tools/tests/fixtures/season/noaa_USW00000003.csv
deleted file mode 100644
index 1a89a7e..0000000
--- a/tools/tests/fixtures/season/noaa_USW00000003.csv
+++ /dev/null
@@ -1,13 +0,0 @@
-"STATION","DATE","LATITUDE","LONGITUDE","ELEVATION","NAME","month","MLY-TMAX-NORMAL"
-"USW00000003","01","47.6","-122.3","10.0","FIXTURE","01","47.0"
-"USW00000003","02","47.6","-122.3","10.0","FIXTURE","02","50.0"
-"USW00000003","03","47.6","-122.3","10.0","FIXTURE","03","54.0"
-"USW00000003","04","47.6","-122.3","10.0","FIXTURE","04","59.0"
-"USW00000003","05","47.6","-122.3","10.0","FIXTURE","05","65.0"
-"USW00000003","06","47.6","-122.3","10.0","FIXTURE","06","70.0"
-"USW00000003","07","47.6","-122.3","10.0","FIXTURE","07","76.0"
-"USW00000003","08","47.6","-122.3","10.0","FIXTURE","08","77.0"
-"USW00000003","09","47.6","-122.3","10.0","FIXTURE","09","72.0"
-"USW00000003","10","47.6","-122.3","10.0","FIXTURE","10","62.0"
-"USW00000003","11","47.6","-122.3","10.0","FIXTURE","11","52.0"
-"USW00000003","12","47.6","-122.3","10.0","FIXTURE","12","47.0"
diff --git a/tools/tests/fixtures/season/noaa_stations.txt b/tools/tests/fixtures/season/noaa_stations.txt
deleted file mode 100644
index 7edfcdb..0000000
--- a/tools/tests/fixtures/season/noaa_stations.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-USW00000001 37.7000 -119.5000 1500.0 CA FIXTURE SIERRA
-USW00000002 32.2000 -110.9000 800.0 AZ FIXTURE DESERT
-USW00000003 47.6000 -122.3000 10.0 WA FIXTURE COAST
diff --git a/tools/tests/fixtures/season/open_meteo_alpine.json b/tools/tests/fixtures/season/open_meteo_alpine.json
deleted file mode 100644
index cf54b50..0000000
--- a/tools/tests/fixtures/season/open_meteo_alpine.json
+++ /dev/null
@@ -1 +0,0 @@
-{"latitude": 37.7, "longitude": -119.5, "elevation": 3400.0, "daily_units": {"time": "iso8601", "temperature_2m_max": "\u00b0C", "snow_depth_max": "m"}, "daily": {"time": ["2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08", "2015-01-09", "2015-01-10", "2015-01-11", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15", "2015-01-16", "2015-01-17", "2015-01-18", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22", "2015-01-23", "2015-01-24", "2015-01-25", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29", "2015-01-30", "2015-01-31", "2015-02-01", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05", "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20", "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26", "2015-02-27", "2015-02-28", "2015-03-01", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05", "2015-03-06", "2015-03-07", "2015-03-08", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20", "2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04", "2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09", "2015-04-10", "2015-04-11", "2015-04-12", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16", "2015-04-17", "2015-04-18", "2015-04-19", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23", "2015-04-24", "2015-04-25", "2015-04-26", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30", "2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09", "2015-05-10", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14", "2015-05-15", "2015-05-16", "2015-05-17", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21", "2015-05-22", "2015-05-23", "2015-05-24", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28", "2015-05-29", "2015-05-30", "2015-05-31", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04", "2015-06-05", "2015-06-06", "2015-06-07", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11", "2015-06-12", "2015-06-13", "2015-06-14", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18", "2015-06-19", "2015-06-20", "2015-06-21", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25", "2015-06-26", "2015-06-27", "2015-06-28", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02", "2015-07-03", "2015-07-04", "2015-07-05", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09", "2015-07-10", "2015-07-11", "2015-07-12", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16", "2015-07-17", "2015-07-18", "2015-07-19", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23", "2015-07-24", "2015-07-25", "2015-07-26", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01", "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06", "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20", "2015-08-21", "2015-08-22", "2015-08-23", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03", "2015-09-04", "2015-09-05", "2015-09-06", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10", "2015-09-11", "2015-09-12", "2015-09-13", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17", "2015-09-18", "2015-09-19", "2015-09-20", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24", "2015-09-25", "2015-09-26", "2015-09-27", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08", "2015-10-09", "2015-10-10", "2015-10-11", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15", "2015-10-16", "2015-10-17", "2015-10-18", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22", "2015-10-23", "2015-10-24", "2015-10-25", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29", "2015-10-30", "2015-10-31", "2015-11-01", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05", "2015-11-06", "2015-11-07", "2015-11-08", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12", "2015-11-13", "2015-11-14", "2015-11-15", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28", "2015-11-29", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03", "2015-12-04", "2015-12-05", "2015-12-06", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10", "2015-12-11", "2015-12-12", "2015-12-13", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17", "2015-12-18", "2015-12-19", "2015-12-20", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24", "2015-12-25", "2015-12-26", "2015-12-27", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31"], "temperature_2m_max": [-2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 16.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0], "snow_depth_max": [1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.2, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.6, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 1.4, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]}}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/open_meteo_coast.json b/tools/tests/fixtures/season/open_meteo_coast.json
deleted file mode 100644
index 443e60b..0000000
--- a/tools/tests/fixtures/season/open_meteo_coast.json
+++ /dev/null
@@ -1 +0,0 @@
-{"latitude": 37.7, "longitude": -119.5, "elevation": 20.0, "daily_units": {"time": "iso8601", "temperature_2m_max": "\u00b0C", "snow_depth_max": "m"}, "daily": {"time": ["2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08", "2015-01-09", "2015-01-10", "2015-01-11", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15", "2015-01-16", "2015-01-17", "2015-01-18", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22", "2015-01-23", "2015-01-24", "2015-01-25", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29", "2015-01-30", "2015-01-31", "2015-02-01", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05", "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20", "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26", "2015-02-27", "2015-02-28", "2015-03-01", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05", "2015-03-06", "2015-03-07", "2015-03-08", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20", "2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04", "2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09", "2015-04-10", "2015-04-11", "2015-04-12", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16", "2015-04-17", "2015-04-18", "2015-04-19", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23", "2015-04-24", "2015-04-25", "2015-04-26", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30", "2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09", "2015-05-10", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14", "2015-05-15", "2015-05-16", "2015-05-17", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21", "2015-05-22", "2015-05-23", "2015-05-24", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28", "2015-05-29", "2015-05-30", "2015-05-31", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04", "2015-06-05", "2015-06-06", "2015-06-07", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11", "2015-06-12", "2015-06-13", "2015-06-14", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18", "2015-06-19", "2015-06-20", "2015-06-21", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25", "2015-06-26", "2015-06-27", "2015-06-28", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02", "2015-07-03", "2015-07-04", "2015-07-05", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09", "2015-07-10", "2015-07-11", "2015-07-12", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16", "2015-07-17", "2015-07-18", "2015-07-19", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23", "2015-07-24", "2015-07-25", "2015-07-26", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01", "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06", "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20", "2015-08-21", "2015-08-22", "2015-08-23", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03", "2015-09-04", "2015-09-05", "2015-09-06", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10", "2015-09-11", "2015-09-12", "2015-09-13", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17", "2015-09-18", "2015-09-19", "2015-09-20", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24", "2015-09-25", "2015-09-26", "2015-09-27", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08", "2015-10-09", "2015-10-10", "2015-10-11", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15", "2015-10-16", "2015-10-17", "2015-10-18", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22", "2015-10-23", "2015-10-24", "2015-10-25", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29", "2015-10-30", "2015-10-31", "2015-11-01", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05", "2015-11-06", "2015-11-07", "2015-11-08", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12", "2015-11-13", "2015-11-14", "2015-11-15", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28", "2015-11-29", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03", "2015-12-04", "2015-12-05", "2015-12-06", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10", "2015-12-11", "2015-12-12", "2015-12-13", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17", "2015-12-18", "2015-12-19", "2015-12-20", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24", "2015-12-25", "2015-12-26", "2015-12-27", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31"], "temperature_2m_max": [9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 14.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 20.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 21.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0], "snow_depth_max": [0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]}}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/open_meteo_desert.json b/tools/tests/fixtures/season/open_meteo_desert.json
deleted file mode 100644
index 14d6e8c..0000000
--- a/tools/tests/fixtures/season/open_meteo_desert.json
+++ /dev/null
@@ -1 +0,0 @@
-{"latitude": 37.7, "longitude": -119.5, "elevation": 400.0, "daily_units": {"time": "iso8601", "temperature_2m_max": "\u00b0C", "snow_depth_max": "m"}, "daily": {"time": ["2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05", "2015-01-06", "2015-01-07", "2015-01-08", "2015-01-09", "2015-01-10", "2015-01-11", "2015-01-12", "2015-01-13", "2015-01-14", "2015-01-15", "2015-01-16", "2015-01-17", "2015-01-18", "2015-01-19", "2015-01-20", "2015-01-21", "2015-01-22", "2015-01-23", "2015-01-24", "2015-01-25", "2015-01-26", "2015-01-27", "2015-01-28", "2015-01-29", "2015-01-30", "2015-01-31", "2015-02-01", "2015-02-02", "2015-02-03", "2015-02-04", "2015-02-05", "2015-02-06", "2015-02-07", "2015-02-08", "2015-02-09", "2015-02-10", "2015-02-11", "2015-02-12", "2015-02-13", "2015-02-14", "2015-02-15", "2015-02-16", "2015-02-17", "2015-02-18", "2015-02-19", "2015-02-20", "2015-02-21", "2015-02-22", "2015-02-23", "2015-02-24", "2015-02-25", "2015-02-26", "2015-02-27", "2015-02-28", "2015-03-01", "2015-03-02", "2015-03-03", "2015-03-04", "2015-03-05", "2015-03-06", "2015-03-07", "2015-03-08", "2015-03-09", "2015-03-10", "2015-03-11", "2015-03-12", "2015-03-13", "2015-03-14", "2015-03-15", "2015-03-16", "2015-03-17", "2015-03-18", "2015-03-19", "2015-03-20", "2015-03-21", "2015-03-22", "2015-03-23", "2015-03-24", "2015-03-25", "2015-03-26", "2015-03-27", "2015-03-28", "2015-03-29", "2015-03-30", "2015-03-31", "2015-04-01", "2015-04-02", "2015-04-03", "2015-04-04", "2015-04-05", "2015-04-06", "2015-04-07", "2015-04-08", "2015-04-09", "2015-04-10", "2015-04-11", "2015-04-12", "2015-04-13", "2015-04-14", "2015-04-15", "2015-04-16", "2015-04-17", "2015-04-18", "2015-04-19", "2015-04-20", "2015-04-21", "2015-04-22", "2015-04-23", "2015-04-24", "2015-04-25", "2015-04-26", "2015-04-27", "2015-04-28", "2015-04-29", "2015-04-30", "2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09", "2015-05-10", "2015-05-11", "2015-05-12", "2015-05-13", "2015-05-14", "2015-05-15", "2015-05-16", "2015-05-17", "2015-05-18", "2015-05-19", "2015-05-20", "2015-05-21", "2015-05-22", "2015-05-23", "2015-05-24", "2015-05-25", "2015-05-26", "2015-05-27", "2015-05-28", "2015-05-29", "2015-05-30", "2015-05-31", "2015-06-01", "2015-06-02", "2015-06-03", "2015-06-04", "2015-06-05", "2015-06-06", "2015-06-07", "2015-06-08", "2015-06-09", "2015-06-10", "2015-06-11", "2015-06-12", "2015-06-13", "2015-06-14", "2015-06-15", "2015-06-16", "2015-06-17", "2015-06-18", "2015-06-19", "2015-06-20", "2015-06-21", "2015-06-22", "2015-06-23", "2015-06-24", "2015-06-25", "2015-06-26", "2015-06-27", "2015-06-28", "2015-06-29", "2015-06-30", "2015-07-01", "2015-07-02", "2015-07-03", "2015-07-04", "2015-07-05", "2015-07-06", "2015-07-07", "2015-07-08", "2015-07-09", "2015-07-10", "2015-07-11", "2015-07-12", "2015-07-13", "2015-07-14", "2015-07-15", "2015-07-16", "2015-07-17", "2015-07-18", "2015-07-19", "2015-07-20", "2015-07-21", "2015-07-22", "2015-07-23", "2015-07-24", "2015-07-25", "2015-07-26", "2015-07-27", "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01", "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06", "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11", "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16", "2015-08-17", "2015-08-18", "2015-08-19", "2015-08-20", "2015-08-21", "2015-08-22", "2015-08-23", "2015-08-24", "2015-08-25", "2015-08-26", "2015-08-27", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", "2015-09-01", "2015-09-02", "2015-09-03", "2015-09-04", "2015-09-05", "2015-09-06", "2015-09-07", "2015-09-08", "2015-09-09", "2015-09-10", "2015-09-11", "2015-09-12", "2015-09-13", "2015-09-14", "2015-09-15", "2015-09-16", "2015-09-17", "2015-09-18", "2015-09-19", "2015-09-20", "2015-09-21", "2015-09-22", "2015-09-23", "2015-09-24", "2015-09-25", "2015-09-26", "2015-09-27", "2015-09-28", "2015-09-29", "2015-09-30", "2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07", "2015-10-08", "2015-10-09", "2015-10-10", "2015-10-11", "2015-10-12", "2015-10-13", "2015-10-14", "2015-10-15", "2015-10-16", "2015-10-17", "2015-10-18", "2015-10-19", "2015-10-20", "2015-10-21", "2015-10-22", "2015-10-23", "2015-10-24", "2015-10-25", "2015-10-26", "2015-10-27", "2015-10-28", "2015-10-29", "2015-10-30", "2015-10-31", "2015-11-01", "2015-11-02", "2015-11-03", "2015-11-04", "2015-11-05", "2015-11-06", "2015-11-07", "2015-11-08", "2015-11-09", "2015-11-10", "2015-11-11", "2015-11-12", "2015-11-13", "2015-11-14", "2015-11-15", "2015-11-16", "2015-11-17", "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24", "2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28", "2015-11-29", "2015-11-30", "2015-12-01", "2015-12-02", "2015-12-03", "2015-12-04", "2015-12-05", "2015-12-06", "2015-12-07", "2015-12-08", "2015-12-09", "2015-12-10", "2015-12-11", "2015-12-12", "2015-12-13", "2015-12-14", "2015-12-15", "2015-12-16", "2015-12-17", "2015-12-18", "2015-12-19", "2015-12-20", "2015-12-21", "2015-12-22", "2015-12-23", "2015-12-24", "2015-12-25", "2015-12-26", "2015-12-27", "2015-12-28", "2015-12-29", "2015-12-30", "2015-12-31"], "temperature_2m_max": [19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 22.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 26.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 31.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 36.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 44.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 43.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 39.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 32.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0, 19.0], "snow_depth_max": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}}
\ No newline at end of file
diff --git a/tools/tests/fixtures/season/open_meteo_nodata.json b/tools/tests/fixtures/season/open_meteo_nodata.json
deleted file mode 100644
index a6e84c4..0000000
--- a/tools/tests/fixtures/season/open_meteo_nodata.json
+++ /dev/null
@@ -1 +0,0 @@
-{"error": true, "reason": "No data"}
\ No newline at end of file
diff --git a/tools/tests/test_season_climate.py b/tools/tests/test_season_climate.py
index 7d4d4bc..71e2705 100644
--- a/tools/tests/test_season_climate.py
+++ b/tools/tests/test_season_climate.py
@@ -1,14 +1,17 @@
-"""Tests for tools/season_climate.py. All offline: an injected opener
-serves the canned responses in fixtures/season/.
+"""Tests for tools/season_climate.py. All offline: an injected range
+getter serves small synthetic GeoTIFFs laid out like CHELSA's (LZW with
+a horizontal predictor, 16 bit) and ETOPO's (deflate with the floating
+point predictor).
Run from the repository root:
python3 -m unittest discover tools/tests
"""
-import io
import os
+import struct
import sys
import tempfile
import unittest
+import zlib
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -16,147 +19,230 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import season_climate as C # noqa: E402
import validate as V # noqa: E402
-FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "season")
+W = H = 8
+TW = TH = 4
+X0, Y0, RES = -120.0, 40.0, 0.5
-def fixture_bytes(name):
- with open(os.path.join(FIX, name), "rb") as f:
- return f.read()
+def lzw_encode(data):
+ """A plain TIFF LZW encoder for short inputs (9 bit codes only)."""
+ table = {bytes([i]): i for i in range(256)}
+ nxt = 258
+ codes = [256]
+ cur = b""
+ for byte in data:
+ nb = cur + bytes([byte])
+ if nb in table:
+ cur = nb
+ else:
+ codes.append(table[cur])
+ table[nb] = nxt
+ nxt += 1
+ cur = bytes([byte])
+ if cur:
+ codes.append(table[cur])
+ codes.append(257)
+ assert nxt < 500
+ bits = "".join(format(c, "09b") for c in codes)
+ bits += "0" * (-len(bits) % 8)
+ return bytes(int(bits[i:i + 8], 2) for i in range(0, len(bits), 8))
-class FakeResponse(io.BytesIO):
- headers = {}
+def build_tiff(tiles, compression, predictor, bits, sampleformat, meta="", nodata=None):
+ """Classic little-endian TIFF, W x H in TW x TH tiles."""
+ entries = []
+ extra = bytearray()
+ base = 8 + 2 + 20 * 12 + 4 # room for up to 20 entries
+
+ def short(tag, v):
+ entries.append((tag, 3, 1, struct.pack("f", v) for v in row)
+ planar = bytes(be[j * 4 + k] for k in range(4) for j in range(len(row)))
+ diff = bytearray(len(planar))
+ prev = 0
+ for i, b in enumerate(planar):
+ diff[i] = (b - prev) & 255
+ prev = b
+ raw += bytes(diff)
+ return zlib.compress(raw)
+
+
+def month_file(month, nodata_at=None):
+ """Kelvin times ten, one value per cell: 280 K plus the month plus
+ the column, so every cell and month is distinguishable."""
+ vals = [int((280.0 + month + (i % W) * 0.1) * 10) for i in range(W * H)]
+ if nodata_at is not None:
+ vals[nodata_at] = 65535
+ meta = ('0'
+ '0.1')
+ return build_tiff(tiles_of(vals, encode_u16), 5, 2, 16, 1, meta,
+ nodata=65535 if nodata_at is not None else None)
+
+
+def dem_file(elev=1000.0):
+ vals = [elev] * (W * H)
+ return build_tiff(tiles_of(vals, encode_float), 8, 3, 32, 3, nodata=-99999)
+
+
+class Getter:
+ def __init__(self, nodata_at=None, elev=1000.0):
self.calls = []
- self.open_meteo = open_meteo
+ self.files = {}
+ for m in range(1, 13):
+ self.files[C.CHELSA_URL.format(month=m)] = month_file(
+ m, nodata_at if m == 1 else nodata_at)
+ self.files[C.ETOPO_URL] = dem_file(elev)
- def __call__(self, req, timeout=None):
- url = req.full_url if hasattr(req, "full_url") else str(req)
- self.calls.append(url)
- if "archive-api.open-meteo.com" in url:
- return FakeResponse(fixture_bytes(self.open_meteo))
- if "ghcnd-stations.txt" in url:
- return FakeResponse(fixture_bytes("noaa_stations.txt"))
- if "normals-monthly" in url:
- for sid in ("USW00000001", "USW00000002", "USW00000003"):
- if sid in url:
- return FakeResponse(fixture_bytes(f"noaa_{sid}.csv"))
- raise AssertionError(url)
- if "api.weather.gc.ca" in url:
- return FakeResponse(fixture_bytes("eccc_normals.geojson"))
- raise AssertionError(url)
+ def __call__(self, url, start, end):
+ self.calls.append((url, start, end))
+ return self.files[url][start:end + 1]
-class OpenMeteoTest(unittest.TestCase):
- def setUp(self):
- C.DELAY_S = 0
+class ReaderTest(unittest.TestCase):
+ def test_lzw_round_trips_repeats(self):
+ data = b"ABABABABCCCCCCDDDDABAB" * 5
+ self.assertEqual(C.lzw_decode(lzw_encode(data)), data)
- def test_a_fixture_response_becomes_point_normals(self):
+ def test_a_chelsa_style_tile_is_read_with_its_predictor_and_scale(self):
with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache, opener=FakeOpener())
- self.assertIsNotNone(got)
- self.assertEqual(len(got.tmax_c), 12)
- self.assertEqual(len(got.snow_cm), 12)
- self.assertEqual(got.tmax_c[0], -2.0) # January, degrees C
- self.assertEqual(got.tmax_c[6], 21.0) # July
- self.assertEqual(got.snow_cm[0], 120.0) # 1.2 metres of snow, in cm
- self.assertEqual(got.snow_cm[7], 0.0)
+ src = C.Source(C.CHELSA_URL.format(month=3), cache, Getter())
+ raw = src.pixel(2, 2)
+ self.assertEqual(raw, int((283.0 + 0.2) * 10))
+ self.assertAlmostEqual(src.value_nearest(-119.0, 39.0), 283.2, places=1)
- def test_values_are_rounded_to_a_tenth(self):
+ def test_an_etopo_style_float_tile_is_read(self):
with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_normals(37.7, -119.5, None, cache=cache, opener=FakeOpener())
- for value in list(got.tmax_c) + list(got.snow_cm):
- self.assertEqual(value, round(value, 1))
+ src = C.Source(C.ETOPO_URL, cache, Getter(elev=1234.5))
+ self.assertAlmostEqual(src.value_bilinear(-119.1, 39.2), 1234.5, places=1)
- def test_cell_elevation_is_used_when_none_is_asked_for(self):
+
+class NormalsTest(unittest.TestCase):
+ def test_a_point_becomes_twelve_celsius_values_at_the_cell_elevation(self):
with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_normals(37.7, -119.5, None, cache=cache, opener=FakeOpener())
- self.assertEqual(got.elev_m, 3400.0)
+ n = C.fetch_normals(39.0, -119.0, None, cache=cache, getter=Getter())
+ self.assertEqual(len(n.tmax_c), 12)
+ self.assertEqual(n.elev_m, 1000.0)
+ self.assertIsNone(n.snow_cm)
+ self.assertAlmostEqual(n.tmax_c[0], 281.0 + 0.2 - 273.15, places=1)
+
+ def test_values_are_corrected_by_the_lapse_rate_to_the_asked_elevation(self):
+ with tempfile.TemporaryDirectory() as cache:
+ g = Getter()
+ cell = C.fetch_normals(39.0, -119.0, None, cache=cache, getter=g)
+ up = C.fetch_normals(39.0, -119.0, 2000, cache=cache, getter=g)
+ self.assertEqual(up.elev_m, 2000.0)
+ self.assertAlmostEqual(cell.tmax_c[6] - up.tmax_c[6], 6.5, places=1)
def test_a_second_call_reads_the_cache_not_the_network(self):
- opener = FakeOpener()
with tempfile.TemporaryDirectory() as cache:
- first = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache, opener=opener)
- second = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache, opener=opener)
- self.assertEqual(first, second)
- self.assertEqual(len(opener.calls), 1)
+ g = Getter()
+ C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=g)
+ first = len(g.calls)
+ self.assertGreater(first, 0)
+ C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=g)
+ self.assertEqual(len(g.calls), first)
+
+ def test_a_new_getter_still_reads_cached_tiles(self):
+ with tempfile.TemporaryDirectory() as cache:
+ C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=Getter())
+ g2 = Getter()
+ C.fetch_normals(39.2, -119.0, 1500, cache=cache, getter=g2)
+ # a different point in the same tiles: no tile range is asked again
+ tile_asks = [c for c in g2.calls if c[1] != 0]
+ self.assertEqual(tile_asks, [])
def test_a_point_with_no_data_returns_none_not_zeros(self):
with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_normals(0.0, 0.0, None, cache=cache,
- opener=FakeOpener("open_meteo_nodata.json"))
- self.assertIsNone(got)
-
- def test_a_429_is_retried_after_a_pause(self):
- import urllib.error
- from unittest import mock
- calls = []
-
- def flaky(req, timeout=None):
- calls.append(req.full_url)
- if len(calls) == 1:
- raise urllib.error.HTTPError(
- req.full_url, 429, "Too Many Requests",
- {"Retry-After": "0"}, None)
- return FakeResponse(fixture_bytes("open_meteo_alpine.json"))
+ # every cell of every month file is nodata
+ g = Getter()
+ for m in range(1, 13):
+ url = C.CHELSA_URL.format(month=m)
+ vals = [65535] * (W * H)
+ meta = ('0.1'
+ '')
+ g.files[url] = build_tiff(tiles_of(vals, encode_u16), 5, 2, 16, 1,
+ meta, nodata=65535)
+ self.assertIsNone(C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=g))
+ def test_a_sea_cell_borrows_the_nearest_land_cell(self):
with tempfile.TemporaryDirectory() as cache:
- with mock.patch.object(C.time, "sleep", lambda s: None):
- got = C.fetch_normals(37.7, -119.5, 3400.0, cache=cache,
- opener=flaky)
- self.assertIsNotNone(got)
- self.assertEqual(len(calls), 2)
+ # cell (2, 2) is sea in every month; (3, 2) is land
+ g = Getter(nodata_at=2 * W + 2)
+ n = C.fetch_normals(39.0, -119.0, None, cache=cache, getter=g)
+ self.assertIsNotNone(n)
- def test_the_desert_and_coast_fixtures_parse(self):
+ def test_a_point_outside_the_grid_has_no_data(self):
with tempfile.TemporaryDirectory() as cache:
- desert = C.fetch_normals(32.2, -110.9, 800.0, cache=cache,
- opener=FakeOpener("open_meteo_desert.json"))
- coast = C.fetch_normals(47.6, -122.3, 10.0, cache=cache,
- opener=FakeOpener("open_meteo_coast.json"))
- self.assertEqual(desert.tmax_c[6], 44.0)
- self.assertTrue(all(v == 0.0 for v in desert.snow_cm))
- self.assertEqual(coast.tmax_c[0], 9.0)
-
-
-class NoaaTest(unittest.TestCase):
- def setUp(self):
- C.DELAY_S = 0
-
- def test_noaa_fixture_becomes_point_normals(self):
- with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_noaa(37.71, -119.51, 1500.0, cache=cache, opener=FakeOpener())
- self.assertIsNotNone(got)
- self.assertEqual(len(got.tmax_c), 12)
- self.assertEqual(got.tmax_c[0], 10.0) # 50 F in C, no lapse change
- self.assertIsNone(got.snow_cm) # the normals carry no snow depth
-
- def test_noaa_lapse_adjusts_to_the_point_elevation(self):
- with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_noaa(37.71, -119.51, 2500.0, cache=cache, opener=FakeOpener())
- self.assertEqual(got.tmax_c[0], 3.5) # 10 C less 6.5 C for 1000 m
-
- def test_noaa_returns_none_far_from_any_station(self):
- with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_noaa(66.5, -65.0, None, cache=cache, opener=FakeOpener())
- self.assertIsNone(got)
-
-
-class EcccTest(unittest.TestCase):
- def setUp(self):
- C.DELAY_S = 0
-
- def test_eccc_fixture_becomes_point_normals(self):
- with tempfile.TemporaryDirectory() as cache:
- got = C.fetch_eccc(49.25, -123.05, None, cache=cache, opener=FakeOpener())
- self.assertIsNotNone(got)
- self.assertEqual(got.tmax_c[0], 6.0) # the nearer of the two stations
- self.assertEqual(got.tmax_c[6], 24.0)
- self.assertIsNone(got.snow_cm)
+ self.assertIsNone(C.fetch_normals(80.0, -119.0, 100, cache=cache, getter=Getter()))
class SourceTest(unittest.TestCase):
@@ -167,7 +253,8 @@ class SourceTest(unittest.TestCase):
for key in ("name", "publisher", "url", "licence", "period"):
self.assertIn(key, C.SOURCE)
self.assertTrue(str(C.SOURCE[key]).strip())
- self.assertIn("CC BY 4.0", C.SOURCE["licence"])
+ self.assertIn("CC0", C.SOURCE["licence"])
+ self.assertEqual(C.SOURCE["period"], "1981-2010")
if __name__ == "__main__":
From b2cdfc37cf13d907a3eb0042ad5274e4d0bbd6d6 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 11:34:19 -0700
Subject: [PATCH 07/30] Fit the season rule against the sourced seasons, record
the figure, and add the estimate review list, proposals and check
Co-Authored-By: Claude Sonnet 5.5
---
tools/estimate_season.py | 732 ++++++++++++++++++++++++++--
tools/season_fit.json | 225 +++++++++
tools/tests/test_estimate_season.py | 311 ++++++++++++
tools/tests/test_season_fit.py | 60 +++
4 files changed, 1299 insertions(+), 29 deletions(-)
create mode 100644 tools/season_fit.json
create mode 100644 tools/tests/test_season_fit.py
diff --git a/tools/estimate_season.py b/tools/estimate_season.py
index d1bdc2c..006dca7 100644
--- a/tools/estimate_season.py
+++ b/tools/estimate_season.py
@@ -19,13 +19,20 @@ trails a winter one that wraps the year end, and mild trails all
twelve months. It cannot know that some trails are walked in snow by
choice; the fit against sourced seasons says how often that matters.
-Commands are added by the plan's later tasks (fit, propose, check).
+Commands: fit (tune and record the thresholds), trial (compare the
+climate candidates), propose (the review list), proposals (stage
+accepted estimates for the refresh pipeline) and check (rerun
+every estimate and the fit).
"""
import sys
sys.dont_write_bytecode = True
+import argparse
import bisect
+import csv
+import datetime
+import hashlib
import json
import math
import os
@@ -36,7 +43,12 @@ from dataclasses import dataclass, replace
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
-import season_climate # noqa: E402 (types and distance only; no network)
+import refresh # noqa: E402
+import season # noqa: E402
+import season_batches # noqa: E402
+import season_climate # noqa: E402
+
+ROOT = os.path.dirname(HERE)
RULE_VERSION = 1
@@ -96,46 +108,59 @@ def _median_at(points, month, attr):
return round(statistics.median(values), 1)
-def _month_passes(high, low, month, params):
- high_tmax = _median_at(high, month, "tmax_c")
- if high_tmax is None or high_tmax < params.cold_c_min:
- return False
- snow = _median_at(high, month, "snow_cm")
- if snow is not None and snow > params.snow_cm_max:
- return False
- low_tmax = _median_at(low, month, "tmax_c")
- if low_tmax is None or low_tmax > params.heat_c_max:
- return False
- return True
+def _medians(points):
+ """Per-month medians the rule compares: (high-ground mean daily
+ high, high-ground snow depth, low-ground mean daily high), each a
+ tuple of twelve rounded to a tenth, snow entries None where no
+ high-ground point has a snow measure. None when a point lacks
+ data. Precomputing these once per trail is what makes the grid
+ search cheap."""
+ got = _usable(points)
+ if got is None:
+ return None
+ high, low = _high_low(got)
+ return (
+ tuple(_median_at(high, m, "tmax_c") for m in range(12)),
+ tuple(_median_at(high, m, "snow_cm") for m in range(12)),
+ tuple(_median_at(low, m, "tmax_c") for m in range(12)),
+ )
+
+
+def _months_from(medians, params):
+ high_tmax, high_snow, low_tmax = medians
+ out = []
+ for m in range(12):
+ if high_tmax[m] is None or high_tmax[m] < params.cold_c_min:
+ continue
+ if high_snow[m] is not None and high_snow[m] > params.snow_cm_max:
+ continue
+ if low_tmax[m] is None or low_tmax[m] > params.heat_c_max:
+ continue
+ out.append(m + 1)
+ return out
def months_in_season(points, params):
"""Sorted month numbers in season, or None. None means either some
point has no data or no month qualifies; why_not says which. An
empty list is never returned."""
- got = _usable(points)
- if got is None:
+ medians = _medians(points)
+ if medians is None:
return None
- high, low = _high_low(got)
- months = [m + 1 for m in range(12) if _month_passes(high, low, m, params)]
- return months or None
+ return _months_from(medians, params) or None
def why_not(points, params):
"""Why months_in_season returned None, or "" when it did not."""
- got = _usable(points)
- if got is None:
+ medians = _medians(points)
+ if medians is None:
return "no data for one of the sample points"
- if months_in_season(got, params) is not None:
+ if _months_from(medians, params):
return ""
- high, low = _high_low(got)
- cold_ok = sum(1 for m in range(12)
- if (_median_at(high, m, "tmax_c") or -999) >= params.cold_c_min)
- snow_ok = sum(1 for m in range(12)
- if (_median_at(high, m, "snow_cm") is None
- or _median_at(high, m, "snow_cm") <= params.snow_cm_max))
- heat_ok = sum(1 for m in range(12)
- if (_median_at(low, m, "tmax_c") or 999) <= params.heat_c_max)
+ high_tmax, high_snow, low_tmax = medians
+ cold_ok = sum(1 for v in high_tmax if v is not None and v >= params.cold_c_min)
+ snow_ok = sum(1 for v in high_snow if v is None or v <= params.snow_cm_max)
+ heat_ok = sum(1 for v in low_tmax if v is not None and v <= params.heat_c_max)
return (f"no month passes the cold, snow and heat tests together "
f"(cold passes in {cold_ok} months, snow in {snow_ok}, "
f"heat in {heat_ok})")
@@ -394,3 +419,652 @@ def sample_points(root, rec):
elev_m=None if elev is None else float(elev),
km=None)], "place"
return [], "place"
+
+
+# ---------------------------------------------------------------------------
+# Fitting the three thresholds against the sourced seasons. The rule is
+# tuned on the sourced trails whose id hashes even and reported on the
+# ones that hash odd (held out), then the shipped numbers are refit on
+# all of them. Estimates may ship only over the owner's bar, held here
+# in one place.
+
+BAR = {"within1_min": 0.75, "coverage_min": 0.90}
+
+DEFAULT_GRID = {
+ "snow_cm_max": [float(v) for v in range(0, 65, 5)],
+ "cold_c_min": [float(v) for v in range(-5, 26)],
+ "heat_c_max": [float(v) for v in range(20, 46)],
+}
+
+SCORES = {"exact": 2, "within1": 1, "worse": 0}
+
+
+def held_out(tid):
+ """True when a stable hash of the id is odd. The split never
+ changes as records come and go, unlike a random one."""
+ return hashlib.sha256(str(tid).encode("utf-8")).digest()[-1] % 2 == 1
+
+
+def _grade_of(estimated, sourced_months):
+ if not estimated:
+ return "worse"
+ return season.grade(estimated, sourced_months)
+
+
+def season_kind(months):
+ """The kind of trail a sourced season describes, from the season
+ alone: "year-round" (eleven or twelve months), "cool-season" (hiked
+ in the cool months, none of June to August), "alpine" (a summer
+ season that leaves out December to February and covers July or
+ August, at most six months) or "other" (the shoulder seasons and
+ the rest)."""
+ months = set(months)
+ if len(months) >= 11:
+ return "year-round"
+ if not months & {6, 7, 8}:
+ return "cool-season"
+ if not months & {12, 1, 2} and months & {7, 8} and len(months) <= 6:
+ return "alpine"
+ return "other"
+
+
+KINDS = ("alpine", "cool-season", "year-round", "other")
+
+
+def fit_params(sourced, grid):
+ """Grid search the three thresholds for the best mean grade over
+ the estimable trails in sourced, a list of (id, normals, months)
+ with an optional fourth item ignored here. Grades score exact 2,
+ within one month 1, worse 0. Ties go to the first combination in
+ grid order, so the same input always gives the same numbers."""
+ prepared = []
+ for item in sourced:
+ medians = _medians(item[1])
+ if medians is not None:
+ prepared.append((medians, item[2]))
+ if not prepared:
+ raise ValueError("no estimable trails to fit on")
+ best, best_score = None, None
+ for snow in grid["snow_cm_max"]:
+ for cold in grid["cold_c_min"]:
+ for heat in grid["heat_c_max"]:
+ params = Params(snow_cm_max=float(snow), cold_c_min=float(cold),
+ heat_c_max=float(heat))
+ total = sum(SCORES[_grade_of(_months_from(med, params), months)]
+ for med, months in prepared)
+ score = total / len(prepared)
+ if best_score is None or score > best_score:
+ best, best_score = params, score
+ return best
+
+
+def report(sourced, params):
+ """Counts of how the rule does on sourced trails: n, exact,
+ within1 (which counts exact too, so within1 + worse + no_data is
+ n), worse and no_data, plus the same per region group in by_group.
+ A trail whose points lack data is no_data; a trail with data but
+ no qualifying month grades worse."""
+ counts = {"n": 0, "exact": 0, "within1": 0, "worse": 0, "no_data": 0}
+ by_group = {}
+ by_kind = {k: dict(counts) for k in KINDS}
+ for item in sourced:
+ group = item[3] if len(item) > 3 else season_batches.OTHER
+ bucket = by_group.setdefault(
+ group, {"n": 0, "exact": 0, "within1": 0, "worse": 0, "no_data": 0})
+ kind_bucket = by_kind[season_kind(item[2])]
+ medians = _medians(item[1])
+ for target in (counts, bucket, kind_bucket):
+ target["n"] += 1
+ if medians is None:
+ for target in (counts, bucket, kind_bucket):
+ target["no_data"] += 1
+ continue
+ grade = _grade_of(_months_from(medians, params), item[2])
+ for target in (counts, bucket, kind_bucket):
+ if grade == "exact":
+ target["exact"] += 1
+ target["within1"] += 1
+ elif grade == "within1":
+ target["within1"] += 1
+ else:
+ target["worse"] += 1
+ counts["by_group"] = by_group
+ counts["by_kind"] = by_kind
+ return counts
+
+
+def passes_bar(rep, bar=BAR):
+ """The owner's bar: at least 75 percent of held-out sourced trails
+ within one month at each end, and at least 90 percent estimable."""
+ n = rep.get("n") or 0
+ if not n:
+ return False
+ return (rep["within1"] / n >= bar["within1_min"]
+ and 1 - rep["no_data"] / n >= bar["coverage_min"])
+
+
+def _records(root):
+ for tid in refresh.trail_ids(root):
+ yield tid, refresh.load_toml(os.path.join(root, tid, "trail.toml"))
+
+
+def normals_at(points, fetch):
+ return [fetch(p.lat, p.lon, p.elev_m) for p in points]
+
+
+def sourced_trails(root, fetch, log=None):
+ """(id, normals, sourced months, region group) for every record
+ whose season comes from a page. Fetching goes through the climate
+ cache; a network failure aborts the run and a rerun resumes from
+ the cache, so no point is ever downloaded twice."""
+ out = []
+ for tid, rec in _records(root):
+ hike = rec.get("hike") or {}
+ if not hike.get("season") or hike.get("season_basis") == "estimate":
+ continue
+ points, kind = sample_points(root, rec)
+ normals = normals_at(points, fetch)
+ if log:
+ log(f"{tid}: {kind}, {len(points)} points")
+ out.append((tid, normals, list(hike.get("months") or []),
+ season_batches.group_of(rec)))
+ return out
+
+
+def _fetch_with_cache(cache_dir):
+ if cache_dir is None:
+ return season_climate.fetch_normals
+ return lambda lat, lon, elev: season_climate.fetch_normals(
+ lat, lon, elev, cache=cache_dir)
+
+
+def _params_doc(params):
+ return {"snow_cm_max": params.snow_cm_max, "cold_c_min": params.cold_c_min,
+ "heat_c_max": params.heat_c_max}
+
+
+def cmd_fit(args):
+ fetch = _fetch_with_cache(args.cache)
+ sourced = sourced_trails(ROOT, fetch, log=lambda line: print(line, flush=True))
+ train = [s for s in sourced if not held_out(s[0])]
+ test = [s for s in sourced if held_out(s[0])]
+ train_params = fit_params(train, DEFAULT_GRID)
+ held = report(test, train_params)
+ shipped = fit_params(sourced, DEFAULT_GRID)
+ whole = report(sourced, shipped)
+ doc = {
+ "computed": datetime.date.today().isoformat(),
+ "rule_version": RULE_VERSION,
+ "dataset": season_climate.SOURCE["name"],
+ "period": season_climate.SOURCE["period"],
+ "params": _params_doc(shipped),
+ "held_out_params": _params_doc(train_params),
+ "all": whole,
+ "held_out": held,
+ "bar": BAR,
+ "passes": passes_bar(held),
+ }
+ path = os.path.join(ROOT, "tools", "season_fit.json")
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(doc, f, indent=1, sort_keys=True)
+ f.write("\n")
+ print(f"sourced {len(sourced)} (train {len(train)}, held out {len(test)})")
+ print(f"held out: within1 {held['within1']}/{held['n']}, "
+ f"exact {held['exact']}, worse {held['worse']}, "
+ f"no data {held['no_data']}, passes {doc['passes']}")
+ print(f"all: within1 {whole['within1']}/{whole['n']}, "
+ f"exact {whole['exact']}, worse {whole['worse']}, "
+ f"no data {whole['no_data']}")
+ print(f"shipped params {_params_doc(shipped)} "
+ f"(held-out fit {_params_doc(train_params)})")
+ print(f"wrote {path}")
+ return 0
+
+
+
+# ---------------------------------------------------------------------------
+# Estimates for trails with no sourced season, the review list a person
+# reads, the staged proposals that write accepted estimates through the
+# refresh pipeline, and the check that reruns both.
+
+COARSE_PARAMS = Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
+
+# The trial's twelve, by rule: akshayuk-pass is the far north trail;
+# great-divide-trail and west-coast-trail are in Canada; john-muir,
+# colorado-trail and uinta-highline are alpine; desert-winter-thru-hike
+# and arizona are desert; west-coast-trail and washington-coast-trail
+# are coastal; maah-daah-hey is prairie; florida is the southeast;
+# superior-hiking fills the dozen from the midwest.
+TRIAL_TRAILS = ["akshayuk-pass", "great-divide-trail", "west-coast-trail",
+ "john-muir", "colorado-trail", "uinta-highline",
+ "desert-winter-thru-hike", "arizona", "florida",
+ "washington-coast-trail", "maah-daah-hey", "superior-hiking"]
+
+FLAG_ORDER = ("no-track", "place-centre", "no-data", "no-month",
+ "desert", "coast", "far-north", "few-points")
+
+_CENTRES = {}
+
+
+def _centre(points):
+ if not points:
+ return None
+ return (sum(p.lat for p in points) / len(points),
+ sum(p.lon for p in points) / len(points))
+
+
+def _sourced_centres(root):
+ """(id, centre lat, centre lon, season phrase) for sourced trails,
+ computed once per root per run: sampling every track again for
+ each estimate would make the review list take minutes."""
+ if root not in _CENTRES:
+ out = []
+ for tid, rec in _records(root):
+ hike = rec.get("hike") or {}
+ if not hike.get("season") or hike.get("season_basis") == "estimate":
+ continue
+ points, _kind = sample_points(root, rec)
+ centre = _centre(points)
+ if centre:
+ out.append((tid, centre[0], centre[1], str(hike.get("season"))))
+ _CENTRES[root] = out
+ return _CENTRES[root]
+
+
+def _flags(points, kind, normals, medians, params):
+ found = set()
+ if kind != "track":
+ found.add("no-track")
+ if kind == "place":
+ found.add("place-centre")
+ if len(points) < 3:
+ found.add("few-points")
+ if points and max(p.lat for p in points) > 60:
+ found.add("far-north")
+ if medians is None:
+ found.add("no-data")
+ else:
+ elevs = [n.elev_m for n in normals if n is not None]
+ if elevs and max(elevs) <= 200:
+ found.add("coast")
+ high_tmax, high_snow, low_tmax = medians
+ for m in range(12):
+ cold_ok = high_tmax[m] is not None and high_tmax[m] >= params.cold_c_min
+ snow_ok = high_snow[m] is None or high_snow[m] <= params.snow_cm_max
+ heat_ok = low_tmax[m] is not None and low_tmax[m] <= params.heat_c_max
+ if cold_ok and snow_ok and not heat_ok:
+ found.add("desert")
+ break
+ if not _months_from(medians, params):
+ found.add("no-month")
+ return [name for name in FLAG_ORDER if name in found]
+
+
+def estimate(root, rec, params, fetch=season_climate.fetch_normals):
+ """One trail's estimated season and how much to trust it: months
+ (None when unestimable, with the reason), the phrase and method
+ sentence an accepted estimate would carry, how its points were got,
+ flags for hand review, and the nearest sourced trail to compare
+ it with. Fetch errors propagate; nothing here touches the network
+ except through fetch."""
+ points, kind = sample_points(root, rec)
+ normals = normals_at(points, fetch)
+ medians = _medians(normals)
+ months = _months_from(medians, params) if medians is not None else None
+ months = months or None
+ comparable, comparable_phrase = "", ""
+ centre = _centre(points)
+ if centre:
+ best = None
+ for tid, clat, clon, phrase in _sourced_centres(root):
+ if tid == rec.get("id"):
+ continue
+ dist = season_climate.haversine_km(centre[0], centre[1], clat, clon)
+ if best is None or dist < best[0]:
+ best = (dist, tid, phrase)
+ if best:
+ comparable, comparable_phrase = best[1], best[2]
+ return {
+ "months": months,
+ "phrase": season.phrase_for(months) if months else "",
+ "method": season.method_sentence(
+ season_climate.SOURCE["name"], season_climate.SOURCE["period"],
+ len(points), kind, RULE_VERSION),
+ "kind": kind,
+ "flags": _flags(points, kind, normals, medians, params),
+ "comparable": comparable,
+ "comparable_phrase": comparable_phrase,
+ "reason": "" if months else why_not(normals, params),
+ "points": points,
+ "normals": normals,
+ }
+
+
+def load_fit(root):
+ with open(os.path.join(root, "tools", "season_fit.json"), encoding="utf-8") as f:
+ return json.load(f)
+
+
+def load_params(root):
+ doc = load_fit(root)["params"]
+ return Params(snow_cm_max=float(doc["snow_cm_max"]),
+ cold_c_min=float(doc["cold_c_min"]),
+ heat_c_max=float(doc["heat_c_max"]))
+
+
+def _with_cache(fetch_fn, cache_dir):
+ if cache_dir is None:
+ return fetch_fn
+ return lambda lat, lon, elev: fetch_fn(lat, lon, elev, cache=cache_dir)
+
+
+def propose(root, params, fetch, given_dir=None):
+ """Write the review list, one row per trail with no season, to
+ /season/estimates.csv and list every unestimable trail
+ with its reason. Returns the row count."""
+ staging = refresh.staging_dir(root, given_dir, create=True)
+ out_dir = os.path.join(staging, "season")
+ os.makedirs(out_dir, exist_ok=True)
+ rows, unestimable = [], []
+ for tid, rec in _records(root):
+ if (rec.get("hike") or {}).get("season"):
+ continue
+ est = estimate(root, rec, params, fetch)
+ rows.append([tid, " ".join(str(m) for m in est["months"] or []),
+ est["phrase"], est["kind"], ";".join(est["flags"]),
+ est["comparable"], est["comparable_phrase"]])
+ if not est["months"]:
+ unestimable.append((tid, est["reason"]))
+ path = os.path.join(out_dir, "estimates.csv")
+ with open(path, "w", newline="", encoding="utf-8") as f:
+ writer = csv.writer(f)
+ writer.writerow(["id", "proposed_months", "phrase", "kind", "flags",
+ "comparable", "comparable_phrase"])
+ writer.writerows(rows)
+ for tid, reason in unestimable:
+ print(f"{tid}: not estimable: {reason}")
+ print(f"{len(rows)} rows written to {path} "
+ f"({len(unestimable)} not estimable)")
+ return len(rows)
+
+
+def _toml_str(text):
+ return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def _parse_months(text):
+ months = []
+ for piece in (text or "").replace(",", " ").replace(";", " ").split():
+ months.append(int(piece))
+ return sorted(set(months))
+
+
+def proposals(root, reviewed_csv, given_dir=None):
+ """Stage one change proposal per accepted reviewed row (a row with
+ months). A row with a note was adjusted by hand, and its method
+ sentence says so. Returns how many proposals were staged."""
+ with open(reviewed_csv, newline="", encoding="utf-8") as f:
+ reviewed = list(csv.DictReader(f))
+ staging = refresh.staging_dir(root, given_dir, create=True)
+ out = os.path.join(staging, "staged", "season-estimate")
+ today = datetime.date.today().isoformat()
+ source = season_climate.SOURCE
+ report = []
+ for row in reviewed:
+ tid = (row.get("id") or "").strip()
+ try:
+ months = _parse_months(row.get("proposed_months"))
+ except ValueError:
+ raise ValueError(f"{tid}: proposed_months {row.get('proposed_months')!r} "
+ "is not a list of month numbers")
+ if not tid or not months:
+ continue
+ rec = refresh.load_toml(os.path.join(root, tid, "trail.toml"))
+ hike = rec.get("hike") or {}
+ if hike.get("season"):
+ raise ValueError(f"{tid}: already has a season")
+ points, kind = sample_points(root, rec)
+ phrase = season.phrase_for(months)
+ method = season.method_sentence(source["name"], source["period"],
+ len(points), kind, RULE_VERSION)
+ note = (row.get("note") or "").strip()
+ comparable = (row.get("comparable") or "").strip()
+ if note and comparable:
+ method = method[:-1] + f", and adjusted by hand against {comparable}."
+ quote = (f"Monthly climate ({source['period']}) from {source['name']} "
+ f"gives {phrase} at the trail elevation.")
+ page = source["url"]
+ lines = ["[[proposal]]", 'kind = "change"', f"id = {_toml_str(tid)}",
+ f"date = {_toml_str(today)}",
+ f"summary = {_toml_str('Add an estimated season: ' + phrase + '.')}", ""]
+
+ def edit(field, new_toml, old_toml=None):
+ lines.append("[[proposal.edit]]")
+ lines.append(f"field = {_toml_str(field)}")
+ if old_toml is not None:
+ lines.append(f"old = {old_toml}")
+ lines.append(f"new = {new_toml}")
+ lines.append(f"page = {_toml_str(page)}")
+ lines.append(f"quote = {_toml_str(quote)}")
+ lines.append("")
+
+ edit("hike.season", _toml_str(phrase))
+ edit("hike.months", "[" + ", ".join(str(m) for m in months) + "]")
+ edit("hike.season_basis", _toml_str("estimate"))
+ edit("hike.season_method", _toml_str(method))
+ checked_old = hike.get("checked")
+ edit("hike.checked", _toml_str(today),
+ _toml_str(checked_old) if checked_old else None)
+ lines += ["[[proposal.append]]", 'table = "hike.source"',
+ f"page = {_toml_str(page)}", f"quote = {_toml_str(quote)}", "",
+ "[proposal.append.entry]",
+ f"url = {_toml_str(page)}",
+ f"publisher = {_toml_str(source['publisher'])}",
+ 'facts = ["season", "months"]', "",
+ "[proposal.history]",
+ f"change = {_toml_str('A season was estimated from climate: ' + phrase + '.')}",
+ f"basis = {_toml_str('No page states a season; it is estimated from climate (rule version ' + str(RULE_VERSION) + ').')}",
+ f"basis_url = {_toml_str(page)}",
+ 'asked_by = "the dataset\'s own check"',
+ 'fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]',
+ ""]
+ d = os.path.join(out, tid)
+ os.makedirs(d, exist_ok=True)
+ with open(os.path.join(d, "proposal.toml"), "w", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+ remark = f"estimated season {phrase}" + (f"; note: {note}" if note else "")
+ report.append((tid, "changed", page, remark))
+ os.makedirs(out, exist_ok=True)
+ with open(os.path.join(out, "report.csv"), "w", newline="", encoding="utf-8") as f:
+ writer = csv.writer(f)
+ writer.writerow(["id", "outcome", "pages", "remark"])
+ writer.writerows(report)
+ return len(report)
+
+
+def check(root, fetch):
+ """Rerun every estimated season and the held-out fit. Returns
+ (ok, lines): not ok when an estimate would now come out different,
+ when the held-out within-one-month share has fallen by more than
+ 0.02 from season_fit.json, or when that file does not pass."""
+ try:
+ fit = load_fit(root)
+ except OSError:
+ return False, ["tools/season_fit.json is missing: run "
+ "python3 tools/estimate_season.py fit"]
+ params = load_params(root)
+ ok, lines, checked = True, [], 0
+ for tid, rec in _records(root):
+ hike = rec.get("hike") or {}
+ if hike.get("season_basis") != "estimate":
+ continue
+ checked += 1
+ est = estimate(root, rec, params, fetch)
+ old = sorted(int(m) for m in hike.get("months") or [])
+ new = sorted(est["months"] or [])
+ if new != old:
+ ok = False
+ detail = est["phrase"] or est["reason"]
+ lines.append(f"{tid}: estimate was {old}, now {new} ({detail})")
+ sourced = sourced_trails(root, fetch)
+ train = [s for s in sourced if not held_out(s[0])]
+ test = [s for s in sourced if held_out(s[0])]
+ if train and test:
+ try:
+ now = report(test, fit_params(train, DEFAULT_GRID))
+ except ValueError:
+ now = None
+ stored = fit.get("held_out") or {}
+ if now and stored.get("n"):
+ was_share = stored["within1"] / stored["n"]
+ now_share = now["within1"] / now["n"] if now["n"] else 0.0
+ if was_share - now_share > 0.02:
+ ok = False
+ lines.append(
+ f"fit got worse: held-out within one month "
+ f"{now['within1']}/{now['n']} ({now_share:.2f}), "
+ f"was {stored['within1']}/{stored['n']} ({was_share:.2f})")
+ if not fit.get("passes"):
+ ok = False
+ lines.append("tools/season_fit.json does not pass the bar; "
+ "estimates must not ship")
+ if ok:
+ lines.append(f"check passed: {checked} estimated seasons unchanged")
+ return ok, lines
+
+
+def cmd_trial(args):
+ for name, fetch_fn in season_climate.CANDIDATES.items():
+ fetch = _with_cache(fetch_fn, args.cache)
+ print(f"{name}: trail (sourced months) gives estimated months, grade")
+ data = within = 0
+ for tid in TRIAL_TRAILS:
+ rec = refresh.load_toml(os.path.join(ROOT, tid, "trail.toml"))
+ sourced = list((rec.get("hike") or {}).get("months") or [])
+ points, _kind = sample_points(ROOT, rec)
+ try:
+ normals = normals_at(points, fetch)
+ except Exception as exc:
+ print(f" {tid} ({sourced}): error {type(exc).__name__}: {exc}")
+ continue
+ months = months_in_season(normals, COARSE_PARAMS) if points else None
+ if normals and all(n is not None for n in normals):
+ data += 1
+ grade = season.grade(months, sourced) if months else "no-month"
+ within += grade in ("exact", "within1")
+ print(f" {tid} ({sourced}): {months}, {grade}")
+ else:
+ print(f" {tid} ({sourced}): no data")
+ print(f" data for {data} of {len(TRIAL_TRAILS)}, "
+ f"exact or within one month for {within}")
+ return 0
+
+
+def all_sample_points(root):
+ """Every sample point for every record, as (id, kind, points)."""
+ out = []
+ for tid, rec in _records(root):
+ points, kind = sample_points(root, rec)
+ out.append((tid, kind, points))
+ return out
+
+
+def cmd_warm(args):
+ """Read the climate for every sample point of every trail into the
+ cache, several points at a time. Safe to stop and rerun."""
+ from concurrent.futures import ThreadPoolExecutor
+ fetch = _fetch_with_cache(args.cache)
+ jobs = []
+ seen = set()
+ for _tid, _kind, points in all_sample_points(ROOT):
+ for p in points:
+ key = (round(p.lat, 3), round(p.lon, 3),
+ None if p.elev_m is None else int(round(p.elev_m)))
+ if key not in seen:
+ seen.add(key)
+ jobs.append(p)
+ print(f"{len(jobs)} distinct points", flush=True)
+ done = [0]
+ nodata = [0]
+
+ def one(p):
+ n = fetch(p.lat, p.lon, p.elev_m)
+ done[0] += 1
+ if n is None:
+ nodata[0] += 1
+ if done[0] % 25 == 0 or done[0] == len(jobs):
+ print(f"{done[0]}/{len(jobs)} done, {nodata[0]} without data",
+ flush=True)
+
+ with ThreadPoolExecutor(max_workers=args.workers) as pool:
+ list(pool.map(one, jobs))
+ print("warm finished", flush=True)
+ return 0
+
+
+def cmd_propose(args):
+ fetch = _fetch_with_cache(args.cache)
+ propose(ROOT, load_params(ROOT), fetch, args.dir)
+ return 0
+
+
+def cmd_proposals(args):
+ count = proposals(ROOT, args.reviewed, args.dir)
+ print(f"{count} proposals staged")
+ return 0
+
+
+def cmd_check(args):
+ fetch = _fetch_with_cache(args.cache)
+ ok, lines = check(ROOT, fetch)
+ for line in lines:
+ print(line)
+ return 0 if ok else 1
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ sub = parser.add_subparsers(dest="command", required=True)
+ fit_parser = sub.add_parser(
+ "fit", help="fit the rule against the sourced seasons")
+ fit_parser.add_argument("--cache", default=None,
+ help="climate cache directory")
+ fit_parser.set_defaults(func=cmd_fit)
+ trial_parser = sub.add_parser(
+ "trial", help="compare the climate candidates on twelve trails")
+ trial_parser.add_argument("--cache", default=None,
+ help="climate cache directory")
+ trial_parser.set_defaults(func=cmd_trial)
+ warm_parser = sub.add_parser(
+ "warm", help="read the climate for every sample point into the cache")
+ warm_parser.add_argument("--cache", default=None,
+ help="climate cache directory")
+ warm_parser.add_argument("--workers", type=int, default=6)
+ warm_parser.set_defaults(func=cmd_warm)
+ propose_parser = sub.add_parser(
+ "propose", help="write the estimate review list")
+ propose_parser.add_argument("--dir", default=None,
+ help="staging directory")
+ propose_parser.add_argument("--cache", default=None,
+ help="climate cache directory")
+ propose_parser.set_defaults(func=cmd_propose)
+ proposals_parser = sub.add_parser(
+ "proposals", help="stage proposals from a reviewed list")
+ proposals_parser.add_argument("--reviewed", required=True,
+ help="reviewed estimates CSV")
+ proposals_parser.add_argument("--dir", default=None,
+ help="staging directory")
+ proposals_parser.set_defaults(func=cmd_proposals)
+ check_parser = sub.add_parser(
+ "check", help="rerun every estimate and the fit")
+ check_parser.add_argument("--cache", default=None,
+ help="climate cache directory")
+ check_parser.set_defaults(func=cmd_check)
+ argv = ["check" if a == "--check" else a
+ for a in (sys.argv[1:] if argv is None else argv)]
+ args = parser.parse_args(argv)
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/season_fit.json b/tools/season_fit.json
new file mode 100644
index 0000000..7162650
--- /dev/null
+++ b/tools/season_fit.json
@@ -0,0 +1,225 @@
+{
+ "all": {
+ "by_group": {
+ "Canada east and north": {
+ "exact": 0,
+ "n": 8,
+ "no_data": 0,
+ "within1": 5,
+ "worse": 3
+ },
+ "Canada west": {
+ "exact": 1,
+ "n": 11,
+ "no_data": 0,
+ "within1": 7,
+ "worse": 4
+ },
+ "Rockies": {
+ "exact": 2,
+ "n": 22,
+ "no_data": 0,
+ "within1": 15,
+ "worse": 7
+ },
+ "interior west": {
+ "exact": 3,
+ "n": 10,
+ "no_data": 0,
+ "within1": 6,
+ "worse": 4
+ },
+ "northeast": {
+ "exact": 0,
+ "n": 6,
+ "no_data": 0,
+ "within1": 3,
+ "worse": 3
+ },
+ "plains and midwest": {
+ "exact": 1,
+ "n": 3,
+ "no_data": 0,
+ "within1": 1,
+ "worse": 2
+ },
+ "southeast": {
+ "exact": 3,
+ "n": 10,
+ "no_data": 0,
+ "within1": 4,
+ "worse": 6
+ },
+ "southwest": {
+ "exact": 3,
+ "n": 17,
+ "no_data": 0,
+ "within1": 8,
+ "worse": 9
+ },
+ "west coast": {
+ "exact": 0,
+ "n": 22,
+ "no_data": 0,
+ "within1": 12,
+ "worse": 10
+ }
+ },
+ "by_kind": {
+ "alpine": {
+ "exact": 6,
+ "n": 63,
+ "no_data": 0,
+ "within1": 44,
+ "worse": 19
+ },
+ "cool-season": {
+ "exact": 5,
+ "n": 30,
+ "no_data": 0,
+ "within1": 12,
+ "worse": 18
+ },
+ "other": {
+ "exact": 2,
+ "n": 8,
+ "no_data": 0,
+ "within1": 5,
+ "worse": 3
+ },
+ "year-round": {
+ "exact": 0,
+ "n": 8,
+ "no_data": 0,
+ "within1": 0,
+ "worse": 8
+ }
+ },
+ "exact": 13,
+ "n": 109,
+ "no_data": 0,
+ "within1": 61,
+ "worse": 48
+ },
+ "bar": {
+ "coverage_min": 0.9,
+ "within1_min": 0.75
+ },
+ "computed": "2026-11-20",
+ "dataset": "CHELSA V2.1 climatologies, with ETOPO 2022 elevation",
+ "held_out": {
+ "by_group": {
+ "Canada east and north": {
+ "exact": 0,
+ "n": 2,
+ "no_data": 0,
+ "within1": 0,
+ "worse": 2
+ },
+ "Canada west": {
+ "exact": 0,
+ "n": 6,
+ "no_data": 0,
+ "within1": 1,
+ "worse": 5
+ },
+ "Rockies": {
+ "exact": 1,
+ "n": 9,
+ "no_data": 0,
+ "within1": 5,
+ "worse": 4
+ },
+ "interior west": {
+ "exact": 3,
+ "n": 3,
+ "no_data": 0,
+ "within1": 3,
+ "worse": 0
+ },
+ "northeast": {
+ "exact": 0,
+ "n": 2,
+ "no_data": 0,
+ "within1": 0,
+ "worse": 2
+ },
+ "plains and midwest": {
+ "exact": 0,
+ "n": 1,
+ "no_data": 0,
+ "within1": 0,
+ "worse": 1
+ },
+ "southeast": {
+ "exact": 0,
+ "n": 4,
+ "no_data": 0,
+ "within1": 0,
+ "worse": 4
+ },
+ "southwest": {
+ "exact": 0,
+ "n": 9,
+ "no_data": 0,
+ "within1": 2,
+ "worse": 7
+ },
+ "west coast": {
+ "exact": 0,
+ "n": 12,
+ "no_data": 0,
+ "within1": 5,
+ "worse": 7
+ }
+ },
+ "by_kind": {
+ "alpine": {
+ "exact": 4,
+ "n": 24,
+ "no_data": 0,
+ "within1": 12,
+ "worse": 12
+ },
+ "cool-season": {
+ "exact": 0,
+ "n": 15,
+ "no_data": 0,
+ "within1": 2,
+ "worse": 13
+ },
+ "other": {
+ "exact": 0,
+ "n": 4,
+ "no_data": 0,
+ "within1": 2,
+ "worse": 2
+ },
+ "year-round": {
+ "exact": 0,
+ "n": 5,
+ "no_data": 0,
+ "within1": 0,
+ "worse": 5
+ }
+ },
+ "exact": 4,
+ "n": 48,
+ "no_data": 0,
+ "within1": 16,
+ "worse": 32
+ },
+ "held_out_params": {
+ "cold_c_min": 14.0,
+ "heat_c_max": 31.0,
+ "snow_cm_max": 0.0
+ },
+ "params": {
+ "cold_c_min": 12.0,
+ "heat_c_max": 28.0,
+ "snow_cm_max": 0.0
+ },
+ "passes": false,
+ "period": "1981-2010",
+ "rule_version": 1
+}
diff --git a/tools/tests/test_estimate_season.py b/tools/tests/test_estimate_season.py
index a1bc3e2..750c04d 100644
--- a/tools/tests/test_estimate_season.py
+++ b/tools/tests/test_estimate_season.py
@@ -4,14 +4,19 @@ normals, so they run with no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
+import csv
+import json
import os
+import shutil
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 estimate_season as E # noqa: E402
+import test_refresh as TR # noqa: E402
import season_climate as C # noqa: E402
PARAMS = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
@@ -200,5 +205,311 @@ class SamplePointsTest(unittest.TestCase):
self.assertAlmostEqual(points[0].lat, 43.85)
+KNOWN = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=30.0)
+GRID = {"snow_cm_max": [float(v) for v in range(0, 65, 5)],
+ "cold_c_min": [float(v) for v in range(0, 13)],
+ "heat_c_max": [float(v) for v in range(24, 41)]}
+
+
+def synthetic_sourced():
+ """Trails whose sourced months come from KNOWN, designed so each
+ threshold is pinned by months just either side of it."""
+ cases = [
+ ("cold-pin", normals(3000, [4, 4, 6, 6, 10, 15, 20, 20, 15, 10, 6, 4],
+ snow=[0] * 12)),
+ ("snow-pin", normals(3000, [15] * 12,
+ snow=[20, 20, 12, 8, 0, 0, 0, 0, 0, 0, 8, 12])),
+ ("heat-pin", normals(400, [20, 22, 26, 29, 31, 36, 38, 38, 36, 31, 28, 22],
+ snow=[0] * 12)),
+ ("mild-all-year", normals(100, [15] * 12, snow=[0] * 12)),
+ ]
+ out = []
+ for tid, point in cases:
+ months = E.months_in_season([point], KNOWN)
+ assert months, tid
+ out.append((tid, [point], months))
+ return out
+
+
+class FitTest(unittest.TestCase):
+ def test_held_out_is_stable_and_splits_roughly_in_half(self):
+ ids = [f"trail-{i:04d}" for i in range(1000)]
+ again = [t for t in ids if E.held_out(t)]
+ self.assertEqual(again, [t for t in ids if E.held_out(t)])
+ share = len(again) / len(ids)
+ self.assertTrue(0.40 <= share <= 0.60, share)
+
+ def test_fit_recovers_known_params_from_synthetic_trails(self):
+ sourced = synthetic_sourced()
+ fitted = E.fit_params(sourced, GRID)
+ self.assertLessEqual(abs(fitted.snow_cm_max - KNOWN.snow_cm_max), 5)
+ self.assertLessEqual(abs(fitted.cold_c_min - KNOWN.cold_c_min), 1)
+ self.assertLessEqual(abs(fitted.heat_c_max - KNOWN.heat_c_max), 1)
+ self.assertEqual(E.report(sourced, fitted)["exact"], len(sourced))
+
+ def test_report_counts_grades_and_no_data(self):
+ params = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
+ mild = normals(100, [15] * 12, snow=[0] * 12)
+ alpine = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1],
+ snow=[0] * 12)
+ sourced = [
+ ("exact-1", [mild], list(range(1, 13))),
+ ("within-1", [alpine], [5, 6, 7, 8, 9]), # rule gives 4 to 10
+ ("worse-1", [alpine], [1, 2]),
+ ("nodata-1", [None], [6, 7, 8]),
+ ]
+ rep = E.report(sourced, params)
+ self.assertEqual(rep["n"], 4)
+ self.assertEqual(rep["exact"], 1)
+ self.assertEqual(rep["within1"], 2) # within1 counts exact too
+ self.assertEqual(rep["worse"], 1)
+ self.assertEqual(rep["no_data"], 1)
+ self.assertEqual(rep["within1"] + rep["worse"] + rep["no_data"], rep["n"])
+ self.assertIn("by_group", rep)
+
+ def test_passes_is_false_below_the_bar_and_true_at_it(self):
+ def rep(within1, no_data=0, n=100):
+ return {"n": n, "exact": 0, "within1": within1,
+ "worse": n - within1 - no_data, "no_data": no_data}
+ self.assertFalse(E.passes_bar(rep(74)))
+ self.assertTrue(E.passes_bar(rep(75)))
+ self.assertFalse(E.passes_bar(rep(90, no_data=11))) # coverage 89%
+
+ def test_the_same_input_gives_the_same_report_twice(self):
+ sourced = synthetic_sourced()
+ self.assertEqual(E.report(sourced, KNOWN), E.report(sourced, KNOWN))
+ self.assertEqual(E.fit_params(sourced, GRID), E.fit_params(sourced, GRID))
+
+
+def mild_fetch(lat, lon, elev):
+ return C.PointNormals(lat=float(lat), lon=float(lon),
+ elev_m=float(elev if elev is not None else 100.0),
+ tmax_c=tuple([15.0] * 12), snow_cm=tuple([0.0] * 12))
+
+
+def none_fetch(lat, lon, elev):
+ return None
+
+
+def bounds_root(td):
+ os.makedirs(os.path.join(td, "web"))
+ with open(os.path.join(td, "web", "place-bounds.toml"), "w") as f:
+ f.write('[box]\n"US-VT" = [-73.5, 42.7, -71.5, 45.0]\n')
+ return td
+
+
+def ends_rec(tid="trail-x", lat=43.0, extra=None):
+ hike = {"summary": "x", "checked": "2026-01-01", "source": [],
+ "start_lonlat": [-110.0, lat], "end_lonlat": [-109.0, lat + 1.0]}
+ hike.update(extra or {})
+ return {"id": tid, "country": "US", "regions": ["VT"],
+ "source": {"line_file": "line.geojson"}, "hike": hike}
+
+
+class EstimateTest(unittest.TestCase):
+ def test_a_no_track_record_is_flagged(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ est = E.estimate(bounds_root(td), ends_rec(), PARAMS, fetch=mild_fetch)
+ self.assertIn("no-track", est["flags"])
+ self.assertEqual(est["months"], list(range(1, 13)))
+ self.assertEqual(est["phrase"], "All year")
+
+ def test_a_trail_with_no_data_is_listed_not_estimated(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ est = E.estimate(bounds_root(td), ends_rec(), PARAMS, fetch=none_fetch)
+ self.assertIsNone(est["months"])
+ self.assertIn("no-data", est["flags"])
+ self.assertIn("no data", est["reason"])
+
+ def test_flags_include_far_north_above_sixty_degrees(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as td:
+ est = E.estimate(bounds_root(td), ends_rec(lat=61.0), PARAMS,
+ fetch=mild_fetch)
+ self.assertIn("far-north", est["flags"])
+
+ def test_nothing_in_estimate_touches_the_network_without_a_fetch(self):
+ import tempfile
+
+ def raising(lat, lon, elev):
+ raise AssertionError("network touched")
+
+ with tempfile.TemporaryDirectory() as td:
+ with self.assertRaises(AssertionError):
+ E.estimate(bounds_root(td), ends_rec(), PARAMS, fetch=raising)
+
+ def test_comparable_is_the_nearest_sourced_trail(self):
+ import tempfile, shutil
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = TR.make_repo(tmp, trails=[
+ ("near-one", "Near", {"extra_hike":
+ 'season = "June to September"\nmonths = [6, 7, 8, 9]\n'
+ 'season_basis = "source"\n'
+ 'start_lonlat = [-110.0, 43.1]\nend_lonlat = [-110.0, 43.3]\n'}),
+ ("far-one", "Far", {"extra_hike":
+ 'season = "July to August"\nmonths = [7, 8]\n'
+ 'season_basis = "source"\n'
+ 'start_lonlat = [-100.0, 35.0]\nend_lonlat = [-100.0, 35.2]\n'}),
+ ("target-one", "Target", {"extra_hike":
+ 'start_lonlat = [-110.0, 43.0]\nend_lonlat = [-110.0, 43.2]\n'}),
+ ])
+ os.makedirs(os.path.join(root, "web"))
+ with open(os.path.join(root, "web", "place-bounds.toml"), "w") as f:
+ f.write('[box]\n"US-VT" = [-73.5, 42.7, -71.5, 45.0]\n')
+ import refresh as R
+ rec = R.load_toml(os.path.join(root, "target-one", "trail.toml"))
+ # fixture records claim line_file "" so sampling uses the ends
+ rec["source"]["line_file"] = "line.geojson"
+ est = E.estimate(root, rec, PARAMS, fetch=mild_fetch)
+ self.assertEqual(est["comparable"], "near-one")
+ self.assertEqual(est["comparable_phrase"], "June to September")
+
+
+class ProposeCheckTest(unittest.TestCase):
+ def fit_doc(self, root, passes=True, held_within1=3, held_n=4):
+ os.makedirs(os.path.join(root, "tools"), exist_ok=True)
+ doc = {"computed": "2026-11-20", "rule_version": E.RULE_VERSION,
+ "dataset": "test", "period": "2011-2020",
+ "params": {"snow_cm_max": 10.0, "cold_c_min": 5.0,
+ "heat_c_max": 32.0},
+ "held_out": {"n": held_n, "exact": 0, "within1": held_within1,
+ "worse": held_n - held_within1, "no_data": 0,
+ "by_group": {}},
+ "all": {"n": held_n, "exact": 0, "within1": held_within1,
+ "worse": held_n - held_within1, "no_data": 0,
+ "by_group": {}},
+ "bar": E.BAR, "passes": passes}
+ with open(os.path.join(root, "tools", "season_fit.json"), "w") as f:
+ json.dump(doc, f)
+
+ def repo_with(self, tmp, trails):
+ root = TR.make_repo(tmp, trails=trails)
+ os.makedirs(os.path.join(root, "web"))
+ with open(os.path.join(root, "web", "place-bounds.toml"), "w") as f:
+ f.write('[box]\n"US-VT" = [-73.5, 42.7, -71.5, 45.0]\n')
+ # fixture records name no track file; point them at the default
+ for tid, _name, _kw in trails:
+ path = os.path.join(root, tid, "trail.toml")
+ text = TR.read(root, f"{tid}/trail.toml").replace(
+ 'line_file = ""', 'line_file = "line.geojson"')
+ TR.write(path, text)
+ return root
+
+ ENDS = 'start_lonlat = [-110.0, 43.0]\nend_lonlat = [-110.0, 43.2]\n'
+
+ def test_propose_writes_one_row_per_unsourced_trail(self):
+ import tempfile, shutil, csv
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.repo_with(tmp, [
+ ("aaa", "Aaa", {"extra_hike": self.ENDS}),
+ ("bbb", "Bbb", {"extra_hike":
+ 'season = "June to September"\nmonths = [6, 7, 8, 9]\n'
+ 'season_basis = "source"\n' + self.ENDS}),
+ ("ccc", "Ccc", {"hike": False}),
+ ])
+ stage = os.path.join(tmp, "stage")
+ n = E.propose(root, PARAMS, mild_fetch, stage)
+ self.assertEqual(n, 2) # aaa and ccc have no season
+ with open(os.path.join(stage, "season", "estimates.csv"),
+ newline="") as f:
+ rows = list(csv.DictReader(f))
+ self.assertEqual([r["id"] for r in rows], ["aaa", "ccc"])
+ self.assertEqual(rows[0]["phrase"], "All year")
+
+ def est_repo(self, tmp, months_extra):
+ return self.repo_with(tmp, [
+ ("aaa", "Aaa", {"extra_hike": months_extra + self.ENDS}),
+ ])
+
+ def test_check_passes_when_nothing_changed(self):
+ import tempfile, shutil
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.est_repo(
+ tmp,
+ 'season = "All year"\n'
+ 'months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n'
+ 'season_basis = "estimate"\nseason_method = "Estimated."\n')
+ self.fit_doc(root)
+ ok, lines = E.check(root, mild_fetch)
+ self.assertTrue(ok, lines)
+
+ def test_check_names_the_trail_whose_estimate_changed(self):
+ import tempfile, shutil
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.est_repo(
+ tmp,
+ 'season = "June to July"\nmonths = [6, 7]\n'
+ 'season_basis = "estimate"\nseason_method = "Estimated."\n')
+ self.fit_doc(root)
+ ok, lines = E.check(root, mild_fetch)
+ self.assertFalse(ok)
+ self.assertTrue(any("aaa" in line and "[6, 7]" in line
+ for line in lines), lines)
+
+ def test_check_fails_when_the_fit_got_worse(self):
+ import tempfile, shutil
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ # one train and one held-out sourced trail, both graded worse
+ # by mild all-year normals against a June-only season
+ ids = [f"trail-{i:03d}" for i in range(40)]
+ train_id = next(t for t in ids if not E.held_out(t))
+ test_id = next(t for t in ids if E.held_out(t))
+ extra = ('season = "June"\nmonths = [6]\n'
+ 'season_basis = "source"\n' + self.ENDS)
+ root = self.repo_with(tmp, [(train_id, "Train", {"extra_hike": extra}),
+ (test_id, "Test", {"extra_hike": extra})])
+ self.fit_doc(root, held_within1=4, held_n=4)
+ ok, lines = E.check(root, mild_fetch)
+ self.assertFalse(ok)
+ self.assertTrue(any("fit got worse" in line for line in lines), lines)
+
+ def test_proposals_collect_cleanly(self):
+ import tempfile, shutil, csv
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.repo_with(tmp, [("aaa", "Aaa", {"extra_hike": self.ENDS})])
+ stage = os.path.join(tmp, "stage")
+ os.makedirs(os.path.join(stage, "season"))
+ reviewed = os.path.join(stage, "season", "estimates.reviewed.csv")
+ with open(reviewed, "w", newline="") as f:
+ w = csv.writer(f)
+ w.writerow(["id", "proposed_months", "phrase", "kind", "flags",
+ "comparable", "comparable_phrase", "note"])
+ w.writerow(["aaa", "6 7 8 9", "June to September", "ends",
+ "no-track", "", "", ""])
+ self.assertEqual(E.proposals(root, reviewed, stage), 1)
+ code, out = TR.main(root, "--dir", stage, "collect")
+ self.assertEqual(code, 0, out)
+ import refresh as R
+ coll = R.load_toml(os.path.join(stage, "collected.toml"))
+ props = coll["proposal"]
+ self.assertEqual(len(props), 1)
+ self.assertEqual(props[0]["status"], "proposed", out)
+
+
+class SeasonKindTest(unittest.TestCase):
+ def test_kinds_of_sourced_seasons(self):
+ self.assertEqual(E.season_kind(list(range(1, 13))), "year-round")
+ self.assertEqual(E.season_kind([7, 8, 9]), "alpine")
+ self.assertEqual(E.season_kind([10, 11, 12, 1, 2, 3, 4]), "cool-season")
+ self.assertEqual(E.season_kind([4, 5, 6, 7, 8, 9, 10]), "other")
+
+ def test_the_report_splits_by_kind(self):
+ def pn(v):
+ return C.PointNormals(40.0, -100.0, 1000.0, tuple([v] * 12))
+ sourced = [("a", [pn(20.0)], list(range(1, 13)), "x")]
+ rep = E.report(sourced, E.Params(10.0, 5.0, 40.0))
+ self.assertEqual(rep["by_kind"]["year-round"]["n"], 1)
+ self.assertEqual(rep["by_kind"]["year-round"]["exact"], 1)
+ self.assertEqual(rep["by_kind"]["alpine"]["n"], 0)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/tests/test_season_fit.py b/tools/tests/test_season_fit.py
new file mode 100644
index 0000000..f15e7e4
--- /dev/null
+++ b/tools/tests/test_season_fit.py
@@ -0,0 +1,60 @@
+"""Tests for the committed fit figure in tools/season_fit.json.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import json
+import os
+import sys
+import unittest
+
+sys.dont_write_bytecode = True
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import estimate_season as E # noqa: E402
+import refresh # noqa: E402
+import validate as V # noqa: E402
+
+FIT_PATH = os.path.join(V.ROOT, "tools", "season_fit.json")
+
+
+def load_fit():
+ with open(FIT_PATH, encoding="utf-8") as f:
+ return json.load(f)
+
+
+class SeasonFitFileTest(unittest.TestCase):
+ def test_the_committed_fit_has_the_fields_the_site_reads(self):
+ fit = load_fit()
+ for key in ("computed", "rule_version", "dataset", "period",
+ "params", "all", "held_out", "bar", "passes"):
+ self.assertIn(key, fit)
+ for key in ("snow_cm_max", "cold_c_min", "heat_c_max"):
+ self.assertIn(key, fit["params"])
+ for part in ("all", "held_out"):
+ for key in ("n", "exact", "within1", "worse", "no_data", "by_group"):
+ self.assertIn(key, fit[part], part)
+ rep = fit[part]
+ self.assertEqual(rep["within1"] + rep["worse"] + rep["no_data"],
+ rep["n"], part)
+ self.assertEqual(fit["bar"], E.BAR)
+ self.assertEqual(fit["rule_version"], E.RULE_VERSION)
+ self.assertEqual(fit["passes"], E.passes_bar(fit["held_out"], fit["bar"]))
+
+ def test_estimates_only_with_a_passing_fit(self):
+ estimated = []
+ for tid in refresh.trail_ids(V.ROOT):
+ rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
+ if (rec.get("hike") or {}).get("season_basis") == "estimate":
+ estimated.append(tid)
+ if not estimated:
+ self.skipTest("no estimated seasons on file yet")
+ fit = load_fit()
+ self.assertTrue(fit["passes"], fit)
+ held = fit["held_out"]
+ self.assertGreaterEqual(held["within1"] / held["n"],
+ E.BAR["within1_min"])
+
+
+if __name__ == "__main__":
+ unittest.main()
From 748186d306d0867873fd2318a17ab7f3ec52a2a9 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 12:36:37 -0700
Subject: [PATCH 08/30] Estimate seasons by blending climate thresholds with
the seasons of the most similar sourced trails, scored leave-one-out against
the owner's measure
The earlier two-threshold rule matched 33 percent on a held-out half. The new method keeps the cold and heat thresholds and lets the twenty most similar sourced trails confirm or add months. Leave-one-out it matches 100 of 148 sourced seasons (67.6 percent), still under the 75 percent bar, so the fit file says it does not pass and estimates must not ship.
Co-Authored-By: Claude Sonnet 5.5
---
tools/estimate_season.py | 518 +++++++++++-----------------
tools/season_fit.json | 251 +++++---------
tools/season_model.py | 435 +++++++++++++++++++++++
tools/tests/test_estimate_season.py | 205 ++++-------
tools/tests/test_season_fit.py | 14 +-
tools/tests/test_season_model.py | 185 ++++++++++
6 files changed, 987 insertions(+), 621 deletions(-)
create mode 100644 tools/season_model.py
create mode 100644 tools/tests/test_season_model.py
diff --git a/tools/estimate_season.py b/tools/estimate_season.py
index 006dca7..a3d8fa9 100644
--- a/tools/estimate_season.py
+++ b/tools/estimate_season.py
@@ -1,28 +1,22 @@
#!/usr/bin/env python3
"""Estimate a hiking season from climate, for trails no page gives one.
-Python 3 standard library only. The rule is a pure function over monthly
-normals (tools/season_climate.py does the downloading, cached outside
-the repository), so its tests run with no network. See
-docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md.
+Python 3 standard library only. The estimator itself is a pure function
+over monthly climate normals (tools/season_model.py: thresholds on the
+track's high and low ground, blended with the seasons of the most
+similar sourced trails); this file finds a trail's sample points, reads
+their normals (tools/season_climate.py does the downloading, cached
+outside the repository) and runs the model, so its tests run with no
+network. See docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md.
-A month is in season when the trail's high ground is normally free of
-deep snow and not bitterly cold, and its low ground is not dangerously
-hot: over the high-ground points (at or above the upper quartile of
-the sample elevations), the median mean daily high is at least
-cold_c_min and the median mean snow depth is at most snow_cm_max, and
-over the low-ground points (at or below the median elevation) the
-median mean daily high is at most heat_c_max. When no high-ground
-point has a snow measure the snow test is dropped and the cold test
-stands in for it. That gives alpine trails a summer season, desert
-trails a winter one that wraps the year end, and mild trails all
-twelve months. It cannot know that some trails are walked in snow by
-choice; the fit against sourced seasons says how often that matters.
+The model cannot know that some trails are walked in snow by choice, or
+that a page names only a thru-hike start window; the leave-one-out fit
+against sourced seasons says how often that matters.
-Commands: fit (tune and record the thresholds), trial (compare the
-climate candidates), propose (the review list), proposals (stage
-accepted estimates for the refresh pipeline) and check (rerun
-every estimate and the fit).
+Commands: fit (fit the model and record the leave-one-out figure), trial
+(compare the climate sources), warm (read every point's climate into the
+cache), propose (the review list), proposals (stage accepted estimates
+for the refresh pipeline) and check (rerun every estimate and the fit).
"""
import sys
@@ -47,10 +41,11 @@ import refresh # noqa: E402
import season # noqa: E402
import season_batches # noqa: E402
import season_climate # noqa: E402
+import season_model # noqa: E402
ROOT = os.path.dirname(HERE)
-RULE_VERSION = 1
+RULE_VERSION = 2
@dataclass(frozen=True)
@@ -61,109 +56,9 @@ class SamplePoint:
km: float = None
-@dataclass(frozen=True)
-class Params:
- snow_cm_max: float
- cold_c_min: float
- heat_c_max: float
-
-
-def _usable(points):
- """The points as a list, or None when any point lacks data. A trail
- with a gap in its climate data is unestimable, never filled in."""
- if not points:
- return None
- got = list(points)
- for point in got:
- if point is None or len(getattr(point, "tmax_c", ()) or ()) != 12:
- return None
- if point.snow_cm is not None and len(point.snow_cm) != 12:
- return None
- return got
-
-
-def _high_low(points):
- """Split points into high ground (at or above the upper quartile of
- the elevations, at least one point) and low ground (at or below
- the median). A single point is both."""
- elevs = sorted(p.elev_m for p in points)
- if len(elevs) == 1:
- return points, points
- upper = statistics.quantiles(elevs, n=4, method="inclusive")[2]
- median = statistics.median(elevs)
- high = [p for p in points if p.elev_m >= upper]
- low = [p for p in points if p.elev_m <= median]
- if not high:
- high = [max(points, key=lambda p: p.elev_m)]
- if not low:
- low = [min(points, key=lambda p: p.elev_m)]
- return high, low
-
-
-def _median_at(points, month, attr):
- values = [getattr(p, attr)[month] for p in points
- if getattr(p, attr) is not None]
- if not values:
- return None
- return round(statistics.median(values), 1)
-
-
-def _medians(points):
- """Per-month medians the rule compares: (high-ground mean daily
- high, high-ground snow depth, low-ground mean daily high), each a
- tuple of twelve rounded to a tenth, snow entries None where no
- high-ground point has a snow measure. None when a point lacks
- data. Precomputing these once per trail is what makes the grid
- search cheap."""
- got = _usable(points)
- if got is None:
- return None
- high, low = _high_low(got)
- return (
- tuple(_median_at(high, m, "tmax_c") for m in range(12)),
- tuple(_median_at(high, m, "snow_cm") for m in range(12)),
- tuple(_median_at(low, m, "tmax_c") for m in range(12)),
- )
-
-
-def _months_from(medians, params):
- high_tmax, high_snow, low_tmax = medians
- out = []
- for m in range(12):
- if high_tmax[m] is None or high_tmax[m] < params.cold_c_min:
- continue
- if high_snow[m] is not None and high_snow[m] > params.snow_cm_max:
- continue
- if low_tmax[m] is None or low_tmax[m] > params.heat_c_max:
- continue
- out.append(m + 1)
- return out
-
-
-def months_in_season(points, params):
- """Sorted month numbers in season, or None. None means either some
- point has no data or no month qualifies; why_not says which. An
- empty list is never returned."""
- medians = _medians(points)
- if medians is None:
- return None
- return _months_from(medians, params) or None
-
-
-def why_not(points, params):
- """Why months_in_season returned None, or "" when it did not."""
- medians = _medians(points)
- if medians is None:
- return "no data for one of the sample points"
- if _months_from(medians, params):
- return ""
- high_tmax, high_snow, low_tmax = medians
- cold_ok = sum(1 for v in high_tmax if v is not None and v >= params.cold_c_min)
- snow_ok = sum(1 for v in high_snow if v is None or v <= params.snow_cm_max)
- heat_ok = sum(1 for v in low_tmax if v is not None and v <= params.heat_c_max)
- return (f"no month passes the cold, snow and heat tests together "
- f"(cold passes in {cold_ok} months, snow in {snow_ok}, "
- f"heat in {heat_ok})")
+Params = season_model.Params
+Reference = season_model.Reference
+months_in_season = season_model.months_in_season
# ---------------------------------------------------------------------------
@@ -422,34 +317,12 @@ def sample_points(root, rec):
# ---------------------------------------------------------------------------
-# Fitting the three thresholds against the sourced seasons. The rule is
-# tuned on the sourced trails whose id hashes even and reported on the
-# ones that hash odd (held out), then the shipped numbers are refit on
-# all of them. Estimates may ship only over the owner's bar, held here
-# in one place.
+# Fitting the model against the sourced seasons, scored leave-one-out
+# (tools/season_model.py). Estimates may ship only over the owner's bar,
+# held here in one place.
BAR = {"within1_min": 0.75, "coverage_min": 0.90}
-DEFAULT_GRID = {
- "snow_cm_max": [float(v) for v in range(0, 65, 5)],
- "cold_c_min": [float(v) for v in range(-5, 26)],
- "heat_c_max": [float(v) for v in range(20, 46)],
-}
-
-SCORES = {"exact": 2, "within1": 1, "worse": 0}
-
-
-def held_out(tid):
- """True when a stable hash of the id is odd. The split never
- changes as records come and go, unlike a random one."""
- return hashlib.sha256(str(tid).encode("utf-8")).digest()[-1] % 2 == 1
-
-
-def _grade_of(estimated, sourced_months):
- if not estimated:
- return "worse"
- return season.grade(estimated, sourced_months)
-
def season_kind(months):
"""The kind of trail a sourced season describes, from the season
@@ -471,71 +344,50 @@ def season_kind(months):
KINDS = ("alpine", "cool-season", "year-round", "other")
-def fit_params(sourced, grid):
- """Grid search the three thresholds for the best mean grade over
- the estimable trails in sourced, a list of (id, normals, months)
- with an optional fourth item ignored here. Grades score exact 2,
- within one month 1, worse 0. Ties go to the first combination in
- grid order, so the same input always gives the same numbers."""
- prepared = []
- for item in sourced:
- medians = _medians(item[1])
- if medians is not None:
- prepared.append((medians, item[2]))
- if not prepared:
- raise ValueError("no estimable trails to fit on")
- best, best_score = None, None
- for snow in grid["snow_cm_max"]:
- for cold in grid["cold_c_min"]:
- for heat in grid["heat_c_max"]:
- params = Params(snow_cm_max=float(snow), cold_c_min=float(cold),
- heat_c_max=float(heat))
- total = sum(SCORES[_grade_of(_months_from(med, params), months)]
- for med, months in prepared)
- score = total / len(prepared)
- if best_score is None or score > best_score:
- best, best_score = params, score
- return best
-
-
-def report(sourced, params):
- """Counts of how the rule does on sourced trails: n, exact,
- within1 (which counts exact too, so within1 + worse + no_data is
- n), worse and no_data, plus the same per region group in by_group.
- A trail whose points lack data is no_data; a trail with data but
- no qualifying month grades worse."""
- counts = {"n": 0, "exact": 0, "within1": 0, "worse": 0, "no_data": 0}
- by_group = {}
- by_kind = {k: dict(counts) for k in KINDS}
- for item in sourced:
- group = item[3] if len(item) > 3 else season_batches.OTHER
- bucket = by_group.setdefault(
- group, {"n": 0, "exact": 0, "within1": 0, "worse": 0, "no_data": 0})
- kind_bucket = by_kind[season_kind(item[2])]
- medians = _medians(item[1])
- for target in (counts, bucket, kind_bucket):
- target["n"] += 1
- if medians is None:
- for target in (counts, bucket, kind_bucket):
- target["no_data"] += 1
+def report(sourced, loo):
+ """How the model did leave-one-out on sourced trails. sourced is
+ (id, medians or None, months, region group); loo maps id to
+ (estimated mask, score) from season_model.fit_model. n counts every
+ sourced trail; no_data those whose points lack climate data;
+ within1 those that match under the owner's measure (a match is
+ within one month at each end, window by window for two windows,
+ ten or more months for a year-round season). classified and
+ jaccard are means over the estimable trails, by kind and by region
+ group too."""
+ def empty():
+ return {"n": 0, "within1": 0, "no_data": 0, "worse": 0,
+ "classified": 0.0, "jaccard": 0.0}
+ total, by_group = empty(), {}
+ by_kind = {k: empty() for k in KINDS}
+ for tid, med, months, group in sourced:
+ buckets = (total, by_group.setdefault(group, empty()),
+ by_kind[season_kind(months)])
+ for b in buckets:
+ b["n"] += 1
+ if med is None or tid not in loo:
+ for b in buckets:
+ b["no_data"] += 1
continue
- grade = _grade_of(_months_from(medians, params), item[2])
- for target in (counts, bucket, kind_bucket):
- if grade == "exact":
- target["exact"] += 1
- target["within1"] += 1
- elif grade == "within1":
- target["within1"] += 1
+ a, c_share, jac = loo[tid][1]
+ for b in buckets:
+ if a:
+ b["within1"] += 1
else:
- target["worse"] += 1
- counts["by_group"] = by_group
- counts["by_kind"] = by_kind
- return counts
+ b["worse"] += 1
+ b["classified"] += c_share
+ b["jaccard"] += jac
+ for b in (total, *by_group.values(), *by_kind.values()):
+ est = b["n"] - b["no_data"]
+ b["classified"] = round(b["classified"] / est, 4) if est else 0.0
+ b["jaccard"] = round(b["jaccard"] / est, 4) if est else 0.0
+ total["by_group"] = by_group
+ total["by_kind"] = by_kind
+ return total
def passes_bar(rep, bar=BAR):
- """The owner's bar: at least 75 percent of held-out sourced trails
- within one month at each end, and at least 90 percent estimable."""
+ """The owner's bar: at least 75 percent of sourced trails matched
+ leave-one-out, and at least 90 percent estimable."""
n = rep.get("n") or 0
if not n:
return False
@@ -553,20 +405,20 @@ def normals_at(points, fetch):
def sourced_trails(root, fetch, log=None):
- """(id, normals, sourced months, region group) for every record
- whose season comes from a page. Fetching goes through the climate
- cache; a network failure aborts the run and a rerun resumes from
- the cache, so no point is ever downloaded twice."""
+ """(id, medians or None, sourced months, region group) for every
+ record whose season comes from a page. Fetching goes through the
+ climate cache; a network failure aborts the run and a rerun
+ resumes from the cache, so no point is ever downloaded twice."""
out = []
for tid, rec in _records(root):
hike = rec.get("hike") or {}
if not hike.get("season") or hike.get("season_basis") == "estimate":
continue
points, kind = sample_points(root, rec)
- normals = normals_at(points, fetch)
+ med = season_model.medians(normals_at(points, fetch))
if log:
log(f"{tid}: {kind}, {len(points)} points")
- out.append((tid, normals, list(hike.get("months") or []),
+ out.append((tid, med, list(hike.get("months") or []),
season_batches.group_of(rec)))
return out
@@ -578,56 +430,85 @@ def _fetch_with_cache(cache_dir):
lat, lon, elev, cache=cache_dir)
+def fit_sourced(sourced):
+ """(params fitted on all, leave-one-out report) for sourced trails;
+ the estimable ones are fitted and the rest counted as no data."""
+ usable = [(t[0], t[1], t[2]) for t in sourced if t[1] is not None]
+ params, loo = season_model.fit_model(usable)
+ return params, report(sourced, loo), loo
+
+
+def confidence_cut(sourced, loo, params):
+ """The (close, decisive) limits of season_model.confidence that
+ make a "high" estimate the most reliable group of at least a
+ quarter of the sourced trails, by a leave-one-out look: for each
+ trail, its neighbours leave it out. Returns the pair and the
+ share of high and low estimates that matched."""
+ refs = [Reference(t[0], t[1], t[2]) for t in sourced if t[1] is not None]
+ rows = []
+ for tid, med, months, _g in sourced:
+ if med is None or tid not in loo:
+ continue
+ near = season_model.nearest(med, refs, params.k, exclude=tid)
+ _mask, scores, fell = season_model.blend(med, near, params)
+ rows.append((near, scores, fell, med, loo[tid][1][0]))
+ best = None
+ for close in (0.08, 0.1, 0.12, 0.15, 0.2, 0.3):
+ for decisive in (0.5, 0.6, 0.7, 0.8, 0.9):
+ hi = [r[4] for r in rows
+ if season_model.confidence(r[3], r[0], r[1], r[2], close, decisive)[0] == "high"]
+ lo = [r[4] for r in rows
+ if season_model.confidence(r[3], r[0], r[1], r[2], close, decisive)[0] == "low"]
+ if len(hi) < len(rows) / 4 or not lo:
+ continue
+ gap = sum(hi) / len(hi) - sum(lo) / len(lo)
+ if best is None or gap > best[0]:
+ best = (gap, close, decisive, sum(hi) / len(hi), sum(lo) / len(lo), len(hi))
+ return best
+
+
def _params_doc(params):
- return {"snow_cm_max": params.snow_cm_max, "cold_c_min": params.cold_c_min,
- "heat_c_max": params.heat_c_max}
+ return params.as_dict()
def cmd_fit(args):
fetch = _fetch_with_cache(args.cache)
sourced = sourced_trails(ROOT, fetch, log=lambda line: print(line, flush=True))
- train = [s for s in sourced if not held_out(s[0])]
- test = [s for s in sourced if held_out(s[0])]
- train_params = fit_params(train, DEFAULT_GRID)
- held = report(test, train_params)
- shipped = fit_params(sourced, DEFAULT_GRID)
- whole = report(sourced, shipped)
+ params, rep, loo = fit_sourced(sourced)
doc = {
"computed": datetime.date.today().isoformat(),
"rule_version": RULE_VERSION,
"dataset": season_climate.SOURCE["name"],
"period": season_climate.SOURCE["period"],
- "params": _params_doc(shipped),
- "held_out_params": _params_doc(train_params),
- "all": whole,
- "held_out": held,
+ "params": _params_doc(params),
+ "loo": rep,
"bar": BAR,
- "passes": passes_bar(held),
+ "passes": passes_bar(rep),
+ "confidence": None,
}
+ best = confidence_cut(sourced, loo, params)
+ if best:
+ doc["confidence"] = {"close": best[1], "decisive": best[2],
+ "high_matched": round(best[3], 3),
+ "low_matched": round(best[4], 3), "high_n": best[5]}
path = os.path.join(ROOT, "tools", "season_fit.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(doc, f, indent=1, sort_keys=True)
f.write("\n")
- print(f"sourced {len(sourced)} (train {len(train)}, held out {len(test)})")
- print(f"held out: within1 {held['within1']}/{held['n']}, "
- f"exact {held['exact']}, worse {held['worse']}, "
- f"no data {held['no_data']}, passes {doc['passes']}")
- print(f"all: within1 {whole['within1']}/{whole['n']}, "
- f"exact {whole['exact']}, worse {whole['worse']}, "
- f"no data {whole['no_data']}")
- print(f"shipped params {_params_doc(shipped)} "
- f"(held-out fit {_params_doc(train_params)})")
+ print(f"sourced {rep['n']}: leave-one-out matched {rep['within1']}/{rep['n']}, "
+ f"classified {rep['classified']}, jaccard {rep['jaccard']}, "
+ f"no data {rep['no_data']}, passes {doc['passes']}")
+ print(f"params {_params_doc(params)}; confidence {doc['confidence']}")
print(f"wrote {path}")
return 0
-
# ---------------------------------------------------------------------------
# Estimates for trails with no sourced season, the review list a person
# reads, the staged proposals that write accepted estimates through the
# refresh pipeline, and the check that reruns both.
-COARSE_PARAMS = Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
+COARSE_PARAMS = Params(cold_c_min=5.0, heat_c_max=32.0)
# The trial's twelve, by rule: akshayuk-pass is the far north trail;
# great-divide-trail and west-coast-trail are in Canada; john-muir,
@@ -643,35 +524,7 @@ TRIAL_TRAILS = ["akshayuk-pass", "great-divide-trail", "west-coast-trail",
FLAG_ORDER = ("no-track", "place-centre", "no-data", "no-month",
"desert", "coast", "far-north", "few-points")
-_CENTRES = {}
-
-
-def _centre(points):
- if not points:
- return None
- return (sum(p.lat for p in points) / len(points),
- sum(p.lon for p in points) / len(points))
-
-
-def _sourced_centres(root):
- """(id, centre lat, centre lon, season phrase) for sourced trails,
- computed once per root per run: sampling every track again for
- each estimate would make the review list take minutes."""
- if root not in _CENTRES:
- out = []
- for tid, rec in _records(root):
- hike = rec.get("hike") or {}
- if not hike.get("season") or hike.get("season_basis") == "estimate":
- continue
- points, _kind = sample_points(root, rec)
- centre = _centre(points)
- if centre:
- out.append((tid, centre[0], centre[1], str(hike.get("season"))))
- _CENTRES[root] = out
- return _CENTRES[root]
-
-
-def _flags(points, kind, normals, medians, params):
+def _flags(points, kind, normals, med, params, fell_back=False):
found = set()
if kind != "track":
found.add("no-track")
@@ -681,49 +534,70 @@ def _flags(points, kind, normals, medians, params):
found.add("few-points")
if points and max(p.lat for p in points) > 60:
found.add("far-north")
- if medians is None:
+ if med is None:
found.add("no-data")
else:
elevs = [n.elev_m for n in normals if n is not None]
if elevs and max(elevs) <= 200:
found.add("coast")
- high_tmax, high_snow, low_tmax = medians
+ high, low = med
for m in range(12):
- cold_ok = high_tmax[m] is not None and high_tmax[m] >= params.cold_c_min
- snow_ok = high_snow[m] is None or high_snow[m] <= params.snow_cm_max
- heat_ok = low_tmax[m] is not None and low_tmax[m] <= params.heat_c_max
- if cold_ok and snow_ok and not heat_ok:
+ if high[m] >= params.cold_c_min and low[m] > params.heat_c_max:
found.add("desert")
break
- if not _months_from(medians, params):
+ if fell_back:
found.add("no-month")
return [name for name in FLAG_ORDER if name in found]
-def estimate(root, rec, params, fetch=season_climate.fetch_normals):
+_REFS = {}
+
+
+def references(root, fetch):
+ """The sourced trails as comparable-trail references, read once per
+ root per run (sampling and reading every sourced trail again for
+ each estimate would take minutes)."""
+ if root not in _REFS:
+ _REFS[root] = [Reference(t[0], t[1], t[2])
+ for t in sourced_trails(root, fetch) if t[1] is not None]
+ return _REFS[root]
+
+
+def estimate(root, rec, params, fetch=season_climate.fetch_normals, refs=None):
"""One trail's estimated season and how much to trust it: months
(None when unestimable, with the reason), the phrase and method
sentence an accepted estimate would carry, how its points were got,
- flags for hand review, and the nearest sourced trail to compare
- it with. Fetch errors propagate; nothing here touches the network
- except through fetch."""
+ flags for hand review, the comparable trails the estimate drew on
+ (nearest first, as (id, distance, sourced phrase)) and a confidence
+ ("high" or "low") with its reason. A trail's own sourced season is
+ never one of its comparable trails. refs defaults to the sourced
+ trails read through fetch. Fetch errors propagate; nothing here
+ touches the network except through fetch."""
points, kind = sample_points(root, rec)
normals = normals_at(points, fetch)
- medians = _medians(normals)
- months = _months_from(medians, params) if medians is not None else None
- months = months or None
- comparable, comparable_phrase = "", ""
- centre = _centre(points)
- if centre:
- best = None
- for tid, clat, clon, phrase in _sourced_centres(root):
- if tid == rec.get("id"):
- continue
- dist = season_climate.haversine_km(centre[0], centre[1], clat, clon)
- if best is None or dist < best[0]:
- best = (dist, tid, phrase)
- if best:
- comparable, comparable_phrase = best[1], best[2]
+ med = season_model.medians(normals)
+ if refs is None:
+ refs = references(root, fetch)
+ months, near, fell_back, conf, why = None, [], False, "low", ""
+ if med is not None:
+ near = season_model.nearest(med, refs, params.k, exclude=rec.get("id"))
+ mask, scores, fell_back = season_model.blend(med, near, params)
+ months = season_model.to_months(mask)
+ limits = {"close": 0.12, "decisive": 0.7}
+ try:
+ limits = (load_fit(root).get("confidence") or limits)
+ except OSError:
+ pass
+ conf, why = season_model.confidence(
+ med, near, scores, fell_back, limits["close"], limits["decisive"])
+ if kind != "track" or len(points) < 3:
+ conf, why = "low", "the location is a fallback (" + (
+ "the trail's ends" if kind == "ends" else "the region's centre") + ")"
+ else:
+ why = "no data for one of the sample points"
+ phrases = _phrases(root)
+ comparable = [(r.id, round(d, 3), phrases.get(r.id, ""), season_model.to_months(r.mask))
+ for d, r in near]
return {
"months": months,
"phrase": season.phrase_for(months) if months else "",
@@ -731,25 +605,39 @@ def estimate(root, rec, params, fetch=season_climate.fetch_normals):
season_climate.SOURCE["name"], season_climate.SOURCE["period"],
len(points), kind, RULE_VERSION),
"kind": kind,
- "flags": _flags(points, kind, normals, medians, params),
- "comparable": comparable,
- "comparable_phrase": comparable_phrase,
- "reason": "" if months else why_not(normals, params),
+ "flags": _flags(points, kind, normals, med, params, fell_back),
+ "comparable": comparable[0][0] if comparable else "",
+ "comparable_phrase": comparable[0][2] if comparable else "",
+ "neighbours": comparable,
+ "confidence": conf,
+ "confidence_reason": why,
+ "reason": "" if months else why,
"points": points,
"normals": normals,
}
+def _phrases(root):
+ if root not in _PHRASES:
+ out = {}
+ for tid, rec in _records(root):
+ hike = rec.get("hike") or {}
+ if hike.get("season") and hike.get("season_basis") != "estimate":
+ out[tid] = str(hike.get("season"))
+ _PHRASES[root] = out
+ return _PHRASES[root]
+
+
+_PHRASES = {}
+
+
def load_fit(root):
with open(os.path.join(root, "tools", "season_fit.json"), encoding="utf-8") as f:
return json.load(f)
def load_params(root):
- doc = load_fit(root)["params"]
- return Params(snow_cm_max=float(doc["snow_cm_max"]),
- cold_c_min=float(doc["cold_c_min"]),
- heat_c_max=float(doc["heat_c_max"]))
+ return Params.from_dict(load_fit(root)["params"])
def _with_cache(fetch_fn, cache_dir):
@@ -769,7 +657,7 @@ def propose(root, params, fetch, given_dir=None):
for tid, rec in _records(root):
if (rec.get("hike") or {}).get("season"):
continue
- est = estimate(root, rec, params, fetch)
+ est = estimate(root, dict(rec, id=tid), params, fetch)
rows.append([tid, " ".join(str(m) for m in est["months"] or []),
est["phrase"], est["kind"], ";".join(est["flags"]),
est["comparable"], est["comparable_phrase"]])
@@ -883,10 +771,10 @@ def proposals(root, reviewed_csv, given_dir=None):
def check(root, fetch):
- """Rerun every estimated season and the held-out fit. Returns
+ """Rerun every estimated season and the leave-one-out fit. Returns
(ok, lines): not ok when an estimate would now come out different,
- when the held-out within-one-month share has fallen by more than
- 0.02 from season_fit.json, or when that file does not pass."""
+ when the leave-one-out match share has fallen by more than 0.02
+ from season_fit.json, or when that file does not pass."""
try:
fit = load_fit(root)
except OSError:
@@ -894,12 +782,13 @@ def check(root, fetch):
"python3 tools/estimate_season.py fit"]
params = load_params(root)
ok, lines, checked = True, [], 0
+ refs = references(root, fetch)
for tid, rec in _records(root):
hike = rec.get("hike") or {}
if hike.get("season_basis") != "estimate":
continue
checked += 1
- est = estimate(root, rec, params, fetch)
+ est = estimate(root, dict(rec, id=tid), params, fetch, refs)
old = sorted(int(m) for m in hike.get("months") or [])
new = sorted(est["months"] or [])
if new != old:
@@ -907,21 +796,16 @@ def check(root, fetch):
detail = est["phrase"] or est["reason"]
lines.append(f"{tid}: estimate was {old}, now {new} ({detail})")
sourced = sourced_trails(root, fetch)
- train = [s for s in sourced if not held_out(s[0])]
- test = [s for s in sourced if held_out(s[0])]
- if train and test:
- try:
- now = report(test, fit_params(train, DEFAULT_GRID))
- except ValueError:
- now = None
- stored = fit.get("held_out") or {}
- if now and stored.get("n"):
+ if any(s[1] is not None for s in sourced):
+ _p, now, _loo = fit_sourced(sourced)
+ stored = fit.get("loo") or {}
+ if stored.get("n"):
was_share = stored["within1"] / stored["n"]
now_share = now["within1"] / now["n"] if now["n"] else 0.0
if was_share - now_share > 0.02:
ok = False
lines.append(
- f"fit got worse: held-out within one month "
+ f"fit got worse: leave-one-out matches "
f"{now['within1']}/{now['n']} ({now_share:.2f}), "
f"was {stored['within1']}/{stored['n']} ({was_share:.2f})")
if not fit.get("passes"):
diff --git a/tools/season_fit.json b/tools/season_fit.json
index 7162650..919dbc6 100644
--- a/tools/season_fit.json
+++ b/tools/season_fit.json
@@ -1,225 +1,142 @@
{
- "all": {
+ "bar": {
+ "coverage_min": 0.9,
+ "within1_min": 0.75
+ },
+ "computed": "2026-11-20",
+ "confidence": {
+ "close": 0.3,
+ "decisive": 0.6,
+ "high_matched": 0.868,
+ "high_n": 38,
+ "low_matched": 0.609
+ },
+ "dataset": "CHELSA V2.1 climatologies, with ETOPO 2022 elevation",
+ "loo": {
"by_group": {
"Canada east and north": {
- "exact": 0,
- "n": 8,
+ "classified": 0.7685,
+ "jaccard": 0.5546,
+ "n": 9,
"no_data": 0,
"within1": 5,
- "worse": 3
+ "worse": 4
},
"Canada west": {
- "exact": 1,
- "n": 11,
+ "classified": 0.8512,
+ "jaccard": 0.6607,
+ "n": 14,
"no_data": 0,
- "within1": 7,
- "worse": 4
+ "within1": 12,
+ "worse": 2
},
"Rockies": {
- "exact": 2,
- "n": 22,
+ "classified": 0.8913,
+ "jaccard": 0.6832,
+ "n": 23,
"no_data": 0,
- "within1": 15,
- "worse": 7
+ "within1": 20,
+ "worse": 3
},
"interior west": {
- "exact": 3,
- "n": 10,
+ "classified": 0.7153,
+ "jaccard": 0.3855,
+ "n": 12,
"no_data": 0,
"within1": 6,
- "worse": 4
+ "worse": 6
},
"northeast": {
- "exact": 0,
- "n": 6,
+ "classified": 0.7556,
+ "jaccard": 0.6198,
+ "n": 15,
"no_data": 0,
- "within1": 3,
+ "within1": 12,
"worse": 3
},
"plains and midwest": {
- "exact": 1,
- "n": 3,
+ "classified": 0.6458,
+ "jaccard": 0.4722,
+ "n": 8,
"no_data": 0,
- "within1": 1,
- "worse": 2
+ "within1": 3,
+ "worse": 5
},
"southeast": {
- "exact": 3,
- "n": 10,
- "no_data": 0,
- "within1": 4,
- "worse": 6
- },
- "southwest": {
- "exact": 3,
- "n": 17,
+ "classified": 0.6667,
+ "jaccard": 0.4973,
+ "n": 13,
"no_data": 0,
"within1": 8,
- "worse": 9
+ "worse": 5
},
- "west coast": {
- "exact": 0,
+ "southwest": {
+ "classified": 0.6932,
+ "jaccard": 0.4759,
"n": 22,
"no_data": 0,
- "within1": 12,
- "worse": 10
+ "within1": 11,
+ "worse": 11
+ },
+ "west coast": {
+ "classified": 0.7995,
+ "jaccard": 0.5687,
+ "n": 32,
+ "no_data": 0,
+ "within1": 23,
+ "worse": 9
}
},
"by_kind": {
"alpine": {
- "exact": 6,
- "n": 63,
+ "classified": 0.8689,
+ "jaccard": 0.6547,
+ "n": 82,
"no_data": 0,
- "within1": 44,
- "worse": 19
+ "within1": 67,
+ "worse": 15
},
"cool-season": {
- "exact": 5,
- "n": 30,
+ "classified": 0.7292,
+ "jaccard": 0.4613,
+ "n": 40,
"no_data": 0,
- "within1": 12,
+ "within1": 22,
"worse": 18
},
"other": {
- "exact": 2,
- "n": 8,
+ "classified": 0.5926,
+ "jaccard": 0.4345,
+ "n": 18,
"no_data": 0,
- "within1": 5,
- "worse": 3
+ "within1": 11,
+ "worse": 7
},
"year-round": {
- "exact": 0,
+ "classified": 0.3542,
+ "jaccard": 0.3542,
"n": 8,
"no_data": 0,
"within1": 0,
"worse": 8
}
},
- "exact": 13,
- "n": 109,
+ "classified": 0.7697,
+ "jaccard": 0.5594,
+ "n": 148,
"no_data": 0,
- "within1": 61,
+ "within1": 100,
"worse": 48
},
- "bar": {
- "coverage_min": 0.9,
- "within1_min": 0.75
- },
- "computed": "2026-11-20",
- "dataset": "CHELSA V2.1 climatologies, with ETOPO 2022 elevation",
- "held_out": {
- "by_group": {
- "Canada east and north": {
- "exact": 0,
- "n": 2,
- "no_data": 0,
- "within1": 0,
- "worse": 2
- },
- "Canada west": {
- "exact": 0,
- "n": 6,
- "no_data": 0,
- "within1": 1,
- "worse": 5
- },
- "Rockies": {
- "exact": 1,
- "n": 9,
- "no_data": 0,
- "within1": 5,
- "worse": 4
- },
- "interior west": {
- "exact": 3,
- "n": 3,
- "no_data": 0,
- "within1": 3,
- "worse": 0
- },
- "northeast": {
- "exact": 0,
- "n": 2,
- "no_data": 0,
- "within1": 0,
- "worse": 2
- },
- "plains and midwest": {
- "exact": 0,
- "n": 1,
- "no_data": 0,
- "within1": 0,
- "worse": 1
- },
- "southeast": {
- "exact": 0,
- "n": 4,
- "no_data": 0,
- "within1": 0,
- "worse": 4
- },
- "southwest": {
- "exact": 0,
- "n": 9,
- "no_data": 0,
- "within1": 2,
- "worse": 7
- },
- "west coast": {
- "exact": 0,
- "n": 12,
- "no_data": 0,
- "within1": 5,
- "worse": 7
- }
- },
- "by_kind": {
- "alpine": {
- "exact": 4,
- "n": 24,
- "no_data": 0,
- "within1": 12,
- "worse": 12
- },
- "cool-season": {
- "exact": 0,
- "n": 15,
- "no_data": 0,
- "within1": 2,
- "worse": 13
- },
- "other": {
- "exact": 0,
- "n": 4,
- "no_data": 0,
- "within1": 2,
- "worse": 2
- },
- "year-round": {
- "exact": 0,
- "n": 5,
- "no_data": 0,
- "within1": 0,
- "worse": 5
- }
- },
- "exact": 4,
- "n": 48,
- "no_data": 0,
- "within1": 16,
- "worse": 32
- },
- "held_out_params": {
- "cold_c_min": 14.0,
- "heat_c_max": 31.0,
- "snow_cm_max": 0.0
- },
"params": {
"cold_c_min": 12.0,
- "heat_c_max": 28.0,
- "snow_cm_max": 0.0
+ "cut": 0.65,
+ "heat_c_max": 25.0,
+ "k": 20,
+ "mix": 0.7,
+ "power": 1
},
"passes": false,
"period": "1981-2010",
- "rule_version": 1
+ "rule_version": 2
}
diff --git a/tools/season_model.py b/tools/season_model.py
new file mode 100644
index 0000000..25e13cc
--- /dev/null
+++ b/tools/season_model.py
@@ -0,0 +1,435 @@
+"""The season estimator: a pure function over monthly climate normals.
+
+Python 3 standard library only, no network. tools/estimate_season.py
+finds a trail's sample points and their normals (tools/season_climate.py
+downloads them, cached outside the repository) and hands them to this
+module. See docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md.
+
+The method, in three parts:
+
+1. Thresholds. A month is in season when the high ground (points at or
+ above the upper quartile of the track's elevations) has a median mean
+ daily high of at least cold_c_min, and the low ground (points at or
+ below the median elevation) has one of at most heat_c_max.
+2. Comparable trails. Each trail is described by twelve monthly
+ high-ground highs and twelve low-ground highs. The k most similar
+ sourced trails (a season some page states) vote, each weighted by
+ 1 / (distance + 0.05) ** power, on every month.
+3. The blend. Each month scores mix * (share of the comparable trails'
+ weight that has the month in season) + (1 - mix) * (1 if the
+ thresholds pass it else 0), and the month is in season when the score
+ reaches cut. The thresholds propose and the comparable trails confirm
+ or add, so a desert trail inherits a cool-season pattern and an arctic
+ trail a short summer from trails like it.
+
+A month set is never empty: when no month reaches the cut the three
+highest scoring months are used and the result says so.
+
+The measure (match, score) is the owner's: a trail's estimated season
+matches a sourced one when each end is within one month, a two-window
+season is compared window by window, and a year-round season matches
+only an estimate of ten or more months. fit_model scores the method by
+leave-one-out over the sourced trails: every trail is predicted by a
+model that never saw it, including the choice of the numbers above.
+"""
+import sys
+
+sys.dont_write_bytecode = True
+
+import math
+import statistics
+
+import season
+
+EPS = 0.05
+FALLBACK_MONTHS = 3
+GRID_COLD = list(range(-10, 26))
+GRID_HEAT = list(range(15, 46))
+GRID_K = (3, 5, 8, 12, 20)
+GRID_POWER = (1, 2)
+GRID_CUT = (0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7)
+GRID_MIX = (0.5, 0.6, 0.7, 0.8, 0.9)
+GRID_BLEND_CUT = (0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8)
+FULL = 0xFFF
+
+
+class Params:
+ """cold_c_min, heat_c_max (the thresholds), k and power (the comparable
+ trails), mix and cut (the blend)."""
+
+ __slots__ = ("cold_c_min", "heat_c_max", "k", "power", "mix", "cut")
+
+ def __init__(self, cold_c_min, heat_c_max, k=20, power=1, mix=0.7, cut=0.65):
+ self.cold_c_min = float(cold_c_min)
+ self.heat_c_max = float(heat_c_max)
+ self.k = int(k)
+ self.power = int(power)
+ self.mix = float(mix)
+ self.cut = float(cut)
+
+ def as_dict(self):
+ return {name: getattr(self, name) for name in self.__slots__}
+
+ @classmethod
+ def from_dict(cls, doc):
+ return cls(**{name: doc[name] for name in cls.__slots__})
+
+ def __eq__(self, other):
+ return isinstance(other, Params) and self.as_dict() == other.as_dict()
+
+ def __repr__(self):
+ return "Params(%s)" % ", ".join(f"{k}={v!r}" for k, v in self.as_dict().items())
+
+
+# ---------------------------------------------------------------------------
+# Months as 12-bit masks (bit 0 is January) inside; lists of 1..12 outside.
+
+def to_mask(months):
+ mask = 0
+ for m in months:
+ mask |= 1 << (int(m) - 1)
+ return mask
+
+
+def to_months(mask):
+ return [m + 1 for m in range(12) if mask >> m & 1]
+
+
+def _runs(mask):
+ """Circular runs of months as (first, last) pairs; December to
+ January joins into one run."""
+ runs = []
+ for m in to_months(mask):
+ if runs and m == runs[-1][1] + 1:
+ runs[-1][1] = m
+ else:
+ runs.append([m, m])
+ if len(runs) > 1 and runs[0][0] == 1 and runs[-1][1] == 12:
+ runs[0][0] = runs.pop()[0]
+ return [tuple(r) for r in runs]
+
+
+def _near(a, b):
+ d = abs(a - b)
+ return min(d, 12 - d) <= 1
+
+
+def match(estimated, sourced):
+ """The owner's measure, on month lists or masks. A sourced season of
+ eleven or twelve months matches an estimate of ten or more. A sourced
+ season in two or more windows matches when every window has an
+ estimated window within a month at both ends and the estimate has no
+ window of its own left over. Any other sourced season matches when
+ the estimate's span (season.span) is within a month at each end."""
+ est = estimated if isinstance(estimated, int) else to_mask(estimated)
+ src = sourced if isinstance(sourced, int) else to_mask(sourced)
+ if not est or not src:
+ return False
+ if bin(src).count("1") >= 11:
+ return bin(est).count("1") >= 10
+ src_runs = _runs(src)
+ if len(src_runs) >= 2:
+ est_runs = _runs(est)
+ return (all(any(_near(a, c) and _near(b, d) for c, d in est_runs)
+ for a, b in src_runs)
+ and all(any(_near(a, c) and _near(b, d) for c, d in src_runs)
+ for a, b in est_runs))
+ return season.grade(to_months(est), to_months(src)) != "worse"
+
+
+def score(estimated, sourced):
+ """(match 1 or 0, share of the twelve months classified correctly,
+ Jaccard overlap of the month sets)."""
+ est = estimated if isinstance(estimated, int) else to_mask(estimated)
+ src = sourced if isinstance(sourced, int) else to_mask(sourced)
+ union = bin(est | src).count("1")
+ return (1.0 if match(est, src) else 0.0,
+ bin(~(est ^ src) & FULL).count("1") / 12,
+ bin(est & src).count("1") / union if union else 0.0)
+
+
+# ---------------------------------------------------------------------------
+# Climate summary of a trail.
+
+def usable(points):
+ """The points as a list, or None when any point lacks data. A trail
+ with a gap in its climate data is unestimable, never filled in."""
+ if not points:
+ return None
+ got = list(points)
+ for point in got:
+ if point is None or len(getattr(point, "tmax_c", ()) or ()) != 12:
+ return None
+ return got
+
+
+def high_low(points):
+ """Split points into high ground (at or above the upper quartile of
+ the elevations, at least one point) and low ground (at or below
+ the median). A single point is both."""
+ elevs = sorted(p.elev_m for p in points)
+ if len(elevs) == 1:
+ return points, points
+ upper = statistics.quantiles(elevs, n=4, method="inclusive")[2]
+ median = statistics.median(elevs)
+ high = [p for p in points if p.elev_m >= upper]
+ low = [p for p in points if p.elev_m <= median]
+ if not high:
+ high = [max(points, key=lambda p: p.elev_m)]
+ if not low:
+ low = [min(points, key=lambda p: p.elev_m)]
+ return high, low
+
+
+def medians(points):
+ """(high-ground, low-ground): each twelve median mean daily highs
+ rounded to a tenth. None when a point lacks data."""
+ got = usable(points)
+ if got is None:
+ return None
+ high, low = high_low(got)
+
+ def med(group):
+ return tuple(round(statistics.median(p.tmax_c[m] for p in group), 1)
+ for m in range(12))
+ return med(high), med(low)
+
+
+def threshold_mask(med, params):
+ high, low = med
+ mask = 0
+ for m in range(12):
+ if high[m] >= params.cold_c_min and low[m] <= params.heat_c_max:
+ mask |= 1 << m
+ return mask
+
+
+def _margins(med, params):
+ high, low = med
+ return [min(high[m] - params.cold_c_min, params.heat_c_max - low[m])
+ for m in range(12)]
+
+
+def _top(scores, n=FALLBACK_MONTHS):
+ order = sorted(range(12), key=lambda m: (-scores[m], m))[:n]
+ return sum(1 << m for m in order)
+
+
+# ---------------------------------------------------------------------------
+# Comparable trails.
+
+class Reference:
+ """A sourced trail the estimate may compare with."""
+
+ __slots__ = ("id", "med", "mask")
+
+ def __init__(self, tid, med, months):
+ self.id = tid
+ self.med = med
+ self.mask = to_mask(months)
+
+
+def distance(a, b):
+ """Root mean square difference, in tens of degrees, over the
+ twenty-four high-ground and low-ground monthly highs."""
+ total = 0.0
+ for ga, gb in zip(a, b):
+ for m in range(12):
+ total += ((ga[m] - gb[m]) / 10) ** 2
+ return math.sqrt(total / 24)
+
+
+def nearest(med, refs, k, exclude=None):
+ """The k closest references as (distance, reference), nearest first,
+ leaving out the reference whose id is exclude."""
+ found = sorted(((distance(med, r.med), r.id, r) for r in refs
+ if r.id != exclude))
+ return [(d, r) for d, _id, r in found[:k]]
+
+
+def vote(near, power):
+ """Weighted share of the comparable trails that have each month."""
+ total = 0.0
+ acc = [0.0] * 12
+ for d, r in near:
+ w = 1.0 / (d + EPS) ** power
+ total += w
+ for m in range(12):
+ if r.mask >> m & 1:
+ acc[m] += w
+ return [a / total for a in acc] if total else [0.0] * 12
+
+
+def blend(med, near, params):
+ """(mask, scores, fell_back). Without comparable trails the
+ thresholds stand alone."""
+ thr = threshold_mask(med, params)
+ if not near:
+ if thr:
+ return thr, [float(thr >> m & 1) for m in range(12)], False
+ margins = _margins(med, params)
+ return _top(margins), margins, True
+ votes = vote(near, params.power)
+ scores = [params.mix * votes[m] + (1 - params.mix) * (thr >> m & 1)
+ for m in range(12)]
+ mask = sum(1 << m for m in range(12) if scores[m] >= params.cut)
+ if mask:
+ return mask, scores, False
+ return _top(scores), scores, True
+
+
+def months_in_season(points, params, refs=(), exclude=None):
+ """Sorted month numbers in season, or None when some point has no
+ data. Never an empty list."""
+ med = medians(points)
+ if med is None:
+ return None
+ near = nearest(med, list(refs), params.k, exclude) if refs else []
+ return to_months(blend(med, near, params)[0])
+
+
+def confidence(med, near, scores, fell_back, close=0.12, decisive=0.7):
+ """("high" or "low", reason). High when the comparable trails are
+ close (mean distance at most `close`) and agree (at least `decisive`
+ of the twelve months have a weighted vote of 0.2 or less or 0.8 or
+ more) and the empty-set fallback was not needed. These two numbers
+ were chosen from the leave-one-out predictions: see
+ tools/season_fit.json, confidence."""
+ if not near:
+ return "low", "no comparable trails"
+ mean_d = sum(d for d, _ in near) / len(near)
+ shares = vote(near, 1)
+ sure = sum(1 for s in shares if s <= 0.2 or s >= 0.8) / 12
+ if fell_back:
+ return "low", "no month reached the cut"
+ if mean_d > close:
+ return "low", f"comparable trails are far (mean distance {mean_d:.2f})"
+ if sure < decisive:
+ return "low", f"comparable trails disagree ({sure:.0%} of months settled)"
+ return "high", f"comparable trails are close ({mean_d:.2f}) and agree"
+
+
+# ---------------------------------------------------------------------------
+# Fitting by leave-one-out.
+
+def _obj(s):
+ return s[0] + 1e-3 * s[2]
+
+
+def fit_model(trails, params_grid=None):
+ """Fit the method on sourced trails and score it leave-one-out.
+
+ trails: list of (id, medians, sourced months). Returns (params,
+ loo) where params is fitted on all of them and loo maps id to
+ (estimated mask, score) from a model that never saw that trail.
+ Each of the three parts is chosen by the same objective (matches,
+ then Jaccard overlap): thresholds over the cold and heat grids,
+ comparable trails over k, power and a month cut (nested: when
+ trail i is held out, every other trail's score is recomputed
+ without i among its neighbours), and the blend over mix and cut
+ from the other trails' leave-one-out predictions."""
+ ids = [t[0] for t in trails]
+ index = {tid: n for n, tid in enumerate(ids)}
+ meds = [t[1] for t in trails]
+ truth = [to_mask(t[2]) for t in trails]
+ n = len(trails)
+
+ # -- thresholds
+ combos = [(c, h) for c in GRID_COLD for h in GRID_HEAT]
+ thr_masks, thr_obj = [], []
+ for c, h in combos:
+ p = Params(c, h)
+ row = []
+ for j in range(n):
+ mk = threshold_mask(meds[j], p) or _top(_margins(meds[j], p))
+ row.append(mk)
+ thr_masks.append(row)
+ thr_obj.append([_obj(score(row[j], truth[j])) for j in range(n)])
+ totals = [sum(row) for row in thr_obj]
+ full_t = max(range(len(combos)), key=lambda ci: totals[ci])
+ thr_loo = []
+ for i in range(n):
+ ci = max(range(len(combos)), key=lambda ci: totals[ci] - thr_obj[ci][i])
+ thr_loo.append(thr_masks[ci][i])
+
+ # -- comparable trails
+ refs = [Reference(ids[j], meds[j], t[2]) for j, t in enumerate(trails)]
+ order = [sorted(((distance(meds[j], meds[r]), r) for r in range(n) if r != j))
+ for j in range(n)]
+ pos = [{r: p for p, (_d, r) in enumerate(order[j])} for j in range(n)]
+ bits = [[(truth[r] >> m) & 1 for m in range(12)] for r in range(n)]
+
+ def shares(j, k, power, skip=None):
+ total, acc, got = 0.0, [0.0] * 12, 0
+ for d, r in order[j]:
+ if r == skip:
+ continue
+ w = 1.0 / (d + EPS) ** power
+ total += w
+ for m in range(12):
+ if bits[r][m]:
+ acc[m] += w
+ got += 1
+ if got == k:
+ break
+ return [a / total for a in acc] if total else [0.0] * 12
+
+ def mask_of(v, cut):
+ mk = sum(1 << m for m in range(12) if v[m] >= cut)
+ return mk or _top(v)
+
+ knn = [(k, p, c) for k in GRID_K for p in GRID_POWER for c in GRID_CUT]
+ base = {}
+ for k in GRID_K:
+ for p in GRID_POWER:
+ for j in range(n):
+ v = shares(j, k, p)
+ base[k, p, j] = [_obj(score(mask_of(v, c), truth[j])) for c in GRID_CUT]
+ knn_totals = {}
+ for k in GRID_K:
+ for p in GRID_POWER:
+ for ci, c in enumerate(GRID_CUT):
+ knn_totals[k, p, ci] = sum(base[k, p, j][ci] for j in range(n))
+ full_k = max(knn_totals, key=lambda key: knn_totals[key])
+ knn_choice = []
+ for i in range(n):
+ best, best_total = None, None
+ for k in GRID_K:
+ for p in GRID_POWER:
+ row = [knn_totals[k, p, ci] - base[k, p, i][ci]
+ for ci in range(len(GRID_CUT))]
+ # trails that had i among their k neighbours are rescored without it
+ for j in range(n):
+ if j != i and pos[j][i] < k:
+ v = shares(j, k, p, skip=i)
+ for ci, c in enumerate(GRID_CUT):
+ row[ci] += (_obj(score(mask_of(v, c), truth[j]))
+ - base[k, p, j][ci])
+ for ci in range(len(GRID_CUT)):
+ if best_total is None or row[ci] > best_total:
+ best, best_total = (k, p, ci), row[ci]
+ knn_choice.append(best)
+ knn_votes = [shares(i, knn_choice[i][0], knn_choice[i][1]) for i in range(n)]
+
+ # -- the blend
+ blends = [(mix, cut) for mix in GRID_MIX for cut in GRID_BLEND_CUT]
+ b_masks, b_obj = [], []
+ for mix, cut in blends:
+ row = []
+ for j in range(n):
+ v = [mix * knn_votes[j][m] + (1 - mix) * (thr_loo[j] >> m & 1)
+ for m in range(12)]
+ row.append(mask_of(v, cut))
+ b_masks.append(row)
+ b_obj.append([_obj(score(row[j], truth[j])) for j in range(n)])
+ b_totals = [sum(row) for row in b_obj]
+ full_b = max(range(len(blends)), key=lambda bi: b_totals[bi])
+ loo = {}
+ for i in range(n):
+ bi = max(range(len(blends)), key=lambda bi: b_totals[bi] - b_obj[bi][i])
+ mk = b_masks[bi][i]
+ loo[ids[i]] = (mk, score(mk, truth[i]))
+ cold, heat = combos[full_t]
+ k, p, _ci = full_k
+ mix, cut = blends[full_b]
+ return Params(cold, heat, k, p, mix, cut), loo
diff --git a/tools/tests/test_estimate_season.py b/tools/tests/test_estimate_season.py
index 750c04d..dcadec9 100644
--- a/tools/tests/test_estimate_season.py
+++ b/tools/tests/test_estimate_season.py
@@ -19,7 +19,7 @@ import estimate_season as E # noqa: E402
import test_refresh as TR # noqa: E402
import season_climate as C # noqa: E402
-PARAMS = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
+PARAMS = E.Params(cold_c_min=5.0, heat_c_max=32.0)
def normals(elev, tmax, snow=None):
@@ -30,61 +30,44 @@ def normals(elev, tmax, snow=None):
class RuleTest(unittest.TestCase):
+ """The thresholds on their own: with no sourced trails to compare
+ with, the model is the cold and heat limits."""
+
def test_a_cold_high_point_closes_the_winter(self):
- point = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1],
- snow=[0] * 12)
+ point = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1])
self.assertEqual(E.months_in_season([point], PARAMS),
[4, 5, 6, 7, 8, 9, 10])
- def test_snow_over_the_limit_closes_a_month(self):
- point = normals(3000, [10] * 12,
- snow=[50, 50, 50, 50, 50, 50, 0, 0, 0, 0, 0, 0])
- self.assertEqual(E.months_in_season([point], PARAMS),
- [7, 8, 9, 10, 11, 12])
-
def test_heat_at_the_low_ground_closes_a_summer_month(self):
- desert = normals(400, [19, 22, 26, 31, 36, 42, 44, 43, 39, 32, 24, 19],
- snow=[0] * 12)
- got = E.months_in_season([desert], PARAMS)
- self.assertEqual(set(got), {10, 11, 12, 1, 2, 3, 4})
- self.assertEqual(got, [1, 2, 3, 4, 10, 11, 12])
+ desert = normals(400, [19, 22, 26, 31, 36, 42, 44, 43, 39, 32, 24, 19])
+ self.assertEqual(E.months_in_season([desert], PARAMS),
+ [1, 2, 3, 4, 10, 11, 12])
def test_high_ground_is_the_upper_quartile_of_points(self):
- low = [normals(e, [15] * 12, snow=[0] * 12) for e in (100, 200, 300)]
- top_snow = [0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0]
- high = normals(400, [15] * 12, snow=top_snow)
+ low = [normals(e, [15] * 12) for e in (100, 200, 300)]
+ high = normals(400, [15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15])
got = E.months_in_season(low + [high], PARAMS)
- self.assertNotIn(6, got) # only the highest point has June snow
+ self.assertNotIn(6, got) # only the highest point is cold in June
self.assertEqual(len(got), 11)
- def test_no_snow_measure_uses_temperature_alone(self):
- point = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1],
- snow=None)
- self.assertEqual(E.months_in_season([point], PARAMS),
- [4, 5, 6, 7, 8, 9, 10])
-
def test_a_wrapped_season_is_returned_sorted(self):
- point = normals(400, [15, 15, 15, 15, 15, 40, 40, 40, 40, 40, 15, 15],
- snow=[0] * 12)
+ point = normals(400, [15, 15, 15, 15, 15, 40, 40, 40, 40, 40, 15, 15])
self.assertEqual(E.months_in_season([point], PARAMS),
[1, 2, 3, 4, 5, 11, 12])
- def test_no_qualifying_month_is_none_with_a_reason(self):
- arctic = normals(500, [-5] * 12, snow=[30] * 12)
- self.assertIsNone(E.months_in_season([arctic], PARAMS))
- self.assertIn("no month", E.why_not([arctic], PARAMS))
+ def test_a_trail_that_never_qualifies_still_gets_three_months(self):
+ arctic = normals(500, [-5, -4, -2, 0, 3, 4, 4, 3, 1, -1, -3, -5])
+ got = E.months_in_season([arctic], PARAMS)
+ self.assertEqual(got, [5, 6, 7]) # the three nearest the cold limit
def test_all_twelve_months_is_allowed(self):
- coast = normals(20, [15] * 12, snow=[0] * 12)
+ coast = normals(20, [15] * 12)
self.assertEqual(E.months_in_season([coast], PARAMS), list(range(1, 13)))
- self.assertEqual(E.why_not([coast], PARAMS), "")
def test_a_point_with_missing_data_makes_the_trail_unestimable(self):
- point = normals(20, [15] * 12, snow=[0] * 12)
+ point = normals(20, [15] * 12)
self.assertIsNone(E.months_in_season([point, None], PARAMS))
- self.assertIn("no data", E.why_not([point, None], PARAMS))
self.assertIsNone(E.months_in_season([], PARAMS))
- self.assertIn("no data", E.why_not([], PARAMS))
class SamplePointsTest(unittest.TestCase):
@@ -205,86 +188,61 @@ class SamplePointsTest(unittest.TestCase):
self.assertAlmostEqual(points[0].lat, 43.85)
-KNOWN = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=30.0)
-GRID = {"snow_cm_max": [float(v) for v in range(0, 65, 5)],
- "cold_c_min": [float(v) for v in range(0, 13)],
- "heat_c_max": [float(v) for v in range(24, 41)]}
+class ReportTest(unittest.TestCase):
+ def loo(self, **kw):
+ """loo entries (mask, (match, classified, jaccard)) by id."""
+ return {tid: (0, v) for tid, v in kw.items()}
-
-def synthetic_sourced():
- """Trails whose sourced months come from KNOWN, designed so each
- threshold is pinned by months just either side of it."""
- cases = [
- ("cold-pin", normals(3000, [4, 4, 6, 6, 10, 15, 20, 20, 15, 10, 6, 4],
- snow=[0] * 12)),
- ("snow-pin", normals(3000, [15] * 12,
- snow=[20, 20, 12, 8, 0, 0, 0, 0, 0, 0, 8, 12])),
- ("heat-pin", normals(400, [20, 22, 26, 29, 31, 36, 38, 38, 36, 31, 28, 22],
- snow=[0] * 12)),
- ("mild-all-year", normals(100, [15] * 12, snow=[0] * 12)),
- ]
- out = []
- for tid, point in cases:
- months = E.months_in_season([point], KNOWN)
- assert months, tid
- out.append((tid, [point], months))
- return out
-
-
-class FitTest(unittest.TestCase):
- def test_held_out_is_stable_and_splits_roughly_in_half(self):
- ids = [f"trail-{i:04d}" for i in range(1000)]
- again = [t for t in ids if E.held_out(t)]
- self.assertEqual(again, [t for t in ids if E.held_out(t)])
- share = len(again) / len(ids)
- self.assertTrue(0.40 <= share <= 0.60, share)
-
- def test_fit_recovers_known_params_from_synthetic_trails(self):
- sourced = synthetic_sourced()
- fitted = E.fit_params(sourced, GRID)
- self.assertLessEqual(abs(fitted.snow_cm_max - KNOWN.snow_cm_max), 5)
- self.assertLessEqual(abs(fitted.cold_c_min - KNOWN.cold_c_min), 1)
- self.assertLessEqual(abs(fitted.heat_c_max - KNOWN.heat_c_max), 1)
- self.assertEqual(E.report(sourced, fitted)["exact"], len(sourced))
-
- def test_report_counts_grades_and_no_data(self):
- params = E.Params(snow_cm_max=10.0, cold_c_min=5.0, heat_c_max=32.0)
- mild = normals(100, [15] * 12, snow=[0] * 12)
- alpine = normals(3000, [0, 1, 3, 6, 10, 15, 20, 20, 15, 10, 4, 1],
- snow=[0] * 12)
- sourced = [
- ("exact-1", [mild], list(range(1, 13))),
- ("within-1", [alpine], [5, 6, 7, 8, 9]), # rule gives 4 to 10
- ("worse-1", [alpine], [1, 2]),
- ("nodata-1", [None], [6, 7, 8]),
- ]
- rep = E.report(sourced, params)
- self.assertEqual(rep["n"], 4)
- self.assertEqual(rep["exact"], 1)
- self.assertEqual(rep["within1"], 2) # within1 counts exact too
- self.assertEqual(rep["worse"], 1)
- self.assertEqual(rep["no_data"], 1)
+ def test_report_counts_matches_and_no_data(self):
+ med = ((15.0,) * 12, (15.0,) * 12)
+ sourced = [("a", med, [7, 8], "g"), ("b", med, [7, 8], "g"),
+ ("c", None, [6, 7, 8], "h")]
+ loo = self.loo(a=(1.0, 1.0, 1.0), b=(0.0, 0.5, 0.25))
+ rep = E.report(sourced, loo)
+ self.assertEqual((rep["n"], rep["within1"], rep["worse"], rep["no_data"]),
+ (3, 1, 1, 1))
self.assertEqual(rep["within1"] + rep["worse"] + rep["no_data"], rep["n"])
- self.assertIn("by_group", rep)
+ self.assertEqual(rep["classified"], 0.75)
+ self.assertEqual(rep["jaccard"], 0.625)
+ self.assertEqual(rep["by_group"]["g"]["within1"], 1)
+ self.assertEqual(rep["by_group"]["h"]["no_data"], 1)
def test_passes_is_false_below_the_bar_and_true_at_it(self):
def rep(within1, no_data=0, n=100):
- return {"n": n, "exact": 0, "within1": within1,
+ return {"n": n, "within1": within1,
"worse": n - within1 - no_data, "no_data": no_data}
self.assertFalse(E.passes_bar(rep(74)))
self.assertTrue(E.passes_bar(rep(75)))
self.assertFalse(E.passes_bar(rep(90, no_data=11))) # coverage 89%
- def test_the_same_input_gives_the_same_report_twice(self):
- sourced = synthetic_sourced()
- self.assertEqual(E.report(sourced, KNOWN), E.report(sourced, KNOWN))
- self.assertEqual(E.fit_params(sourced, GRID), E.fit_params(sourced, GRID))
+ def test_the_report_splits_by_kind(self):
+ med = ((20.0,) * 12, (20.0,) * 12)
+ sourced = [("a", med, list(range(1, 13)), "x")]
+ rep = E.report(sourced, self.loo(a=(1.0, 1.0, 1.0)))
+ self.assertEqual(rep["by_kind"]["year-round"]["n"], 1)
+ self.assertEqual(rep["by_kind"]["year-round"]["within1"], 1)
+ self.assertEqual(rep["by_kind"]["alpine"]["n"], 0)
+
+ def test_the_same_input_gives_the_same_fit_twice(self):
+ med = lambda v: (tuple([v] * 12), tuple([v] * 12))
+ sourced = [(f"t{i}", med(10.0 + i), [5, 6, 7, 8], "g") for i in range(6)]
+ first = E.fit_sourced(sourced)
+ second = E.fit_sourced(sourced)
+ self.assertEqual(first[0], second[0])
+ self.assertEqual(first[1], second[1])
def mild_fetch(lat, lon, elev):
return C.PointNormals(lat=float(lat), lon=float(lon),
elev_m=float(elev if elev is not None else 100.0),
- tmax_c=tuple([15.0] * 12), snow_cm=tuple([0.0] * 12))
+ tmax_c=tuple([15.0] * 12))
+
+
+def warm_with_latitude(lat, lon, elev):
+ """Warmer to the south: five degrees a degree of latitude."""
+ return C.PointNormals(lat=float(lat), lon=float(lon),
+ elev_m=float(elev if elev is not None else 100.0),
+ tmax_c=tuple([15.0 + 5.0 * (43.0 - float(lat))] * 12))
def none_fetch(lat, lon, elev):
@@ -340,7 +298,7 @@ class EstimateTest(unittest.TestCase):
with self.assertRaises(AssertionError):
E.estimate(bounds_root(td), ends_rec(), PARAMS, fetch=raising)
- def test_comparable_is_the_nearest_sourced_trail(self):
+ def test_comparable_trails_are_listed_nearest_first(self):
import tempfile, shutil
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
@@ -363,25 +321,24 @@ class EstimateTest(unittest.TestCase):
rec = R.load_toml(os.path.join(root, "target-one", "trail.toml"))
# fixture records claim line_file "" so sampling uses the ends
rec["source"]["line_file"] = "line.geojson"
- est = E.estimate(root, rec, PARAMS, fetch=mild_fetch)
+ est = E.estimate(root, rec, PARAMS, fetch=warm_with_latitude)
self.assertEqual(est["comparable"], "near-one")
self.assertEqual(est["comparable_phrase"], "June to September")
+ self.assertEqual([n[0] for n in est["neighbours"]],
+ ["near-one", "far-one"])
+ self.assertEqual(est["confidence"], "low") # the location is a fallback
class ProposeCheckTest(unittest.TestCase):
- def fit_doc(self, root, passes=True, held_within1=3, held_n=4):
+ def fit_doc(self, root, passes=True, within1=3, n=4):
os.makedirs(os.path.join(root, "tools"), exist_ok=True)
doc = {"computed": "2026-11-20", "rule_version": E.RULE_VERSION,
"dataset": "test", "period": "2011-2020",
- "params": {"snow_cm_max": 10.0, "cold_c_min": 5.0,
- "heat_c_max": 32.0},
- "held_out": {"n": held_n, "exact": 0, "within1": held_within1,
- "worse": held_n - held_within1, "no_data": 0,
- "by_group": {}},
- "all": {"n": held_n, "exact": 0, "within1": held_within1,
- "worse": held_n - held_within1, "no_data": 0,
- "by_group": {}},
- "bar": E.BAR, "passes": passes}
+ "params": E.Params(5.0, 32.0).as_dict(),
+ "loo": {"n": n, "within1": within1, "worse": n - within1,
+ "no_data": 0, "classified": 0.8, "jaccard": 0.6,
+ "by_group": {}, "by_kind": {}},
+ "confidence": None, "bar": E.BAR, "passes": passes}
with open(os.path.join(root, "tools", "season_fit.json"), "w") as f:
json.dump(doc, f)
@@ -418,7 +375,9 @@ class ProposeCheckTest(unittest.TestCase):
newline="") as f:
rows = list(csv.DictReader(f))
self.assertEqual([r["id"] for r in rows], ["aaa", "ccc"])
- self.assertEqual(rows[0]["phrase"], "All year")
+ # the one sourced trail has the same climate, so its June to
+ # September carries the estimate
+ self.assertEqual(rows[0]["phrase"], "June to September")
def est_repo(self, tmp, months_extra):
return self.repo_with(tmp, [
@@ -456,16 +415,11 @@ class ProposeCheckTest(unittest.TestCase):
import tempfile, shutil
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
- # one train and one held-out sourced trail, both graded worse
- # by mild all-year normals against a June-only season
- ids = [f"trail-{i:03d}" for i in range(40)]
- train_id = next(t for t in ids if not E.held_out(t))
- test_id = next(t for t in ids if E.held_out(t))
+ # one sourced trail that mild all-year normals cannot match
extra = ('season = "June"\nmonths = [6]\n'
'season_basis = "source"\n' + self.ENDS)
- root = self.repo_with(tmp, [(train_id, "Train", {"extra_hike": extra}),
- (test_id, "Test", {"extra_hike": extra})])
- self.fit_doc(root, held_within1=4, held_n=4)
+ root = self.repo_with(tmp, [("only", "Only", {"extra_hike": extra})])
+ self.fit_doc(root, within1=4, n=4)
ok, lines = E.check(root, mild_fetch)
self.assertFalse(ok)
self.assertTrue(any("fit got worse" in line for line in lines), lines)
@@ -501,15 +455,6 @@ class SeasonKindTest(unittest.TestCase):
self.assertEqual(E.season_kind([10, 11, 12, 1, 2, 3, 4]), "cool-season")
self.assertEqual(E.season_kind([4, 5, 6, 7, 8, 9, 10]), "other")
- def test_the_report_splits_by_kind(self):
- def pn(v):
- return C.PointNormals(40.0, -100.0, 1000.0, tuple([v] * 12))
- sourced = [("a", [pn(20.0)], list(range(1, 13)), "x")]
- rep = E.report(sourced, E.Params(10.0, 5.0, 40.0))
- self.assertEqual(rep["by_kind"]["year-round"]["n"], 1)
- self.assertEqual(rep["by_kind"]["year-round"]["exact"], 1)
- self.assertEqual(rep["by_kind"]["alpine"]["n"], 0)
-
if __name__ == "__main__":
unittest.main()
diff --git a/tools/tests/test_season_fit.py b/tools/tests/test_season_fit.py
index f15e7e4..3a2c968 100644
--- a/tools/tests/test_season_fit.py
+++ b/tools/tests/test_season_fit.py
@@ -27,19 +27,19 @@ class SeasonFitFileTest(unittest.TestCase):
def test_the_committed_fit_has_the_fields_the_site_reads(self):
fit = load_fit()
for key in ("computed", "rule_version", "dataset", "period",
- "params", "all", "held_out", "bar", "passes"):
+ "params", "loo", "bar", "passes", "confidence"):
self.assertIn(key, fit)
- for key in ("snow_cm_max", "cold_c_min", "heat_c_max"):
- self.assertIn(key, fit["params"])
- for part in ("all", "held_out"):
- for key in ("n", "exact", "within1", "worse", "no_data", "by_group"):
+ self.assertEqual(sorted(fit["params"]), sorted(E.Params(0, 0).as_dict()))
+ for part in ("loo",):
+ for key in ("n", "within1", "worse", "no_data", "classified",
+ "jaccard", "by_group", "by_kind"):
self.assertIn(key, fit[part], part)
rep = fit[part]
self.assertEqual(rep["within1"] + rep["worse"] + rep["no_data"],
rep["n"], part)
self.assertEqual(fit["bar"], E.BAR)
self.assertEqual(fit["rule_version"], E.RULE_VERSION)
- self.assertEqual(fit["passes"], E.passes_bar(fit["held_out"], fit["bar"]))
+ self.assertEqual(fit["passes"], E.passes_bar(fit["loo"], fit["bar"]))
def test_estimates_only_with_a_passing_fit(self):
estimated = []
@@ -51,7 +51,7 @@ class SeasonFitFileTest(unittest.TestCase):
self.skipTest("no estimated seasons on file yet")
fit = load_fit()
self.assertTrue(fit["passes"], fit)
- held = fit["held_out"]
+ held = fit["loo"]
self.assertGreaterEqual(held["within1"] / held["n"],
E.BAR["within1_min"])
diff --git a/tools/tests/test_season_model.py b/tools/tests/test_season_model.py
new file mode 100644
index 0000000..d8ede6a
--- /dev/null
+++ b/tools/tests/test_season_model.py
@@ -0,0 +1,185 @@
+"""Tests for tools/season_model.py: the measure, the thresholds, the
+comparable trails, the blend and the leave-one-out fit. No network."""
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+
+import season_model as M # noqa: E402
+
+P = M.Params(cold_c_min=5.0, heat_c_max=30.0, k=3, power=1, mix=0.7, cut=0.65)
+
+
+def med(high, low=None):
+ return (tuple(float(v) for v in high), tuple(float(v) for v in (low or high)))
+
+
+SUMMER = [-5, -3, 0, 5, 10, 15, 20, 20, 14, 8, 0, -4]
+WINTER = [14, 16, 20, 26, 33, 39, 42, 41, 36, 28, 20, 15]
+
+
+class MatchTest(unittest.TestCase):
+ def test_a_single_window_matches_within_one_month_at_each_end(self):
+ self.assertTrue(M.match([6, 7, 8, 9], [6, 7, 8, 9]))
+ self.assertTrue(M.match([5, 6, 7, 8, 9, 10], [6, 7, 8, 9]))
+ self.assertFalse(M.match([4, 5, 6, 7, 8, 9], [6, 7, 8, 9]))
+ self.assertFalse(M.match([], [6, 7, 8, 9]))
+
+ def test_a_season_over_the_year_end_is_one_window(self):
+ self.assertTrue(M.match([11, 12, 1, 2], [12, 1, 2, 3]))
+
+ def test_a_year_round_season_matches_ten_or_more_months(self):
+ year = list(range(1, 13))
+ self.assertTrue(M.match(year, year))
+ self.assertTrue(M.match(list(range(1, 11)), year))
+ self.assertFalse(M.match(list(range(1, 10)), year))
+
+ def test_two_windows_are_compared_window_by_window(self):
+ spring_fall = [3, 4, 5, 9, 10, 11]
+ self.assertTrue(M.match([3, 4, 5, 9, 10, 11], spring_fall))
+ self.assertTrue(M.match([4, 5, 9, 10], spring_fall))
+ # one long window covers the span but is not two windows
+ self.assertFalse(M.match(list(range(3, 12)), spring_fall))
+ # a window with no partner, and a window left over
+ self.assertFalse(M.match([3, 4, 5], spring_fall))
+ self.assertFalse(M.match([3, 4, 5, 7, 9, 10, 11], spring_fall))
+
+ def test_masks_and_lists_agree(self):
+ self.assertEqual(M.to_months(M.to_mask([3, 1, 12])), [1, 3, 12])
+ self.assertEqual(M.match(M.to_mask([6, 7]), [6, 7]), True)
+
+ def test_score_has_the_three_measures(self):
+ a, b, c = M.score([6, 7, 8], [7, 8, 9])
+ self.assertEqual(a, 1.0)
+ self.assertAlmostEqual(b, 10 / 12)
+ self.assertAlmostEqual(c, 2 / 4)
+ self.assertEqual(M.score([1], [1]), (1.0, 1.0, 1.0))
+
+
+class ThresholdsAndBlendTest(unittest.TestCase):
+ def test_thresholds_use_high_ground_cold_and_low_ground_heat(self):
+ got = M.threshold_mask(med(SUMMER, WINTER), P)
+ # cold: high ground at least 5 in April to October; heat: low
+ # ground at most 30 in October to April
+ self.assertEqual(M.to_months(got), [4, 10])
+
+ def test_a_vote_is_the_weighted_share_of_comparable_trails(self):
+ a = M.Reference("a", med(SUMMER), [6, 7, 8])
+ b = M.Reference("b", med(SUMMER), [7, 8, 9])
+ near = [(0.0, a), (0.0, b)]
+ v = M.vote(near, 1)
+ self.assertEqual(v[5], 0.5)
+ self.assertEqual(v[6], 1.0)
+ self.assertEqual(v[8], 0.5)
+ self.assertEqual(v[0], 0.0)
+
+ def test_closer_trails_weigh_more(self):
+ a = M.Reference("a", med(SUMMER), [6])
+ b = M.Reference("b", med(SUMMER), [7])
+ v = M.vote([(0.0, a), (0.5, b)], 2)
+ self.assertGreater(v[5], v[6])
+
+ def test_nearest_leaves_out_the_trail_itself(self):
+ refs = [M.Reference("self", med(SUMMER), [7]),
+ M.Reference("other", med([x + 1 for x in SUMMER]), [8])]
+ got = M.nearest(med(SUMMER), refs, 5, exclude="self")
+ self.assertEqual([r.id for _d, r in got], ["other"])
+
+ def test_a_trail_inherits_a_cool_season_from_trails_like_it(self):
+ desert = med(WINTER)
+ refs = [M.Reference(f"d{i}", med([x + i * 0.2 for x in WINTER]),
+ [11, 12, 1, 2, 3]) for i in range(4)]
+ near = M.nearest(desert, refs, 3)
+ mask, scores, fell = M.blend(desert, near, P)
+ self.assertEqual(M.to_months(mask), [1, 2, 3, 11, 12])
+ self.assertFalse(fell)
+
+ def test_without_comparable_trails_the_thresholds_stand_alone(self):
+ mask, _s, fell = M.blend(med(SUMMER), [], P)
+ self.assertEqual(M.to_months(mask), [4, 5, 6, 7, 8, 9, 10])
+ self.assertFalse(fell)
+
+ def test_an_empty_result_falls_back_to_three_months_and_says_so(self):
+ arctic = med([-20, -18, -12, -6, -1, 3, 4, 2, -3, -9, -15, -19])
+ mask, _s, fell = M.blend(arctic, [], P)
+ self.assertTrue(fell)
+ self.assertEqual(M.to_months(mask), [6, 7, 8])
+ self.assertEqual(len(M.to_months(mask)), 3)
+
+ def test_months_in_season_is_none_for_a_gap_and_never_empty(self):
+ class Pt:
+ def __init__(self, tmax, elev=100.0):
+ self.tmax_c = tuple(tmax)
+ self.elev_m = elev
+ self.assertIsNone(M.months_in_season([Pt(SUMMER), None], P))
+ self.assertIsNone(M.months_in_season([], P))
+ got = M.months_in_season([Pt([-30] * 12)], P)
+ self.assertEqual(len(got), 3)
+
+
+class ConfidenceTest(unittest.TestCase):
+ def refs(self, spread):
+ return [M.Reference(f"r{i}", med([x + i * spread for x in SUMMER]), [6, 7, 8, 9])
+ for i in range(4)]
+
+ def test_close_agreeing_comparable_trails_give_high(self):
+ near = M.nearest(med(SUMMER), self.refs(0.1), 4)
+ mask, scores, fell = M.blend(med(SUMMER), near, P)
+ level, why = M.confidence(med(SUMMER), near, scores, fell)
+ self.assertEqual(level, "high", why)
+
+ def test_far_comparable_trails_give_low(self):
+ near = M.nearest(med(SUMMER), self.refs(8.0), 4)
+ mask, scores, fell = M.blend(med(SUMMER), near, P)
+ level, why = M.confidence(med(SUMMER), near, scores, fell)
+ self.assertEqual(level, "low")
+ self.assertIn("far", why)
+
+ def test_disagreeing_comparable_trails_give_low(self):
+ refs = self.refs(0.1)
+ for ref, months in zip(refs, ([4, 5, 6], [7, 8, 9], [5, 6, 7, 8],
+ [6, 7, 8, 9, 10])):
+ ref.mask = M.to_mask(months)
+ near = M.nearest(med(SUMMER), refs, 4)
+ mask, scores, fell = M.blend(med(SUMMER), near, P)
+ level, why = M.confidence(med(SUMMER), near, scores, fell)
+ self.assertEqual(level, "low")
+ self.assertIn("disagree", why)
+
+ def test_no_comparable_trails_is_low(self):
+ self.assertEqual(M.confidence(med(SUMMER), [], [0] * 12, False)[0], "low")
+
+
+class FitTest(unittest.TestCase):
+ def trails(self):
+ out = []
+ for i in range(8):
+ out.append((f"alpine{i}", med([x + i * 0.3 for x in SUMMER]), [6, 7, 8, 9]))
+ out.append((f"desert{i}", med([x + i * 0.3 for x in WINTER]), [11, 12, 1, 2, 3]))
+ return out
+
+ def test_leave_one_out_predicts_each_trail_from_the_others(self):
+ params, loo = M.fit_model(self.trails())
+ self.assertEqual(len(loo), 16)
+ for tid, (mask, sc) in loo.items():
+ self.assertEqual(sc[0], 1.0, tid)
+ self.assertIsInstance(params, M.Params)
+
+ def test_the_same_input_gives_the_same_fit_twice(self):
+ self.assertEqual(M.fit_model(self.trails()), M.fit_model(self.trails()))
+
+ def test_a_trail_is_never_scored_by_a_model_that_saw_it(self):
+ trails = self.trails()
+ # one alpine trail whose sourced months disagree with its twins:
+ # leave-one-out cannot learn them, so it must not match
+ odd = ("odd", med(SUMMER), [1, 2, 3])
+ _p, loo = M.fit_model(trails + [odd])
+ self.assertEqual(loo["odd"][1][0], 0.0)
+
+ def test_params_round_trip_through_a_dict(self):
+ self.assertEqual(M.Params.from_dict(P.as_dict()), P)
+
+
+if __name__ == "__main__":
+ unittest.main()
From ebccfb2e33f7820e1e64c5c8c6211ec2ece54bae Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 12:55:30 -0700
Subject: [PATCH 09/30] Let a season be an estimate: the validator takes a
method ending in its confidence and a climate source, refuses an ordinary
page naming it, and requires a season on every trail
---
docs/schema.md | 6 +-
tools/estimate_season.py | 4 +-
tools/season.py | 64 +++++++++++++++--
tools/tests/test_season_basis.py | 117 +++++++++++++++++++++++++------
tools/validate.py | 1 +
5 files changed, 160 insertions(+), 32 deletions(-)
diff --git a/docs/schema.md b/docs/schema.md
index b749a92..b900bcf 100644
--- a/docs/schema.md
+++ b/docs/schema.md
@@ -126,7 +126,7 @@ The field and file names keep the word "line" (`line.geojson`, `line_file`, `lin
## `[hike]`: what a hiker asks first
-Optional: a record without `[hike]` is valid. The table holds the facts a hiker wants before anything else: where the trail goes, what the country is like, how long it takes, when to go, where its own site is. Every fact is read on a page, and that page is named in `[[hike.source]]`. The first choice is a page of the trail's holder (the agency, the association, or for a route its author) or a government page. Where those say nothing, a fact may be read on an established hiking reference that covers the trail, such as a guide site, a hiking association's list of trails or a guidebook publisher's page; the source entry names that site as the publisher, so a reader can see where the fact came from and weigh it. Apps and pages that anyone can edit (AllTrails, forums, social media, wikis) are not sources. A fact found on no acceptable page is left out, never guessed, except season, which may be estimated and must then say so. Typical time is estimated at page-build time and never stored, while an estimated season is stored on the record. Where sources disagree, the managing body's figure is used. Wording is ours: nothing is copied from a source.
+Optional: a record without `[hike]` is valid. The table holds the facts a hiker wants before anything else: where the trail goes, what the country is like, how long it takes, when to go, where its own site is. Every fact is read on a page, and that page is named in `[[hike.source]]`. The first choice is a page of the trail's holder (the agency, the association, or for a route its author) or a government page. Where those say nothing, a fact may be read on an established hiking reference that covers the trail, such as a guide site, a hiking association's list of trails or a guidebook publisher's page; the source entry names that site as the publisher, so a reader can see where the fact came from and weigh it. Apps and pages that anyone can edit (AllTrails, forums, social media, wikis) are not sources. A fact found on no acceptable page is left out, never guessed, except season, which may be estimated and must then say so. Typical time is estimated at page-build time and never stored, while an estimated season is stored on the record. Where sources disagree, the managing body's figure is used; where none of them manages the trail, is its association or is its route author, the season is set by judgement from all the pages and the climate estimate, and `season_method` says so. Wording is ours: nothing is copied from a source.
| Field | Type | Meaning | Example |
| --- | --- | --- | --- |
@@ -138,8 +138,8 @@ Optional: a record without `[hike]` is valid. The table holds the facts a hiker
| `days` | array of two integers | The usual time to walk the whole trail in one go, `[fewest, most]`, in days, as a source states it. Weeks count 7 days, months 30. | `[150, 210]` |
| `season` | string | The months in which the whole trail is usually walked, as a short phrase. Not the dates a park or hut is open, unless those set the walking season. `season` and `months` come together: one is never given without the other. For an estimated season (`season_basis = "estimate"`) the phrase is built from the months. | `"July to September"` |
| `months` | array of integers | The same season as month numbers, 1 to 12, for filtering: every month in which the whole trail, or a usual start, is normally walked. A month counts when about half of it or more is in season. Given whenever `season` is, and never without it. | `[7, 8, 9]` |
-| `season_basis` | string | Required whenever `season` is present, and refused without it. Where the season came from, one of: `primary` (the page is published by the body that manages the trail, the trail's own association, or, for a route worked out by a hiker, that route's author); `sources` (no primary page, but two or more pages from different publishers agree on the season); `source` (one page that is not a primary one); `estimate` (no page states a season, so it is worked out from climate). A route author's stated season counts as `primary`. | `"primary"` |
-| `season_method` | string | Required with `season_basis = "estimate"`, where it is one sentence naming the method and its inputs: the dataset, the period, the points used and the rule version. Allowed with `sources`, where it says in one sentence how the season was settled when the pages differ. Refused with `primary` and `source`. | `"Estimated from 1991-2020 climate normals at 5 track points (rule version 1)."` |
+| `season_basis` | string | Required whenever `season` is present, and refused without it. Where the season came from, one of: `primary` (the page is published by the body that manages the trail, the trail's own association, or, for a route worked out by a hiker, that route's author); `sources` (no primary page, but two or more pages from different publishers agree on the season); `source` (one page that is not a primary one); `estimate` (no page states a season, so it is worked out from climate). A route author's stated season counts as `primary`. An `estimate` has no page that states a season: its one `[[hike.source]]` names both `season` and `months` and cites the climate data (CHELSA, with ETOPO), and any ordinary page naming the season makes the basis wrong. An estimate is worked out by a reviewer from the trail's location, elevation, monthly climate normals, a machine estimate and the most similar sourced trails (`tools/season_judge.py`); the method was tested blind against the seasons that pages state, and the result is in `tools/season_blind_test.json`. | `"primary"` |
+| `season_method` | string | Required with `season_basis = "estimate"`, where it is one or two plain sentences saying how the season was set and what sets it there, ending "Confidence: high.", "Confidence: medium." or "Confidence: low.". Allowed with `sources`, where it says how the season was settled when the pages differ; a season with a method was set by judgement and is shown as an estimate, not as a page's statement. Refused with `primary` and `source`. | `"Snow keeps the high passes closed until late June and returns in October. Confidence: high."` |
| `high_point` | string | Name of the highest point on the trail. | `"Mount Mansfield"` |
| `high_point_m` | integer | The elevation of the highest point in metres, rounded to the nearest metre (converted from feet where the source gives feet). May be given without `high_point` where a source states the elevation but not a name. | `1340` |
| `terrain` | array of strings | One to three of `alpine`, `forest`, `desert`, `coast`, `prairie`, `canyon`, `tundra`, `lakes`, `farmland`: the main kinds of country only. | `["forest"]` |
diff --git a/tools/estimate_season.py b/tools/estimate_season.py
index a3d8fa9..cddd3ef 100644
--- a/tools/estimate_season.py
+++ b/tools/estimate_season.py
@@ -412,7 +412,7 @@ def sourced_trails(root, fetch, log=None):
out = []
for tid, rec in _records(root):
hike = rec.get("hike") or {}
- if not hike.get("season") or hike.get("season_basis") == "estimate":
+ if not season.read_from_a_page(hike):
continue
points, kind = sample_points(root, rec)
med = season_model.medians(normals_at(points, fetch))
@@ -622,7 +622,7 @@ def _phrases(root):
out = {}
for tid, rec in _records(root):
hike = rec.get("hike") or {}
- if hike.get("season") and hike.get("season_basis") != "estimate":
+ if season.read_from_a_page(hike):
out[tid] = str(hike.get("season"))
_PHRASES[root] = out
return _PHRASES[root]
diff --git a/tools/season.py b/tools/season.py
index 7abd502..7c9a351 100644
--- a/tools/season.py
+++ b/tools/season.py
@@ -4,9 +4,41 @@ Python 3 standard library only. tools/validate.py imports this module; it
must not import validate.py. The fields are documented in docs/schema.md.
"""
+import re
+import urllib.parse
+
BASES = ("primary", "sources", "source", "estimate")
PROVENANCE_KEYS = frozenset({"season_basis", "season_method"})
-SEASON_REQUIRED = False
+SEASON_REQUIRED = True
+# The host of the climate data an estimate cites (tools/season_climate.SOURCE).
+CLIMATE_HOSTS = frozenset({"www.chelsa-climate.org"})
+CONFIDENCES = ("high", "medium", "low")
+_CONFIDENCE_END = re.compile(r"Confidence: (high|medium|low)\.\s*$")
+
+
+def _is_climate(source):
+ host = urllib.parse.urlparse(str(source.get("url", ""))).hostname
+ return host in CLIMATE_HOSTS
+
+
+def confidence_of(method):
+ """"high", "medium" or "low" from the end of a season_method, else ""."""
+ found = _CONFIDENCE_END.search(str(method or ""))
+ return found.group(1) if found else ""
+
+
+def read_from_a_page(hike):
+ """True when a page states the season: one is present, its basis is not
+ "estimate", and no method records that it was worked out by judgement
+ (the seasons set from pages that disagree carry one)."""
+ return bool(hike.get("season")) and hike.get("season_basis") in (
+ "primary", "sources", "source") and not hike.get("season_method")
+
+
+def check_present(tid, rec, errors):
+ """Every record has a hike table (check_season then requires its season)."""
+ if not isinstance(rec.get("hike"), dict):
+ errors.append(f"{tid}: hike.season is required")
def _naming(sources, fact):
@@ -51,10 +83,18 @@ def check_season(tid, hike, errors):
errors.append(f"{tid}: hike.season_method must not be empty")
elif len(method) >= 400:
errors.append(f"{tid}: hike.season_method must be under 400 characters")
+ elif basis == "estimate" and not _CONFIDENCE_END.search(method):
+ errors.append(
+ f"{tid}: hike.season_method of an estimate must end with "
+ "\"Confidence: high.\", \"Confidence: medium.\" or \"Confidence: low.\"")
elif basis == "estimate":
errors.append(f"{tid}: hike.season_method is required with season_basis \"estimate\"")
naming_season = _naming(sources, "season")
+ if basis != "estimate" and any(_is_climate(x) for x in naming_season):
+ errors.append(
+ f"{tid}: a source naming season may not cite climate data unless "
+ "hike.season_basis is \"estimate\"")
if basis in ("primary", "source"):
if not naming_season:
errors.append(
@@ -69,16 +109,32 @@ def check_season(tid, hike, errors):
elif basis == "sources":
publishers = {str(s.get("publisher", "")).strip().casefold()
for s in naming_season if str(s.get("publisher", "")).strip()}
- if len(publishers) < 2:
+ if not naming_season:
+ errors.append(
+ f"{tid}: hike.season_basis \"sources\" needs a [[hike.source]] naming season")
+ elif has_method:
+ pass # set by judgement from pages that differ; they may share a publisher
+ elif len(publishers) < 2:
errors.append(
f"{tid}: hike.season_basis \"sources\" needs two sources from different "
"publishers naming season")
elif basis == "estimate":
- naming = {id(s) for s in _naming(sources, "season") + _naming(sources, "months")}
+ naming = {id(x): x for x in _naming(sources, "season") + _naming(sources, "months")}
if len(naming) != 1:
errors.append(
f"{tid}: hike.season_basis \"estimate\" needs exactly one source naming "
- "season or months")
+ "season or months, and it must cite the climate data (no page states a season)")
+ else:
+ only = next(iter(naming.values()))
+ facts = only.get("facts") or []
+ if not _is_climate(only):
+ errors.append(
+ f"{tid}: hike.season_basis \"estimate\" needs its source to cite the "
+ "climate data (CHELSA, with ETOPO); an ordinary page naming the season "
+ "makes the basis wrong")
+ if "season" not in facts or "months" not in facts:
+ errors.append(
+ f"{tid}: the climate source of an estimate must name both season and months")
# ---------------------------------------------------------------------------
diff --git a/tools/tests/test_season_basis.py b/tools/tests/test_season_basis.py
index db35fd9..7b9da90 100644
--- a/tools/tests/test_season_basis.py
+++ b/tools/tests/test_season_basis.py
@@ -20,6 +20,22 @@ def src(publisher, facts=("season", "months"), url="https://example.org/trail"):
return {"url": url, "publisher": publisher, "facts": list(facts)}
+CLIMATE_URL = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+CLIMATE = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+METHOD = "Snow clears from the high ground in June. Confidence: medium."
+
+
+def climate_src(**kw):
+ return src(CLIMATE, url=CLIMATE_URL, **kw)
+
+
+def estimate(**fields):
+ fields.setdefault("season_basis", "estimate")
+ fields.setdefault("season_method", METHOD)
+ fields.setdefault("source", [climate_src()])
+ return check(**fields)
+
+
def check(**fields):
hike = {
"season": "June to September",
@@ -98,42 +114,97 @@ class SeasonBasisTest(unittest.TestCase):
errors = check(source=[src("Park Service", facts=("days",))])
self.assertTrue(errors)
- def test_estimate_needs_a_method_and_refuses_one_otherwise(self):
- self.assertTrue(check(season_basis="estimate"))
+ def test_an_estimate_with_a_method_and_a_climate_source_passes(self):
+ self.assertEqual(estimate(), [])
+
+ def test_an_estimate_needs_a_method(self):
+ errors = estimate(season_method=None)
+ self.assertTrue(any("season_method" in e for e in errors), errors)
+ self.assertTrue(estimate(season_method=""))
+ self.assertTrue(estimate(season_method="x" * 401))
+
+ def test_an_estimate_method_ends_with_its_confidence(self):
+ for word in ("high", "medium", "low"):
+ self.assertEqual(estimate(season_method=f"Set by snow. Confidence: {word}."), [])
+ errors = estimate(season_method="Set by snow.")
+ self.assertTrue(any("Confidence" in e for e in errors), errors)
+ self.assertTrue(estimate(season_method="Set by snow. Confidence: certain."))
+
+ def test_a_method_without_an_estimate_is_still_an_error_on_a_primary(self):
+ self.assertTrue(check(season_method=METHOD))
+
+ def test_an_estimate_refuses_an_ordinary_page_naming_the_season(self):
+ two = [climate_src(), src("Park Service", url="https://example.org/p")]
+ errors = estimate(source=two)
+ self.assertTrue(errors)
+ only = [src("Park Service", url="https://example.org/p")]
+ errors = estimate(source=only)
+ self.assertTrue(any("climate" in e for e in errors), errors)
+
+ def test_an_estimate_with_no_naming_source_is_an_error(self):
+ self.assertTrue(estimate(source=[climate_src(facts=("days",))]))
+
+ def test_an_estimate_source_names_both_season_and_months(self):
+ errors = estimate(source=[climate_src(facts=("season",))])
+ self.assertTrue(any("months" in e for e in errors), errors)
+
+ def test_a_sourced_season_may_not_cite_the_climate_data(self):
+ errors = check(source=[climate_src()])
+ self.assertTrue(any("climate" in e for e in errors), errors)
+
+ def test_the_climate_host_is_the_one_the_estimator_reads(self):
+ import urllib.parse
+ import season_climate
self.assertEqual(
- check(season_basis="estimate", season_method="Estimated from climate normals."), [])
- self.assertTrue(check(season_basis="estimate", season_method=""))
- self.assertTrue(check(season_basis="estimate", season_method="x" * 401))
- self.assertTrue(check(season_method="Estimated from climate normals."))
+ season.CLIMATE_HOSTS,
+ frozenset({urllib.parse.urlparse(season_climate.SOURCE["url"]).hostname}))
- def test_estimate_with_two_naming_sources_is_an_error(self):
- two = [src("Climate", url="https://c.example/1"), src("Other", url="https://o.example/1")]
- errors = check(season_basis="estimate", season_method="Estimated from climate.", source=two)
+ def test_sources_judged_from_pages_that_differ_may_share_a_publisher(self):
+ two = [src("The Trek", url="https://t.example/1"), src("The Trek", url="https://t.example/2")]
+ errors = check(season_basis="sources", source=two)
+ self.assertTrue(errors)
+ self.assertEqual(
+ check(season_basis="sources", source=two,
+ season_method="The pages differ. Confidence: low."), [])
+
+ def test_judged_from_pages_that_differ_needs_a_page(self):
+ errors = check(season_basis="sources", source=[src("The Trek", facts=("days",))],
+ season_method="The pages differ. Confidence: low.")
self.assertTrue(errors)
- def test_estimate_with_no_naming_source_is_an_error(self):
- errors = check(season_basis="estimate", season_method="Estimated from climate.",
- source=[src("Climate", facts=("days",))])
+ def test_a_season_read_from_a_page_has_no_method_and_no_estimate_basis(self):
+ self.assertTrue(season.read_from_a_page({"season": "x", "season_basis": "primary"}))
+ self.assertFalse(season.read_from_a_page({"season": "x", "season_basis": "estimate"}))
+ self.assertFalse(season.read_from_a_page(
+ {"season": "x", "season_basis": "sources", "season_method": "Judged."}))
+ self.assertFalse(season.read_from_a_page({"season_basis": "primary"}))
+
+ def test_the_confidence_is_read_from_the_method(self):
+ self.assertEqual(season.confidence_of("Set by snow. Confidence: low."), "low")
+ self.assertEqual(season.confidence_of("Set by snow."), "")
+
+ def test_a_hike_without_season_is_an_error(self):
+ errors = check(season=None, months=None, season_basis=None, source=None)
+ self.assertTrue(any("season" in e for e in errors), errors)
+
+ def test_a_record_with_no_hike_is_an_error(self):
+ errors = []
+ season.check_present("t", {}, errors)
self.assertTrue(errors)
-
- def test_a_hike_without_season_passes_until_required(self):
- self.assertEqual(check(season=None, months=None, season_basis=None, source=None), [])
-
- def test_required_flag_makes_it_an_error(self):
- with mock.patch.object(season, "SEASON_REQUIRED", True):
- errors = check(season=None, months=None, season_basis=None, source=None)
- self.assertTrue(any("season" in e for e in errors), errors)
+ errors = []
+ season.check_present("t", {"hike": {"season": "x"}}, errors)
+ self.assertEqual(errors, [])
def test_method_without_season_is_an_error(self):
errors = check(season=None, months=None, season_basis=None, season_method="Some method.")
self.assertTrue(errors)
- def test_every_record_with_a_season_passes_the_validator(self):
+ def test_every_record_passes_the_validator(self):
errors = []
for tid in refresh.trail_ids(V.ROOT):
rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
- if (rec.get("hike") or {}).get("season"):
- V.check_hike(tid, rec, errors)
+ V.check_hike(tid, rec, errors)
+ season.check_present(tid, rec, errors)
self.assertEqual(errors, [])
def test_provenance_keys_need_no_source_fact(self):
diff --git a/tools/validate.py b/tools/validate.py
index 281c587..c337e1d 100644
--- a/tools/validate.py
+++ b/tools/validate.py
@@ -934,6 +934,7 @@ def main():
check_guides(tid, guides, errors)
check_links(tid, rec, errors)
check_hike(tid, rec, errors)
+ season.check_present(tid, rec, errors)
check_elevation(tid, tdir, rec, errors)
trail_history.check_entries(tid, rec, errors)
From 40f4cd43c4b8cdd53930c55133ffa1916eb0e445 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 12:59:44 -0700
Subject: [PATCH 10/30] Commit the packet builder and the blind scorer as
tools, with the blind-test result as a data file the site reads, and check
estimates against their recorded inputs
---
docs/season-judging.md | 54 +++
tools/estimate_season.py | 185 ++++----
tools/season_blind_test.json | 24 ++
tools/season_judge.py | 626 ++++++++++++++++++++++++++++
tools/season_judged.tsv | 223 ++++++++++
tools/season_judged_pages.json | 98 +++++
tools/tests/test_estimate_season.py | 124 ++++--
tools/tests/test_season_judge.py | 290 +++++++++++++
8 files changed, 1478 insertions(+), 146 deletions(-)
create mode 100644 docs/season-judging.md
create mode 100644 tools/season_blind_test.json
create mode 100644 tools/season_judge.py
create mode 100644 tools/season_judged.tsv
create mode 100644 tools/season_judged_pages.json
create mode 100644 tools/tests/test_season_judge.py
diff --git a/docs/season-judging.md b/docs/season-judging.md
new file mode 100644
index 0000000..e66ecf8
--- /dev/null
+++ b/docs/season-judging.md
@@ -0,0 +1,54 @@
+# Setting a season by judgement
+
+Where no page states a season, it is set by a reviewer from a packet, and the method was tested blind against the seasons that pages state. This page is the reviewer's instruction and the record of the test. The tools are `tools/season_judge.py` (packets, scoring, staging) and `tools/estimate_season.py` (the machine estimate that is one input, and the monthly check).
+
+## The test
+
+The reviewers also estimated every trail whose season a page states, from packets identical in form with the season hidden: the trail's own timing sentences were removed, and its comparable trails were never dealt to the same part as it. The three parts were reviewed separately, and the figures are added together. The result is in `tools/season_blind_test.json`, which the site reads; `python3 tools/season_judge.py score --write tools/season_blind_test.json` produces it. A season "matches" when each end of the reviewer's months is within one month of the stated season's, on the circle of the year. The machine estimate on its own matches 67.6 percent on the same measure, under the 75 percent bar, so it is not written to a record; the judged method passes, and its confidence labels are honest: high matches most often, low least.
+
+## What a packet lacks
+
+The packets rebuilt by `tools/season_judge.py packets` carry the monthly high temperature at the high and low ground but give monthly precipitation only when a file of it is supplied (`--precip`); the packets the reviewers read in November 2026 carried it for every trail.
+
+## The reviewer's instruction
+
+
+You will estimate the hiking season for each trail on a list you are given (one of `part-1.txt`, `part-2.txt` or `part-3.txt`). For each id there is one packet, `packets/.md`. Work only on the ids in your list, and read only the packet for the id you are estimating.
+
+## What to estimate
+
+The months a typical hiker normally walks the whole trail, or thru-hikes it, in a normal year.
+
+- A season may be two windows (spring and fall) or wrap the year end (October to April).
+- A month counts when about half of it or more is in season.
+- Think about what actually sets the season there: snow on the high ground, summer heat, monsoon, humidity and bugs, hunting season, short daylight, river levels, mud.
+- People do walk in cold and snow in places where that is normal. Do not assume summer everywhere.
+
+## Rules
+
+1. Use only the packet and your own general knowledge of the region and of the trail.
+2. Do not open any trail record, do not search the web, and do not read any file outside the packet and this README.
+3. Do not look at other trails' packets, answers or any scores.
+
+## What a packet contains
+
+- **The trail:** id, name, common name, country, states or provinces, length in miles, kind, shape, terrain, travel (on trail or cross-country), high point and typical days where on file.
+- **Summary, start and end:** from the trail's record, with every sentence that bears on timing removed.
+- **Where it is:** southernmost and northernmost latitude and westernmost and easternmost longitude of the sample points, and whether the location comes from a real track, from start and end points only, or from a region-centre fallback (the least precise).
+- **Elevation:** high ground and low ground in feet as the climate was read, and the track's highest and lowest points where there is a track.
+- **Climate normals (1981 to 2010):** for each month, the mean daily high in degrees F at the high ground (the upper quarter of the sample points) and the low ground (the lower half), and monthly precipitation in inches at both. Temperatures are modelled and lapse-corrected, so treat them as a guide.
+- **Machine estimate:** a climate model's estimated months, right about two times in three. Use it as one input, not an answer.
+- **Comparable trails:** ten trails with a season on record, chosen as most similar in climate and nearest in place, with state, high ground elevation, and each one's season and months. They are neighbours, not copies: yours may differ for good reason.
+- **What pages say:** present for a few trails only, where published pages disagree: each page's publisher and the months it gives.
+
+## Answer format
+
+One tab-separated file, `an answer file named by whoever runs the review (for example `answers/.tsv`)`, one line per trail on your list, no header, five columns:
+
+1. id
+2. months, as comma-separated numbers 1 to 12 (e.g. `7,8,9`, or `3,4,5,9,10,11`, or `10,11,12,1,2,3,4`)
+3. season phrase (e.g. `July to September`, `Spring and fall`)
+4. confidence: `high`, `medium` or `low`
+5. one sentence: what sets the season there
+
+Rules for the file: every id on your list exactly once; never an empty month list; no tabs inside a column; no extra columns. Say low when you really do not know.
diff --git a/tools/estimate_season.py b/tools/estimate_season.py
index cddd3ef..f7e1afd 100644
--- a/tools/estimate_season.py
+++ b/tools/estimate_season.py
@@ -15,8 +15,12 @@ against sourced seasons says how often that matters.
Commands: fit (fit the model and record the leave-one-out figure), trial
(compare the climate sources), warm (read every point's climate into the
-cache), propose (the review list), proposals (stage accepted estimates
-for the refresh pipeline) and check (rerun every estimate and the fit).
+cache), propose (the review list), estimates (the trails whose season is an
+estimate) and check (rerun the machine estimate for every estimate and
+flag any whose inputs changed, and the fit). The seasons themselves are
+set by judgement from the packets of tools/season_judge.py, which also
+stages them for the refresh pipeline; the machine estimate is one input
+to that judgement and is not written to a record on its own.
"""
import sys
@@ -680,101 +684,44 @@ def _toml_str(text):
return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'
-def _parse_months(text):
- months = []
- for piece in (text or "").replace(",", " ").replace(";", " ").split():
- months.append(int(piece))
- return sorted(set(months))
+def inputs_signature(est):
+ """What an estimate rests on, as a small comparable record: the machine
+ estimate's months and a digest of the climate at the high and low
+ ground and of the sourced trails it was compared with."""
+ normals = est["normals"]
+ med = season_model.medians(normals) if all(n is not None for n in normals) else None
+ material = json.dumps({"med": med, "near": [n[0] for n in est["neighbours"]]},
+ sort_keys=True)
+ return {"machine": sorted(est["months"] or []),
+ "digest": hashlib.sha256(material.encode()).hexdigest()[:16]}
-def proposals(root, reviewed_csv, given_dir=None):
- """Stage one change proposal per accepted reviewed row (a row with
- months). A row with a note was adjusted by hand, and its method
- sentence says so. Returns how many proposals were staged."""
- with open(reviewed_csv, newline="", encoding="utf-8") as f:
- reviewed = list(csv.DictReader(f))
- staging = refresh.staging_dir(root, given_dir, create=True)
- out = os.path.join(staging, "staged", "season-estimate")
- today = datetime.date.today().isoformat()
- source = season_climate.SOURCE
- report = []
- for row in reviewed:
- tid = (row.get("id") or "").strip()
- try:
- months = _parse_months(row.get("proposed_months"))
- except ValueError:
- raise ValueError(f"{tid}: proposed_months {row.get('proposed_months')!r} "
- "is not a list of month numbers")
- if not tid or not months:
- continue
- rec = refresh.load_toml(os.path.join(root, tid, "trail.toml"))
- hike = rec.get("hike") or {}
- if hike.get("season"):
- raise ValueError(f"{tid}: already has a season")
- points, kind = sample_points(root, rec)
- phrase = season.phrase_for(months)
- method = season.method_sentence(source["name"], source["period"],
- len(points), kind, RULE_VERSION)
- note = (row.get("note") or "").strip()
- comparable = (row.get("comparable") or "").strip()
- if note and comparable:
- method = method[:-1] + f", and adjusted by hand against {comparable}."
- quote = (f"Monthly climate ({source['period']}) from {source['name']} "
- f"gives {phrase} at the trail elevation.")
- page = source["url"]
- lines = ["[[proposal]]", 'kind = "change"', f"id = {_toml_str(tid)}",
- f"date = {_toml_str(today)}",
- f"summary = {_toml_str('Add an estimated season: ' + phrase + '.')}", ""]
+def load_inputs(root):
+ path = os.path.join(root, "tools", "season_inputs.json")
+ try:
+ with open(path, encoding="utf-8") as f:
+ return json.load(f)
+ except OSError:
+ return {}
- def edit(field, new_toml, old_toml=None):
- lines.append("[[proposal.edit]]")
- lines.append(f"field = {_toml_str(field)}")
- if old_toml is not None:
- lines.append(f"old = {old_toml}")
- lines.append(f"new = {new_toml}")
- lines.append(f"page = {_toml_str(page)}")
- lines.append(f"quote = {_toml_str(quote)}")
- lines.append("")
- edit("hike.season", _toml_str(phrase))
- edit("hike.months", "[" + ", ".join(str(m) for m in months) + "]")
- edit("hike.season_basis", _toml_str("estimate"))
- edit("hike.season_method", _toml_str(method))
- checked_old = hike.get("checked")
- edit("hike.checked", _toml_str(today),
- _toml_str(checked_old) if checked_old else None)
- lines += ["[[proposal.append]]", 'table = "hike.source"',
- f"page = {_toml_str(page)}", f"quote = {_toml_str(quote)}", "",
- "[proposal.append.entry]",
- f"url = {_toml_str(page)}",
- f"publisher = {_toml_str(source['publisher'])}",
- 'facts = ["season", "months"]', "",
- "[proposal.history]",
- f"change = {_toml_str('A season was estimated from climate: ' + phrase + '.')}",
- f"basis = {_toml_str('No page states a season; it is estimated from climate (rule version ' + str(RULE_VERSION) + ').')}",
- f"basis_url = {_toml_str(page)}",
- 'asked_by = "the dataset\'s own check"',
- 'fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]',
- ""]
- d = os.path.join(out, tid)
- os.makedirs(d, exist_ok=True)
- with open(os.path.join(d, "proposal.toml"), "w", encoding="utf-8") as f:
- f.write("\n".join(lines))
- remark = f"estimated season {phrase}" + (f"; note: {note}" if note else "")
- report.append((tid, "changed", page, remark))
- os.makedirs(out, exist_ok=True)
- with open(os.path.join(out, "report.csv"), "w", newline="", encoding="utf-8") as f:
- writer = csv.writer(f)
- writer.writerow(["id", "outcome", "pages", "remark"])
- writer.writerows(report)
- return len(report)
+def estimates(root):
+ """The ids of the records whose season is an estimate, in order."""
+ return [tid for tid, rec in _records(root)
+ if (rec.get("hike") or {}).get("season_basis") == "estimate"]
def check(root, fetch):
- """Rerun every estimated season and the leave-one-out fit. Returns
- (ok, lines): not ok when an estimate would now come out different,
- when the leave-one-out match share has fallen by more than 0.02
- from season_fit.json, or when that file does not pass."""
+ """Rerun the machine estimate for every estimated season and the
+ leave-one-out fit. Returns (ok, lines): not ok when an estimate's
+ inputs have changed since they were recorded in
+ tools/season_inputs.json (the machine estimate, the climate at the
+ trail, or the sourced trails it is compared with), when the
+ leave-one-out match share has fallen by more than 0.02 from
+ tools/season_fit.json, or when the blind test of the judged method
+ (tools/season_blind_test.json) is missing or below the bar. A changed
+ estimate is a flag for a person to look at, not a rewrite."""
+ import season_judge
try:
fit = load_fit(root)
except OSError:
@@ -783,18 +730,31 @@ def check(root, fetch):
params = load_params(root)
ok, lines, checked = True, [], 0
refs = references(root, fetch)
+ recorded = load_inputs(root)
for tid, rec in _records(root):
hike = rec.get("hike") or {}
if hike.get("season_basis") != "estimate":
continue
checked += 1
- est = estimate(root, dict(rec, id=tid), params, fetch, refs)
- old = sorted(int(m) for m in hike.get("months") or [])
- new = sorted(est["months"] or [])
- if new != old:
+ sig = inputs_signature(estimate(root, dict(rec, id=tid), params, fetch, refs))
+ then = recorded.get(tid)
+ if then is None:
ok = False
- detail = est["phrase"] or est["reason"]
- lines.append(f"{tid}: estimate was {old}, now {new} ({detail})")
+ lines.append(f"{tid}: no inputs are recorded for this estimate: run "
+ "python3 tools/season_judge.py inputs")
+ elif sig["machine"] != then["machine"]:
+ ok = False
+ lines.append(f"{tid}: inputs changed: the machine estimate was {then['machine']}, "
+ f"now {sig['machine']}; the season is {sorted(hike.get('months') or [])}")
+ elif sig["digest"] != then["digest"]:
+ ok = False
+ lines.append(f"{tid}: inputs changed: the climate or the similar sourced trails differ "
+ f"(machine estimate still {sig['machine']}); the season is "
+ f"{sorted(hike.get('months') or [])}")
+ for tid in sorted(set(recorded) - set(estimates(root))):
+ ok = False
+ lines.append(f"{tid}: has recorded inputs but is no longer an estimate: remove it "
+ "from tools/season_inputs.json")
sourced = sourced_trails(root, fetch)
if any(s[1] is not None for s in sourced):
_p, now, _loo = fit_sourced(sourced)
@@ -808,12 +768,21 @@ def check(root, fetch):
f"fit got worse: leave-one-out matches "
f"{now['within1']}/{now['n']} ({now_share:.2f}), "
f"was {stored['within1']}/{stored['n']} ({was_share:.2f})")
- if not fit.get("passes"):
+ try:
+ blind = season_judge.load_blind_test(os.path.join(root, "tools", "season_blind_test.json"))
+ problems = season_judge.check_blind_test(blind)
+ if problems:
+ ok = False
+ lines += [f"tools/season_blind_test.json: {p}" for p in problems]
+ elif blind["share"] < BAR["within1_min"]:
+ ok = False
+ lines.append(f"the blind test matched {blind['share']:.2f}, under the bar of "
+ f"{BAR['within1_min']:.2f}; estimates must not ship")
+ except (OSError, ValueError, KeyError):
ok = False
- lines.append("tools/season_fit.json does not pass the bar; "
- "estimates must not ship")
+ lines.append("tools/season_blind_test.json is missing or unreadable")
if ok:
- lines.append(f"check passed: {checked} estimated seasons unchanged")
+ lines.append(f"check passed: {checked} estimated seasons rest on the same inputs")
return ok, lines
@@ -892,9 +861,9 @@ def cmd_propose(args):
return 0
-def cmd_proposals(args):
- count = proposals(ROOT, args.reviewed, args.dir)
- print(f"{count} proposals staged")
+def cmd_estimates(args):
+ for tid in estimates(ROOT):
+ print(tid)
return 0
@@ -932,13 +901,9 @@ def main(argv=None):
propose_parser.add_argument("--cache", default=None,
help="climate cache directory")
propose_parser.set_defaults(func=cmd_propose)
- proposals_parser = sub.add_parser(
- "proposals", help="stage proposals from a reviewed list")
- proposals_parser.add_argument("--reviewed", required=True,
- help="reviewed estimates CSV")
- proposals_parser.add_argument("--dir", default=None,
- help="staging directory")
- proposals_parser.set_defaults(func=cmd_proposals)
+ estimates_parser = sub.add_parser(
+ "estimates", help="list the trails whose season is an estimate")
+ estimates_parser.set_defaults(func=cmd_estimates)
check_parser = sub.add_parser(
"check", help="rerun every estimate and the fit")
check_parser.add_argument("--cache", default=None,
diff --git a/tools/season_blind_test.json b/tools/season_blind_test.json
new file mode 100644
index 0000000..ef9f2f3
--- /dev/null
+++ b/tools/season_blind_test.json
@@ -0,0 +1,24 @@
+{
+ "date": "2026-11-20",
+ "measure": "within one month at each end of the season a page states",
+ "tested": 148,
+ "matched": 114,
+ "share": 0.77,
+ "by_confidence": {
+ "high": {
+ "tested": 52,
+ "matched": 48,
+ "share": 0.92
+ },
+ "medium": {
+ "tested": 76,
+ "matched": 55,
+ "share": 0.72
+ },
+ "low": {
+ "tested": 20,
+ "matched": 11,
+ "share": 0.55
+ }
+ }
+}
diff --git a/tools/season_judge.py b/tools/season_judge.py
new file mode 100644
index 0000000..2958599
--- /dev/null
+++ b/tools/season_judge.py
@@ -0,0 +1,626 @@
+#!/usr/bin/env python3
+"""Packets, blind scoring and proposals for seasons set by judgement.
+
+Python 3 standard library only. Where no page states a season, a reviewer
+sets it from a packet: the trail's location, elevation, monthly climate
+normals (tools/season_climate.py), the machine estimate of
+tools/estimate_season.py and the most similar sourced trails. The method
+was tested blind: the same reviewers estimated the trails whose season a
+page states, from identical packets with the season hidden, and the share
+they matched is in tools/season_blind_test.json, which the site reads.
+docs/season-judging.md says how a reviewer works.
+
+Commands:
+ packets write one packet per trail, and the three part lists
+ score score reviewers' answer files against the sourced seasons
+ (--write records the figures in tools/season_blind_test.json)
+ proposals stage the judged seasons for the trails with no season, for
+ python3 tools/refresh.py collect and apply
+ inputs record the machine estimate and the inputs of every estimate,
+ so the monthly check can see when they change
+
+An answer file is tab separated, one trail a line, no header: id, months
+(comma separated, 1 to 12), season phrase, confidence (high, medium or
+low) and one sentence saying what sets the season there.
+"""
+import sys
+
+sys.dont_write_bytecode = True
+
+import argparse
+import datetime
+import json
+import os
+import random
+import re
+import statistics
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+
+import estimate_season as E # noqa: E402
+import refresh # noqa: E402
+import season # noqa: E402
+import season_climate as C # noqa: E402
+import season_model as M # noqa: E402
+
+ROOT = os.path.dirname(HERE)
+BLIND_TEST = os.path.join(ROOT, "tools", "season_blind_test.json")
+JUDGED = os.path.join(ROOT, "tools", "season_judged.tsv")
+PAGES = os.path.join(ROOT, "tools", "season_judged_pages.json")
+INPUTS = os.path.join(ROOT, "tools", "season_inputs.json")
+
+SEED = 20261120
+PARTS = 3
+NCOMP = 10
+PLACE_WEIGHT = 0.1 # climate-distance units per 1000 km between sample-point centres
+KM_PER_MILE = 1.609344
+CONFIDENCES = ("high", "medium", "low")
+LEAD = "Judged from the climate at the trail's elevation and from similar trails."
+MONTHS = ["January", "February", "March", "April", "May", "June", "July",
+ "August", "September", "October", "November", "December"]
+ABB = [m[:3] for m in MONTHS]
+
+# ---------------------------------------------------------------------------
+# Hiding the season: a packet never carries a sentence that bears on timing.
+
+_MONTH_RE = re.compile(
+ r"\b(?:January|February|March|April|May|June|July|August|September|October|November|"
+ r"December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sept?|Oct|Nov|Dec)\b(?!\s+[A-Z])\.?")
+_SEASON_RE = re.compile(
+ r"\b(?:summer|winter|spring|fall|autumn|seasons?|seasonal|year[- ]?round|all[- ]year|"
+ r"snow[- ]?free|snowmelt|snow[- ]melt|snowpack|monsoons?|best time|time of year|when to go|"
+ r"(?:warm|warmer|cold|colder|cool|cooler|hot|wet|dry|snowy|shoulder) months?)\b", re.I)
+_LEAD_SEASON_RE = re.compile(r"^(?:Summer|Winter|Spring|Fall|Autumn|Seasons?|Seasonal)\b")
+_SPLIT = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9\"'(])")
+
+
+def mentions_season(sentence):
+ """True when a sentence names a month or a season. A capitalised month
+ counts unless it starts a name ("May Lake"); a season word counts in
+ lower case or opening the sentence, so "Summer Lake" does not."""
+ sentence = re.sub(r"\bhot springs?\b", "", sentence, flags=re.I)
+ if _MONTH_RE.search(sentence):
+ return True
+ for found in _SEASON_RE.finditer(sentence):
+ word = found.group(0)
+ if word[0].islower() or word.lower().startswith(("year", "all", "snow")):
+ return True
+ return bool(_LEAD_SEASON_RE.match(sentence))
+
+
+def clean(text):
+ """(text without the sentences that bear on timing, those sentences)."""
+ kept, removed = [], []
+ for sentence in _SPLIT.split(str(text or "").strip()):
+ if not sentence:
+ continue
+ (removed if mentions_season(sentence) else kept).append(sentence)
+ return " ".join(kept), removed
+
+
+def shown(kept, original):
+ if not original:
+ return "(not on file)"
+ return kept or "(none left after removing sentences that mention a season)"
+
+
+# ---------------------------------------------------------------------------
+# The blind protocol: trails are split into parts, and a trail's comparable
+# trails never come from its own part.
+
+def split_parts(sourced, others, n=PARTS, seed=SEED):
+ """Deal the sourced and the other trails separately into n parts, in a
+ seeded shuffle, so every part holds a share of each."""
+ rng = random.Random(seed)
+ parts = [[] for _ in range(n)]
+ for group in (sourced, others):
+ group = list(group)
+ rng.shuffle(group)
+ for k, tid in enumerate(group):
+ parts[k % n].append(tid)
+ return [sorted(p) for p in parts]
+
+
+def comparables(tid, part_of, sourced_ids, meds, centres, k=NCOMP, place_weight=PLACE_WEIGHT):
+ """The k sourced trails closest to tid in climate and place, never itself
+ and never one dealt to its own part."""
+ if tid not in meds:
+ return []
+ rows = []
+ for other in sourced_ids:
+ if other == tid or part_of.get(other) == part_of.get(tid) or other not in meds:
+ continue
+ d = M.distance(meds[tid], meds[other])
+ km = C.haversine_km(*centres[tid], *centres[other])
+ rows.append((d + place_weight * km / 1000.0, other))
+ rows.sort()
+ return [other for _score, other in rows[:k]]
+
+
+# ---------------------------------------------------------------------------
+# The packet.
+
+def _ft(metres):
+ return int(round(metres * 3.28084))
+
+
+def _f(celsius):
+ return celsius * 9 / 5 + 32
+
+
+def _ll(lat, lon):
+ return (f"{abs(lat):.1f}{'N' if lat >= 0 else 'S'}",
+ f"{abs(lon):.1f}{'W' if lon <= 0 else 'E'}")
+
+
+def packet_text(rec, info, machine, comparables, pages=None, precip=None):
+ """The packet for one trail, as text.
+
+ info: {"points": [PointNormals or None], "kind": "track"|"ends"|"place",
+ "profile": (highest_m, lowest_m) or None}. machine: the machine
+ estimate's months. comparables: rows of (name, regions, high ground
+ feet, season phrase, months). pages: what disagreeing pages say, or
+ None. precip: millimetres a month at each point, or None. The trail's
+ own season is never used."""
+ hike = rec.get("hike") or {}
+ tid = rec["id"]
+ out = [f"# Trail packet: {tid}", "", "## The trail", ""]
+ out += [f"- id: {tid}", f"- name: {rec['name']}",
+ f"- common name: {rec.get('common_name') or '(none on file)'}",
+ f"- country: {rec['country']}",
+ f"- states or provinces: {', '.join(rec.get('regions') or []) or '(none on file)'}",
+ f"- length: {rec['length_km'] / KM_PER_MILE:.0f} miles",
+ f"- kind: {rec.get('kind') or '(not on file)'}",
+ f"- shape: {hike.get('shape') or '(not on file)'}",
+ f"- terrain: {', '.join(hike.get('terrain') or []) or '(not on file)'}",
+ f"- travel: {hike.get('travel') or '(not on file)'}"]
+ hp, name = hike.get("high_point_m"), hike.get("high_point")
+ out.append("- high point: " + (f"{_ft(hp)} ft" + (f" ({name})" if name else "")
+ if hp is not None else "(not on file)"))
+ days = hike.get("days")
+ out.append("- typical days: " + (f"{days[0]} to {days[1]}" if days and len(days) == 2
+ and days[0] != days[1] else (str(days[0]) if days else "(not on file)")))
+ out += ["", "## Summary, start and end", "",
+ "(Sentences that bear on timing have been removed.)", ""]
+ for label, key in (("Summary", "summary"), ("Start", "start"), ("End", "end")):
+ kept, _removed = clean(hike.get(key))
+ out.append(f"{label}: {shown(kept, hike.get(key))}")
+ points = M.usable(info["points"])
+ out += ["", "## Where it is", ""]
+ if points:
+ lats, lons = [p.lat for p in points], [p.lon for p in points]
+ south, _ = _ll(min(lats), 0)
+ north, _ = _ll(max(lats), 0)
+ _, west = _ll(0, min(lons))
+ _, east = _ll(0, max(lons))
+ out += [f"- sample points: {len(points)}",
+ f"- southernmost: {south}; northernmost: {north}",
+ f"- westernmost: {west}; easternmost: {east}",
+ f"- rough extent: {south} to {north}, {west} to {east}" if len(points) > 1
+ else f"- rough extent: a single point at {south}, {west}"]
+ out.append("- location is: " + {
+ "track": "a real track (points spaced along it)",
+ "ends": "start and end points only (no track)",
+ "place": "a region-centre fallback (no track and no end points; the centre of "
+ "the first region's box)"}[info["kind"]])
+ out += ["", "## Elevation", ""]
+ if points:
+ high, low = M.high_low(points)
+ out.append(f"- high ground (the upper quarter of the sample points): "
+ f"{_ft(statistics.median(p.elev_m for p in high))} ft")
+ out.append(f"- low ground (the lower half of the sample points): "
+ f"{_ft(statistics.median(p.elev_m for p in low))} ft")
+ prof = info.get("profile")
+ out.append("- track's highest and lowest points: " + (
+ f"{_ft(prof[0])} ft and {_ft(prof[1])} ft" if prof else "(no track elevation on file)"))
+ out += ["", "## Climate normals (1981 to 2010)", ""]
+ if points:
+ pr_of = {}
+ if precip and len(precip) == len(points) and all(precip):
+ pr_of = {id(p): pr for p, pr in zip(points, precip)}
+
+ def by_month(group, get):
+ return [statistics.median(get(p)[m] for p in group) for m in range(12)]
+ hh = by_month(high, lambda p: p.tmax_c)
+ ll = by_month(low, lambda p: p.tmax_c)
+ out.append("Mean daily high in degrees F, " + ("and monthly precipitation in inches, "
+ if pr_of else "")
+ + "at the high ground and at the low ground.")
+ out.append("")
+ if pr_of:
+ ph = by_month(high, lambda p: pr_of[id(p)])
+ pl = by_month(low, lambda p: pr_of[id(p)])
+ out += ["| month | high ground F | low ground F | high ground precip in | low ground precip in |",
+ "|---|---|---|---|---|"]
+ out += [f"| {ABB[m]} | {_f(hh[m]):.0f} | {_f(ll[m]):.0f} | {ph[m] / 25.4:.1f} | {pl[m] / 25.4:.1f} |"
+ for m in range(12)]
+ else:
+ out += ["| month | high ground F | low ground F |", "|---|---|---|"]
+ out += [f"| {ABB[m]} | {_f(hh[m]):.0f} | {_f(ll[m]):.0f} |" for m in range(12)]
+ out += ["", "(Precipitation is not available for this trail.)"]
+ else:
+ out.append("No climate data is available for this trail's location.")
+ out += ["", "## Machine estimate", "",
+ "Labelled: machine estimate, right about two times in three.", "",
+ "Months: " + (", ".join(map(str, machine)) + " (" + ", ".join(MONTHS[m - 1] for m in machine) + ")"
+ if machine else "none"),
+ "", "## Comparable trails", "",
+ "The ten trails with a season on record that are most similar in climate and "
+ "nearest in place (this trail is never listed).", ""]
+ if comparables:
+ out += ["| trail | state | high ground elevation | season | months |", "|---|---|---|---|---|"]
+ out += [f"| {n} | {', '.join(regions)} | {feet} ft | {phrase} | {', '.join(map(str, months))} |"
+ for n, regions, feet, phrase, months in comparables]
+ else:
+ out.append("(none)")
+ if pages:
+ out += ["", "## What pages say", "", "Published pages disagree about this trail's season.", "", pages]
+ return "\n".join(out) + "\n"
+
+
+# ---------------------------------------------------------------------------
+# Answers and the blind score.
+
+def read_answers(path, known):
+ """({id: (months, phrase, confidence, why)}, [(line number, problem)])."""
+ answers, problems, known = {}, [], set(known)
+ with open(path, encoding="utf-8") as f:
+ for n, raw in enumerate(f, 1):
+ line = raw.rstrip("\n")
+ if not line.strip() or line.startswith("#") or line.lower().startswith("id\t"):
+ continue
+ c = line.split("\t")
+ if len(c) < 4:
+ problems.append((n, f"expected at least 4 tab-separated columns, got {len(c)}"))
+ continue
+ tid, text, phrase, conf = c[0].strip(), c[1].strip(), c[2].strip(), c[3].strip().lower()
+ why = c[4].strip() if len(c) > 4 else ""
+ if tid not in known:
+ problems.append((n, f"unknown id {tid!r}"))
+ elif tid in answers:
+ problems.append((n, f"duplicate id {tid}"))
+ elif conf not in CONFIDENCES:
+ problems.append((n, f"{tid}: confidence must be high, medium or low: {conf!r}"))
+ else:
+ try:
+ months = sorted({int(x) for x in re.split(r"[,\s]+", text) if x})
+ except ValueError:
+ problems.append((n, f"{tid}: months are not numbers: {text!r}"))
+ continue
+ if not months or months[0] < 1 or months[-1] > 12:
+ problems.append((n, f"{tid}: months empty or outside 1 to 12: {text!r}"))
+ continue
+ answers[tid] = (months, phrase, conf, why)
+ return answers, problems
+
+
+def score(answers, truth):
+ """The blind result: for every trail whose season a page states (truth,
+ {id: months}) whether the reviewer's months match within a month at each
+ end, in all and by the reviewer's confidence. A trail with no answer is
+ tested and counts as missed; an answer for a trail not in truth is not
+ scored."""
+ by = {c: {"tested": 0, "matched": 0} for c in CONFIDENCES}
+ tested = matched = unanswered = 0
+ for tid, months in sorted(truth.items()):
+ tested += 1
+ if tid not in answers:
+ unanswered += 1
+ continue
+ got, _phrase, conf, _why = answers[tid]
+ hit = bool(M.score(got, months)[0])
+ matched += hit
+ by[conf]["tested"] += 1
+ by[conf]["matched"] += hit
+ return {"tested": tested, "matched": matched, "unanswered": unanswered, "by_confidence": by}
+
+
+def _share(matched, tested):
+ return round(matched / tested, 2) if tested else 0.0
+
+
+def write_blind_test(path, figures, date):
+ doc = {
+ "date": date,
+ "measure": "within one month at each end of the season a page states",
+ "tested": figures["tested"],
+ "matched": figures["matched"],
+ "share": _share(figures["matched"], figures["tested"]),
+ "by_confidence": {
+ c: {"tested": v["tested"], "matched": v["matched"],
+ "share": _share(v["matched"], v["tested"])}
+ for c, v in figures["by_confidence"].items()},
+ }
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(doc, f, indent=1, sort_keys=False)
+ f.write("\n")
+
+
+def load_blind_test(path=BLIND_TEST):
+ with open(path, encoding="utf-8") as f:
+ return json.load(f)
+
+
+def check_blind_test(doc):
+ """Problems with the figure file: the parts must add up to the whole and
+ each share must be the matched count over the tested count."""
+ problems = []
+ by = doc.get("by_confidence") or {}
+ if sorted(by) != sorted(CONFIDENCES):
+ problems.append("by_confidence must hold high, medium and low")
+ return problems
+ if sum(v["tested"] for v in by.values()) != doc["tested"]:
+ problems.append("the confidence groups do not add up to the trails tested")
+ if sum(v["matched"] for v in by.values()) != doc["matched"]:
+ problems.append("the confidence groups do not add up to the trails matched")
+ for name, v in [("all", doc)] + list(by.items()):
+ if v["matched"] > v["tested"]:
+ problems.append(f"{name}: more matched than tested")
+ elif v["share"] != _share(v["matched"], v["tested"]):
+ problems.append(f"{name}: the share is not matched over tested")
+ return problems
+
+
+# ---------------------------------------------------------------------------
+# Writing the judged seasons: proposals for refresh.py collect and apply.
+
+def method_text(why, confidence, lead=LEAD):
+ """The season_method an estimate carries: how it was set, what sets the
+ season there, and the confidence."""
+ return f"{lead} {why.strip()} Confidence: {confidence}."
+
+
+def proposals(root, answers_path, pages_path, given_dir=None):
+ """Stage one proposal for every trail with no season that has an answer.
+ A trail named in the pages file was set by judgement from pages that
+ differ: its season is `sources`, citing those pages, with the sentences
+ the file gives as its method. Every other is an `estimate` citing the
+ climate data. Returns how many were staged."""
+ ids = refresh.trail_ids(root)
+ answers, problems = read_answers(answers_path, ids)
+ if problems:
+ raise ValueError("; ".join(f"line {n}: {t}" for n, t in problems))
+ pages = {}
+ if pages_path and os.path.exists(pages_path):
+ with open(pages_path, encoding="utf-8") as f:
+ pages = json.load(f)
+ staging = refresh.staging_dir(root, given_dir, create=True)
+ out = os.path.join(staging, "staged", "season-judged")
+ today = datetime.date.today().isoformat()
+ source = C.SOURCE
+ report = []
+ for tid in ids:
+ rec = refresh.load_toml(os.path.join(root, tid, "trail.toml"))
+ hike = rec.get("hike") or {}
+ if hike.get("season") or tid not in answers:
+ continue
+ months, _phrase, conf, why = answers[tid]
+ phrase = season.phrase_for(months)
+ judged_pages = pages.get(tid)
+ if judged_pages:
+ basis = "sources"
+ method = f"{judged_pages['why'].strip()} Confidence: {conf}."
+ cites = [(s["url"], s["publisher"], s["quote"]) for s in judged_pages["sources"]]
+ note = "the pages differ; set by judgement"
+ else:
+ basis = "estimate"
+ method = method_text(why, conf)
+ quote = (f"Monthly climate ({source['period']}) from {source['name']} "
+ f"at the trail elevation, read with the seasons of similar trails.")
+ cites = [(source["url"], source["publisher"], quote)]
+ note = "estimated from climate"
+ page, _publisher, quote = cites[0]
+ lines = ["[[proposal]]", 'kind = "change"', f"id = {E._toml_str(tid)}",
+ f"date = {E._toml_str(today)}",
+ f"summary = {E._toml_str('Add a season, ' + note + ': ' + phrase + '.')}", ""]
+
+ def edit(field, new_toml, old_toml=None):
+ lines.append("[[proposal.edit]]")
+ lines.append(f"field = {E._toml_str(field)}")
+ if old_toml is not None:
+ lines.append(f"old = {old_toml}")
+ lines.append(f"new = {new_toml}")
+ lines.append(f"page = {E._toml_str(page)}")
+ lines.append(f"quote = {E._toml_str(quote)}")
+ lines.append("")
+
+ edit("hike.season", E._toml_str(phrase))
+ edit("hike.months", "[" + ", ".join(str(m) for m in months) + "]")
+ edit("hike.season_basis", E._toml_str(basis))
+ edit("hike.season_method", E._toml_str(method))
+ checked_old = hike.get("checked")
+ edit("hike.checked", E._toml_str(today), E._toml_str(checked_old) if checked_old else None)
+ for url, publisher, q in cites:
+ lines += ["[[proposal.append]]", 'table = "hike.source"',
+ f"page = {E._toml_str(url)}", f"quote = {E._toml_str(q)}", "",
+ "[proposal.append.entry]",
+ f"url = {E._toml_str(url)}",
+ f"publisher = {E._toml_str(publisher)}",
+ 'facts = ["season", "months"]', ""]
+ if basis == "estimate":
+ change = f"A season was estimated: {phrase}."
+ why_basis = ("No page states a season. It was set by judgement from the climate "
+ "at the trail's elevation and from similar trails.")
+ else:
+ change = f"A season was set from pages that differ: {phrase}."
+ why_basis = ("The pages that state a season differ and none is the managing body, "
+ "association or route author, so it was set by judgement from all of "
+ "them and the climate estimate.")
+ lines += ["[proposal.history]", f"change = {E._toml_str(change)}",
+ f"basis = {E._toml_str(why_basis)}",
+ f"basis_url = {E._toml_str(page)}",
+ 'asked_by = "the dataset\'s own check"',
+ 'fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]',
+ ""]
+ d = os.path.join(out, tid)
+ os.makedirs(d, exist_ok=True)
+ with open(os.path.join(d, "proposal.toml"), "w", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+ report.append((tid, "changed", page, f"season {phrase}; {note}"))
+ os.makedirs(out, exist_ok=True)
+ import csv
+ with open(os.path.join(out, "report.csv"), "w", newline="", encoding="utf-8") as f:
+ writer = csv.writer(f)
+ writer.writerow(["id", "outcome", "pages", "remark"])
+ writer.writerows(report)
+ return len(report)
+
+
+# ---------------------------------------------------------------------------
+# Command line.
+
+def _truth(root):
+ truth = {}
+ for tid, rec in E._records(root):
+ hike = rec.get("hike") or {}
+ if season.read_from_a_page(hike):
+ truth[tid] = sorted(int(m) for m in hike.get("months") or [])
+ return truth
+
+
+def build_packets(root, out_dir, fetch, precip_file=None, pages_text=None):
+ """Write packets/.md and part-N.txt under out_dir. Reads the climate
+ through fetch (the cache); returns the number of packets."""
+ recs = {tid: dict(rec, id=tid) for tid, rec in E._records(root)}
+ ids = sorted(recs)
+ truth = _truth(root)
+ precip = {}
+ if precip_file:
+ with open(precip_file, encoding="utf-8") as f:
+ precip = json.load(f)
+ params = E.load_params(root)
+ refs = E.references(root, fetch)
+ info, meds, centres = {}, {}, {}
+ for tid in ids:
+ pts, kind = E.sample_points(root, recs[tid])
+ norms = E.normals_at(pts, fetch)
+ profile = None
+ if kind == "track":
+ try:
+ with open(os.path.join(root, tid, "elevation.json"), encoding="utf-8") as f:
+ data = json.load(f)
+ profile = (data["highest"]["m"], data["lowest"]["m"])
+ except (OSError, KeyError, TypeError, ValueError):
+ profile = None
+ got = M.usable(norms)
+ info[tid] = {"points": got or [], "kind": kind, "profile": profile}
+ if got:
+ meds[tid] = M.medians(got)
+ centres[tid] = (sum(p.lat for p in got) / len(got), sum(p.lon for p in got) / len(got))
+ parts = split_parts([t for t in ids if t in truth], [t for t in ids if t not in truth])
+ part_of = {t: n for n, p in enumerate(parts) for t in p}
+ os.makedirs(os.path.join(out_dir, "packets"), exist_ok=True)
+ for n, part in enumerate(parts, 1):
+ with open(os.path.join(out_dir, f"part-{n}.txt"), "w", encoding="utf-8") as f:
+ f.write("\n".join(part) + "\n")
+ pages = {}
+ if os.path.exists(PAGES):
+ with open(PAGES, encoding="utf-8") as f:
+ pages = json.load(f)
+ for tid in ids:
+ rec = recs[tid]
+ est = E.estimate(root, rec, params, fetch, refs)
+ comp = []
+ for other in comparables(tid, part_of, sorted(truth), meds, centres):
+ o = recs[other]
+ high, _low = M.high_low(info[other]["points"])
+ comp.append((o["name"], o.get("regions") or [],
+ _ft(statistics.median(p.elev_m for p in high)),
+ str((o.get("hike") or {}).get("season")), truth[other]))
+ text = packet_text(rec, info[tid], est["months"] or [], comp,
+ pages=_pages_text(pages.get(tid)),
+ precip=precip.get(tid))
+ with open(os.path.join(out_dir, "packets", f"{tid}.md"), "w", encoding="utf-8") as f:
+ f.write(text)
+ return len(ids)
+
+
+def _pages_text(entry):
+ if not entry:
+ return None
+ publishers = "; ".join(s["publisher"] for s in entry["sources"])
+ return f"Publisher(s): {publishers}\nMonths each gives: {entry.get('months_text', '')}"
+
+
+def cmd_packets(args):
+ fetch = E._fetch_with_cache(args.cache)
+ n = build_packets(ROOT, args.out, fetch, args.precip)
+ print(f"{n} packets written to {args.out}/packets")
+ return 0
+
+
+def cmd_score(args):
+ ids = refresh.trail_ids(ROOT)
+ truth = _truth(ROOT)
+ answers = {}
+ for path in args.answers:
+ got, problems = read_answers(path, ids)
+ for n, text in problems:
+ print(f"{path} line {n}: {text}")
+ answers.update(got)
+ figures = score(answers, truth)
+ t, m = figures["tested"], figures["matched"]
+ print(f"owner's measure (within one month at each end): {m} of {t} = {100 * m / t:.1f}%"
+ f" ({figures['unanswered']} unanswered)")
+ for c in CONFIDENCES:
+ v = figures["by_confidence"][c]
+ print(f" {c:<7} {v['matched']:>3} of {v['tested']:<3} = "
+ f"{100 * v['matched'] / v['tested'] if v['tested'] else 0:.1f}%")
+ if args.write:
+ write_blind_test(args.write, figures, args.date or datetime.date.today().isoformat())
+ print(f"written to {args.write}")
+ return 0
+
+
+def cmd_proposals(args):
+ n = proposals(ROOT, args.answers, args.pages, args.dir)
+ print(f"{n} proposals staged")
+ return 0
+
+
+def cmd_inputs(args):
+ fetch = E._fetch_with_cache(args.cache)
+ params = E.load_params(ROOT)
+ refs = E.references(ROOT, fetch)
+ doc = {}
+ for tid, rec in E._records(ROOT):
+ if (rec.get("hike") or {}).get("season_basis") == "estimate":
+ doc[tid] = E.inputs_signature(E.estimate(ROOT, dict(rec, id=tid), params, fetch, refs))
+ with open(args.write, "w", encoding="utf-8") as f:
+ json.dump(doc, f, indent=1, sort_keys=True)
+ f.write("\n")
+ print(f"inputs of {len(doc)} estimates written to {args.write}")
+ return 0
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = parser.add_subparsers(dest="command", required=True)
+ p = sub.add_parser("packets", help="write the packets and part lists")
+ p.add_argument("--out", required=True)
+ p.add_argument("--precip", default=None,
+ help="JSON {id: [twelve monthly mm for each sample point]}; optional")
+ p.add_argument("--cache", default=None)
+ p.set_defaults(func=cmd_packets)
+ p = sub.add_parser("score", help="score answer files against the sourced seasons")
+ p.add_argument("answers", nargs="+")
+ p.add_argument("--write", default=None, help="record the figures in this JSON file")
+ p.add_argument("--date", default=None)
+ p.set_defaults(func=cmd_score)
+ p = sub.add_parser("proposals", help="stage the judged seasons for refresh.py")
+ p.add_argument("--answers", default=JUDGED)
+ p.add_argument("--pages", default=PAGES)
+ p.add_argument("--dir", default=None)
+ p.set_defaults(func=cmd_proposals)
+ p = sub.add_parser("inputs", help="record the inputs of every estimate")
+ p.add_argument("--write", default=INPUTS)
+ p.add_argument("--cache", default=None)
+ p.set_defaults(func=cmd_inputs)
+ args = parser.parse_args(argv)
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/season_judged.tsv b/tools/season_judged.tsv
new file mode 100644
index 0000000..93518e6
--- /dev/null
+++ b/tools/season_judged.tsv
@@ -0,0 +1,223 @@
+across-utah-route 4,5,6,9,10 April to June and September to October medium Desert heat in summer and snow in the Henrys, La Sals and Bryce country in winter leave spring and fall.
+akshayuk-pass 7,8 July to August medium Arctic Baffin Island is frozen and snowbound until late June and freezes up again by September, so the walkable window is the two summer months.
+alexander-mackenzie 6,7,8,9 June to September medium Snow lingers on the Interior Plateau and Tweedsmuir highlands into June and autumn rain and early snow return in October.
+allegheny-trail 4,5,6,7,8,9,10 April to October medium Mid-elevation West Virginia mountains are mild and green from April to October, with winter snow and ice and summer humidity making the edges less pleasant.
+alpine-trail-7 7,8,9 July to September high Heavy winter snow at 7,000 feet in the Swan Range melts out by mid-July, and snow returns in October.
+american-discovery-trail 4,5,6,7,8,9,10 April to October low A coast-to-coast thru-hike starts in spring and must reach the Colorado and Sierra high ground in summer before autumn snow, so the whole route fits April to October.
+appalachian 3,4,5,6,7,8,9,10 March to October high A northbound thru-hike starts in March-April in Georgia and reaches Katahdin by September-October before Maine's snow, so the season spans March to October.
+appalachian-high-route 4,5,6,9,10 Spring and fall medium Mountain loop over 5,000-foot ridges in NC and TN where summer is hot and humid and winter is icy, so spring and fall are the comfortable windows.
+arizona 3,4,5,9,10,11 Spring and fall medium Low desert is too hot in summer and the high forest and Grand Canyon rim hold snow in winter, so thru-hikers go north from March to May or flip into fall.
+avon 4,5,6,7,8,9,10 April to October medium Winter snow and early-spring mud on Ontario farmland end with the thaw, and the walk runs until late fall.
+backbone 1,2,3,4,5,10,11,12 October to May medium Santa Monica Mountains chaparral is baking hot and dry from June to September, so the cool wetter months and spring wildflowers are the walking season.
+baker 4,5,6,9,10 April to June and September to October medium Humid, buggy summers and icy, muddy winters in western Pennsylvania make spring and fall the usual walking months.
+bartram 3,4,5,9,10,11 Spring and fall medium Blue Ridge route with summer heat and haze below and winter ice on the 5,000-foot balds, so spring and fall are best.
+basin-and-range-trail 4,5,9,10 Spring and fall high Nevada desert route with scorching summer heat and little water and snow on the high ranges in winter, so spring and fall are the windows.
+batona 3,4,5,9,10,11 March to May and September to November medium Flat Pine Barrens walking is best when it is cool, away from summer heat, ticks and biting flies.
+bay-circuit 3,4,5,9,10,11 March to May and September to November medium Humid, buggy summers and icy winters in low-lying eastern Massachusetts leave spring and fall, though it can be walked all year.
+bayou-state-trail 1,2,3,4,11,12 November to April medium Summer heat, humidity, mosquitoes and storms in Louisiana push hiking into the cool, dry winter and early spring.
+beartooth-high-route 7,8,9 July to September high Cross-country route at about 11,000 feet in the Beartooths where snow lingers into July and returns by late September, so only mid-summer works.
+benton-mackaye 3,4,5,9,10,11 Spring and fall medium Southern Appalachian ridges up to 5800 ft are pleasant in spring and fall, while summer is hot, humid and buggy and winter brings ice.
+big-bend-100 1,2,3,11,12 November to March high Chihuahuan Desert heat above 90F from May to September makes the cool months the only sensible window.
+big-seki-loop 7,8,9 July to September high High Sierra passes up to 13,000 ft hold snow into early July and fresh snow returns by October, leaving July to September.
+bigfoot-trail 7,8,9 July to September medium Klamath-Siskiyou high ground holds snow into June and gets heavy autumn rain from October, so the dry summer months fit.
+bitterroots-80-mile-route 7,8,9 July to September medium High Selway-Bitterroot ground near 7,900 ft holds snow into early July and fall snow returns by October.
+black-canyon 1,2,3,4,10,11,12 October to April high Sonoran Desert foothills are dangerously hot from May to September, so the cool months from October to April are the season.
+blue-mountains-trail 5,6,9,10 May to June and September to October low Hot dry summers in the canyons and snow in the Wallowas and Blues outside late spring and early fall limit the window, though high sections are fine in midsummer.
+border-route 5,6,7,8,9,10 Late May to October medium Northern Minnesota boundary-waters ridges are snow-bound and muddy until May and bugs peak in June and July, but the trail is walkable from May through fall.
+boreal-trail 6,7,8,9 June to September medium Saskatchewan boreal forest has long cold winters and is frozen into May, leaving the short warm summer for hiking.
+boundary-trail-mount-st-helens 7,8,9,10 July to October high Cascade ridges around 5,000 feet hold snow until July, and heavy rain starts in late October.
+boundary-trail-pasayten 7,8,9 July to September high The Pasayten high country at 5,500 to 7,500 feet is under snow until early July, and snow returns in October.
+brazeau-loop 7,8,9 July to September high Jasper's high passes and river fords need snowmelt to subside, so it is walkable from July until the first snow in September.
+bristol-hills-trail 5,6,7,8,9,10 May to October medium Snow and mud make winter and early spring uncommon for walking, so the comfortable months run from late spring through fall.
+brooks-range-traverse 6,7,8,9 June to September low Arctic tundra is frozen and snowbound most of the year, with river breakup in early June and freeze-up and snow by mid-September.
+bruce-trail 4,5,6,7,8,9,10 April to October medium The Niagara Escarpment is icy and muddy through winter and early spring, so end-to-end hikes run from the April thaw to the end of October.
+buckeye 3,4,5,9,10,11 Spring and fall medium Ohio summers are hot, humid and buggy and winters are cold and muddy, so spring and fall are the comfortable thru-hiking windows.
+california-coastal 4,5,6,7,8,9,10 April to October low The coast can be walked all year, but winter storms bring heavy rain in the north and leave some sections passable only at low tide, so a full walk suits the dry months.
+canol 7,8 July and August medium Mackenzie Mountains trail where snow lingers on the passes into late June and the first snow returns in early September, leaving July and August.
+centennial-sd 5,6,9,10 May to June and September to October medium Black Hills summer heat and thunderstorms and winter snow leave late spring and early fall as the best months.
+central-wilderness-grand-tour 6,7,8,9,10 June to October medium Mid-elevation Golden Trout Wilderness melts out early, but Coyote Lakes Pass and Kern crossings need low snow and low water, so summer through early fall.
+central-wind-rivers-loop 7,8,9 July to September high Wind River Range snow and swollen creeks persist until mid-July and winter returns by late September.
+chinese-wall-circuit 7,8,9 July to September high The Bob Marshall high country near 8,500 ft holds snow until July and gets fall snow by late September.
+circle-of-solitude 7,8,9 July to September high High passes like Colby, Avalanche and Forester stay snowbound and high-water crossings last into July, with autumn storms after September.
+cohos 6,7,8,9,10 June to October medium The pages differ: The Trek gives May to October and Backpacking Routes gives June to November. It was set by judgement from both and from the climate, since snow and mud last into late May and cold sets in by late October.
+colorado-trail 7,8,9 July to September high San Juan and Collegiate high ground above 12,000 ft is snow-covered until early July and snows again by late September.
+condor-trail 3,4,5,10,11 Spring and fall medium Los Padres coast ranges are very hot and dry from June to September and wet in midwinter, so spring and fall are the windows.
+conestoga-trail 3,4,5,9,10,11 March to May and September to November medium The low Lancaster County hills are hot, humid and tick-ridden in summer, so the cool months suit it best.
+conservation-trail 4,5,6,7,8,9,10 April to October medium Low-elevation western New York is snowy in winter and muddy in March, and can be walked from April until late fall.
+continental-divide 5,6,7,8,9,10 May to October medium A thru-hike must start north of the Mexican border after the desert winter and clear the San Juans, Wyoming and Montana high ground between the June snowmelt and the first October storms.
+corvallis-to-the-sea 5,6,7,8,9,10 May to October medium Very wet, muddy Coast Range winters push the walk into the drier months from late spring through early fall.
+cottonwood-trail 6,7,8,9 June to September medium Yukon mountain passes are snow-covered until June and cold and snowy again by late September, leaving the short summer.
+cranberry-lake-50 6,7,8,9,10 June to October medium Adirondack snow and mud in spring and black flies into June leave summer and fall as the usual window.
+cross-vermont 5,6,7,8,9,10 May to October medium A low-elevation route of mostly rail trail and quiet roads, where winter snow and mud season bracket a long snow-free stretch from May to October.
+dan-zhur-donjek 7,8 July to August medium Subarctic Kluane high country with glacial river crossings is snowbound until late June and snows again by early September.
+deadman-and-cloud-canyons 7,8,9 July to September high High Sierra passes like Elizabeth Pass and Colby Pass hold snow and stream crossings run high until July, and autumn storms begin in October.
+deadman-creek-loop 1,2,3,4,11,12 November to April medium Low Sonoran desert at about 2,200 ft reaches 90 to 100 F from May to September, so the walk belongs in the cool season.
+deseret-hiking-route 5,6,7,8,9,10 May to October low A route from southern Utah desert canyons to the Pioneer Mountains of Idaho needs the high ground clear of snow and the south not scorching.
+desert-trail 4,5,6,9,10 April to June and September to October low Waterless desert is too hot in summer and snowy in winter, so a full walk runs through spring and early fall.
+desert-winter-thru-hike 1,2,3,11,12 November to March medium Designed as a winter route through Sonoran, Colorado and Mojave deserts that are too hot from April through October.
+donut-hole 4,5,6,9,10 April to June and September to October low Unbridged streams run high in early spring, and the valleys are hot, humid and buggy in midsummer, so the shoulder months suit best.
+eagle-cap-traverse 7,8,9 July to September high Wallowa high passes near 7,000 ft hold snow until early July and fall storms arrive in October.
+east-beach-trail 5,6,7,8,9 May to September medium Haida Gwaii beach walking is best in the drier months, as heavy rain and storms dominate from October through winter.
+east-coast-trail 6,7,8,9 June to September medium Newfoundland's cold, foggy shoulder seasons and lingering snow and ice leave summer into early fall as the comfortable window.
+eastern-continental-trail 1,2,3,4,5,6,7,8,9,10 January to October low A thru-hike of about 300 days starts in the Florida winter and has to finish in the Gaspe before the November snows.
+eastern-sierra-high-route 7,8,9 July to September high Cross-country passes above 10,500 feet need the snow to have melted, which is from mid-July through September.
+finger-lakes 4,5,6,7,8,9,10 April to October medium The pages differ: one Trek page gives winter, spring, summer and fall, and a table on the same page gives spring, summer and fall. It was set by judgement from both and from the climate, since snow lies from December to March and early spring is muddy.
+florida 1,2,3,11,12 November to March high Subtropical heat, wet-season flooding and bugs from May to October make the cool dry months the thru-hiking season.
+foothills 3,4,5,9,10,11 Spring and fall medium Blue Ridge escarpment trail is comfortable in spring and fall, with hot humid summers and some winter ice at the higher end.
+fremont 6,7,8,9,10 June to October medium Oregon ridge route at 6,000 to 8,000 feet is snow-covered into early June and snowy again by November, with dry summers.
+ganaraska 4,5,6,7,8,9,10 April to October medium Southern Ontario is snowy in winter and muddy in March, and the trail can be walked from April until late fall.
+general-george-crook 4,5,6,9,10 April to June and September to October medium Rim country is snowy in winter, and the July and August monsoon brings lightning and storms, leaving spring and fall.
+georgia-loop 3,4,5,9,10,11 March to May and September to November medium The north Georgia mountains are hot, humid and stormy in summer and cold and icy on the ridges in winter.
+gila-centennial-loop 3,4,5,9,10,11 March to May and September to November medium Gila canyons at 6,000 feet are hot from June to August, with monsoon storms and flash floods, and cold in winter.
+gospel-hump-loop 7,8,9 July to September high Idaho subalpine ridges around 7,000 feet hold snow until late June and get snow again by October, so only summer into early fall works.
+grand-enchantment 3,4,5,10,11 March to May, and October to November low The route crosses hot Sonoran desert and 10,000 ft Mogollon peaks, so a spring or fall thru-hike avoids summer heat at low ground and winter snow high up.
+grand-moab-route 6,9,10 June and September to October low The route crosses 12,000-foot La Sal snow until June and desert canyons above 95F in July and August, which leaves early summer and fall.
+grand-sawtooth-loop 7,8,9 July to September high Sawtooth passes and lake basins hold snow into early July and fall storms return in late September.
+grand-teton-loop 7,8,9 July to September high Paintbrush Divide and Hurricane Pass hold snow into July and are snowy again by October, leaving July to September.
+grand-valley-trail 4,5,6,7,8,9,10 April to October medium A low-elevation southern Ontario footpath that can be walked in all but deep winter and the muddy early spring.
+great-basin-trail 4,5,6,9,10 April to June and September to October low Scarce water and 80 F summer heat in the valleys, plus winter snow on the ranges, favour spring and early fall.
+great-colorado-route 6,7,8,9 June to September medium A route linking fourteeners and passes above 12,000 ft needs the snow gone, so it runs from early summer into early fall.
+great-divide-trail 7,8,9 July to September high Alberta and BC Rockies passes stay snow-covered until early July and fresh snow returns in September, so thru-hikers walk July to mid-September.
+great-eastern 4,5,6,7,8,9,10 April to October low A very long Appalachian walk, started in spring in Alabama and carried through summer humidity and into fall to avoid winter in the north.
+great-plains-trail 5,6,7,8,9,10 May to October low A north-to-south prairie route from Saskatchewan to Texas is walked from late spring to fall, avoiding cold northern winters and heat in the south by timing.
+great-western-divide-loop 7,8,9 July to September medium Kaweah Gap and the Great Western Divide hold deep snow into early July, and autumn storms return by October.
+great-western-loop 4,5,6,7,8,9,10 April to October low A roughly 208-day circuit of western trails starts in spring from the Arizona desert and must clear the Sierra, Rockies and Cascades in summer before fall snow.
+green-river-lakes-titcomb-basin-loop 7,8,9 July to September high The northern Wind Rivers hold snow and high water into mid-July and get fall storms by late September.
+guadalupe-ridge-trail 3,4,10,11 Spring and fall medium Chihuahuan Desert lowlands are very hot from May to September and the ridge gets cold and windy in winter, so spring and fall are best.
+hayduke-trail 4,5,9,10 April to May and September to October medium Canyon country is too hot in summer and the Henry Mountains and Boulder snow in winter, so thru-hikers start in spring or fall.
+heart-lake-two-ocean-plateau-loop 7,8,9 July to September high Yellowstone's high backcountry has deep snow and high water into late June and returns to winter by October, so July to September is the window.
+high-country-pathway 5,6,7,8,9,10 May to October medium Northern Michigan forest is snowbound in winter and muddy in early spring, and walkable from May to October, with bugs the main summer complaint.
+high-sierra 7,8,9 July to September high Kaweah Gap and Whitney's high ground hold snow and run high streams until July, and autumn storms start in October.
+highlands 3,4,5,9,10,11 March to May and September to November medium The low New Jersey and New York Highlands ridges are hot, humid and buggy in summer and icy in midwinter.
+highline 4,5,6,9,10 April to June, and September to October medium Mogollon Rim at 6,000 ft is warm and dry in spring and fall, with summer monsoon storms in July and August and snow in winter.
+hoosier-heritage-trail 3,4,5,9,10,11 March to May and September to November medium Indiana has hot, humid summers with ticks and thick vegetation, so spring and fall are the most comfortable months.
+horse-shoe 3,4,5,9,10,11 March to May and September to November medium Southeast Pennsylvania has humid, buggy summers and icy winters, which leaves spring and fall.
+hot-springs-trail 4,5,6,7,8,9 April to September low A northbound route of about 110 days from coastal California to Idaho needs the Sierra and the northern mountains clear of snow, so it runs from spring to early fall.
+iat-newfoundland-labrador 6,7,8,9 June to September medium Western Newfoundland is cold, snowy and boggy until June, and storms and snow return in October.
+ice-age 5,6,7,8,9,10 May to October medium The pages differ: one Trek page gives summer and fall and another gives summer only. It was set by judgement from both and from the climate, since snow and mud last through April and a hard freeze comes by November.
+idaho-centennial 6,7,8,9 June to September medium Snow on the mountain sections lasts into June while the southern desert gets hot, so a north-bound walk runs June through September.
+international-appalachian-trail-maine 6,7,8,9,10 June to October medium Northern Maine is snowbound and muddy until late May and frozen from November, and fall is best once the bugs fade.
+island-walk 6,7,8,9,10 June to October medium Prince Edward Island is cold and wet in spring and late fall, so the walk is done in the warm months.
+itijjagiaq-trail 7,8 July to August medium Baffin Island's Katannilik park is frozen and used by skiers and snowmobilers until June, so summer hiking is limited to July and August before September freeze.
+john-muir 7,8,9 July to September high High Sierra passes above 11,000 ft are snow-choked until early July and storms and cold return in late September, so thru-hikes run July to September.
+kanab-canyon-loop 3,4,5,10,11 Spring and fall high Grand Canyon inner gorge is dangerously hot from June to September with monsoon storms, so spring and fall are the standard seasons.
+kings-canyon-high-basin-route 7,8,9 July to September high Off-trail travel over 12,000 ft passes needs the snow gone and stable weather, which only holds from July to September.
+knobstone 3,4,5,9,10,11 March to May and September to November medium Southern Indiana summers are hot, humid and tick-ridden, while the steep, leafless bluffs in the cool shoulder seasons are the draw.
+koroc-palmer-loop 7,8 July to August medium The Torngat Mountains in the Arctic are snowbound until late June and freeze again by September, leaving a short July and August window.
+la-cloche 6,7,8,9,10 June to October medium Killarney is snowbound in winter and buggy in spring, so the warm months are the main window, with September and early October the best.
+laurel-highlands 4,5,6,7,8,9,10 April to October medium Moderate Pennsylvania ridge at about 2,500 feet is snowy in midwinter but mild enough from April to October.
+lone-star 1,2,3,11,12 November to March high East Texas piney woods are hot, humid and buggy for much of the year, so the cool winter months are the hiking season.
+long-path 4,5,6,9,10 April to June and September to October medium Humid, buggy summers and icy winters in the Hudson Valley and Catskills favour spring and fall.
+long-trail 6,7,8,9,10 June to October high Green Mountain ridges are muddy and snowy until late May and wintry by November, so thru-hikers walk June to October.
+lost-coast 5,6,7,8,9 May to September high Heavy winter rain, slides and high tides make parts of the coast impassable, so the dry months with workable low tides are used.
+lowest-to-highest-route 5,6,10 Late May to June, or October low Badwater is lethal in summer heat while Whitney holds snow until June, so the route fits a narrow window in late spring or early fall.
+loyalsock 4,5,6,9,10 April to June and September to October medium Rocky, wet terrain in northern Pennsylvania is best in the cool shoulder seasons, before the humid, buggy summer.
+maah-daah-hey 5,6,9,10 May to June and September to October medium Badlands clay turns to impassable gumbo when wet and summer is hot, so late spring and early fall are the usual months.
+maricopa-trail 1,2,3,4,10,11,12 October to April high Phoenix-area Sonoran Desert is above 95F from May to September, so the cool months from October to April are the season.
+mason-dixon 3,4,5,9,10,11 March to May and September to November medium The low Susquehanna valley is hot and humid in summer, so the cool spring and fall months suit best.
+massanutten 3,4,5,9,10,11 Spring and fall medium Virginia ridge circuit with hot humid summers and cold winters, so spring and fall are most comfortable.
+mattabesett 3,4,5,9,10,11 Spring and fall medium Low Connecticut traprock ridges are best in spring and fall, with summer humidity, heat and ticks and some winter ice on ledges.
+metacomet-monadnock 4,5,6,9,10 Spring and early summer, and fall low New England ridge walking is cold and icy in winter and humid and buggy in midsummer, so spring and fall are favoured.
+mid-state 4,5,6,7,8,9,10 April to October medium Pennsylvania ridge and plateau trail at about 2,000 feet is snowy in winter but fine from April to October, with summer humidity and ticks.
+middle-fork-kings-river 7,8,9 July to September high Muir Pass and Hell-for-Sure Pass hold snow into early July and storms return in autumn, so July to September.
+middle-fork-trail 6,7,8,9,10 June to October low Idaho river canyon and high bench trail clears of snow in June and gets cold wet weather by November, though low canyon heat peaks in July.
+midland-to-mackinac-trail 6,7,8,9,10 June to October medium Snow and mud last into April in northern Michigan, and the walk is comfortable from June through early fall.
+midstate-ma 4,5,6,9,10,11 April to June and September to November medium The gentle central Massachusetts hills are pleasant in spring and fall, with humid, buggy summers and cold, icy winters.
+milestone-basin-and-the-upper-kern 7,8,9 July to September high Sierra passes above 10,000 ft and Kern fords stay snowy and high into early July, with autumn storms returning in October.
+mogollon-rim-trail 4,5,9,10 April to May and September to October low Low desert sections reach 90 F by June and the White Mountains and Blue Range hold snow in winter, so spring and fall fit a full crossing.
+mojave-sonoran-trail 1,2,3,11,12 November to March high Colorado River desert lowlands reach 100F from May to September, so the cool winter months are the only practical window.
+monadnock-sunapee 6,7,8,9,10 June to October medium New Hampshire snow, mud and black flies linger into early June and the summit ridges are snowy from late fall.
+montana-trail 6,7,8,9 June to September low A 90-to-122-day crossing from the Divide to the plains starts after mountain snow clears in June and aims to finish before winter on the Missouri breaks.
+mountains-to-sea 3,4,5,9,10,11 March to May and September to November medium High Smokies and Blue Ridge are cold in winter while the Piedmont and coast are hot and humid in summer, so cool shoulder seasons suit a full walk.
+nankoweap-bright-angel-loop 5,9,10 May and September to October low The Grand Canyon inner canyon is dangerously hot from June to August and the North Rim road is snowed in over winter, leaving late spring and early fall.
+nepisiguit-migmaq-trail 6,7,8,9 June to September medium Northern New Brunswick is snowy and muddy through May and cold by October, with river and bug conditions favouring summer.
+new-england 4,5,6,9,10 April to June and September to October medium Traprock ridges are cold and icy in winter and hot, humid and buggy in July and August, so spring and fall suit best.
+north-boundary 7,8,9 July to September medium Snake Indian Pass and the Smoky River crossings need snowmelt in the Jasper backcountry, and winter returns by October.
+north-country 5,6,7,8,9,10 May to October low A thru-hike across the northern states starts after the North Dakota spring thaw and must finish before winter sets in the Adirondacks and Vermont by late October.
+north-south 3,4,5,9,10,11 March to May and September to November medium Rhode Island woods are humid and buggy in summer and cold in winter.
+north-south-lbl 3,4,5,9,10,11 March to May and September to November medium The forests of western Kentucky and Tennessee are hot, humid and tick-ridden in summer, so spring and fall are favoured.
+north-umpqua 6,7,8,9,10 June to October medium The upper Cascade sections near 6,000 feet hold snow into June and see heavy rain and snow from late October, though the river canyon can be walked earlier.
+northern-colorado-trail 7,8,9 July to September medium Flat Tops and Rocky Mountain high ground above 11,000 ft is snowbound until early July and snows again by late September.
+northern-new-mexico-loop 6,7,8,9,10 June to October low The Sangre de Cristo and Jemez high ground holds snow into June, and lower desert stretches are hot in midsummer, so a whole loop fits June to October.
+northville-placid 6,7,8,9,10 June to October medium Adirondack wilderness trail is wet, snowy and muddy until late May, with black flies in May and June and cold weather by late October.
+oak-ridges 4,5,6,7,8,9,10 April to October medium The southern Ontario moraine is snowy and muddy over winter and can be walked from April until late fall.
+ocean-to-lake 1,2,3,11,12 November to March high South Florida is hot, wet and buggy from May to October with flooded swamp and prairie, so the cooler dry months are used.
+oregon-coast 5,6,7,8,9 May to September medium The coast gets 10-16 inches of rain a month from November to March and the drier months from May to September make beach walking and creek crossings workable.
+oregon-desert 4,5,6,9,10 Spring and fall medium High desert at 3,000-8,000 ft is hot and waterless in July and August and cold in winter, so spring and fall are the walking windows.
+ottawa-temiskaming-highland-trail 6,7,8,9,10 June to October medium Northeastern Ontario forest is snowbound and muddy until May, with black flies in early summer, and cold by November.
+ouachita 3,4,5,10,11 October to November and March to May medium The pages differ: one gives April to November, one gives late October to late March, and one gives all year. It was set by judgement from all three and from the climate, since summers are hot and humid with ticks and winters are cold but walkable.
+ozark-highlands 3,4,5,10,11 Spring and fall medium Arkansas Ozark summers are hot, humid and buggy and winters are cold but popular for leaf-off views, so spring and fall are the typical seasons.
+ozark-trail 3,4,5,9,10,11 March to May and September to November medium The pages differ: one Trek page gives spring or fall and another adds winter. It was set by judgement from both and from the climate, since the heat, humidity and ticks of July and August make summer a poor choice.
+pacific-crest 4,5,6,7,8,9,10 April to October medium A thru-hike starts at the desert border in April or May, crosses the Sierra after the June to July snowmelt, and must finish the Washington Cascades by early October.
+pacific-northwest 7,8,9 July to September medium An east-to-west thru-hike starts in Glacier after the snow clears in early July and must finish through the wet Olympic coast before October rain and early snow.
+paumanok-path 3,4,5,9,10,11 March to May and September to November medium Long Island is humid and tick-heavy in summer, and the pine barrens are pleasant in the cool shoulder seasons.
+pfiffner-traverse 7,8,9 July to September high A Continental Divide crest route above 11,000 feet with off-trail passes needs the snow gone, which is from July until the first big September storms.
+pinhoti 3,4,5,10,11 Spring and fall medium Alabama and Georgia hills are hot and humid from June to September, and winter is wet and cold, so spring and fall are best.
+powell-plateau-loop 5,9,10 May and September to October low The Grand Canyon's North Rim access is snowed in until May and the inner canyon is very hot in June to August, leaving late spring and early fall.
+prescott-circle 3,4,5,9,10,11 March to May and September to November medium Prescott's high desert is hot in June to August with monsoon storms in July and August, while winters are cool but usually walkable, so shoulder seasons are best.
+ptarmigan-glenns-lake-highline-loop 7,8,9 July to September high Glacier's Ptarmigan Tunnel, Stoney Indian Pass and Highline are snow-blocked until mid-July and the first snows come in late September.
+quehanna 4,5,6,7,8,9,10 April to October medium Pennsylvania state forest trail at about 2,000 ft is walkable from April to October, with winter snow and March mud outside the season.
+rae-lakes-loop 7,8,9 July to September high Glen Pass at 11,978 ft keeps snow into early July and the Kings River crossings run high, with autumn storms after September.
+rideau-trail 4,5,6,7,8,9,10 April to October medium Eastern Ontario is snowy and muddy over winter, and the trail can be walked from April until late fall.
+ring-the-peak 6,7,8,9,10 June to October low A loop around Pikes Peak that mixes stretches near 11,000 feet with lower trails, and is snow-free from about June to October.
+river-to-river 3,4,5,10,11 Spring and fall medium Southern Illinois summers are hot, humid and buggy, with trailside poison ivy and ticks, so spring and fall are the comfortable seasons.
+route-in-between 4,5,6,7,8,9,10 April to October low A Mexico-to-Canada link route through Arizona desert, Utah canyons and Idaho mountains has to chain a spring start with high Idaho snow clearing by summer and finishing before fall.
+rutherford-lake-loop 7,8,9 July to September high Yosemite's south boundary passes at over 9,000 feet hold snow until early July, and autumn storms begin in October.
+san-diego-trans-county-trail 1,2,3,4,11,12 November to April medium The Salton Sea end and the desert washes are over 100F in summer, so the cool months are used, with the 4,900-foot mountains still mild in winter.
+santa-fe-to-taos 7,8,9 July to September medium Sangre de Cristo peaks near 12,000 ft are snowbound until late June and afternoon monsoon storms peak in July and August.
+sawtooth-wilderness-high-route 7,8,9 July to September high Mostly cross-country passes near 9,000 feet and above need the snow gone, which is from mid-July through September.
+sea-to-sea-route 4,5,6,7,8,9,10 April to October low A 7,775-mile coast-to-coast network across the northern prairie, the Rockies and the Cascades can only be walked from spring thaw to autumn snow.
+selway-river-trail 4,5,6,9,10 Spring and fall medium A low river canyon at 2,000 to 3,000 feet is free of snow early but reaches the mid-80s with fire risk in July and August, so spring and early fall are used.
+sentier-international-appalaches 6,7,8,9 June to September medium Gaspesie's Chic-Choc summits keep snow into June and the cold and snow return in October, so summer is the window.
+shawangunk-ridge-trail 3,4,5,9,10,11 March to May and September to November medium A Hudson Valley ridge with humid, buggy summers and icy winters, so spring and fall are the most comfortable months.
+sheltowee-trace 3,4,5,10,11 Spring and fall medium Kentucky's Daniel Boone National Forest is hot, humid and buggy in summer and cold in winter, so spring and fall are best.
+shenipsit-trail 3,4,5,9,10,11 March to May and September to November medium Central Connecticut has humid, buggy summers and cold, icy winters, so spring and fall are best.
+sierra-grand-traverse 7,8,9 July to September high Over 40 passes between 9,000 and 12,000 ft are snow-covered until July, and fall storms close the high country by October.
+sierra-high-route 7,8,9 July to September high The pages differ: Backpacking Routes gives late July to mid-September, and Skurka warns the route is off-limits to all but expert mountaineers from November through May. It was set by judgement from both and from the climate at the passes, which are near 12,000 feet.
+silver-moccasin-trail 4,5,6,10,11 April to June and October to November medium San Gabriel low canyons exceed 85 F in midsummer and Mount Baden-Powell is snowy in winter, so spring and autumn suit best.
+siskiyou-peaks-trail 7,8,9 July to September medium The summits and cirque lakes are snowbound until late June, and Shasta is climbed in summer.
+sky-islands-traverse 3,4,5,9,10,11 March to May and September to November low Summer heat and the July and August monsoon storms in southeastern Arizona push the walk into spring and fall.
+solitude-loop 7,8,9 July to September high Cloud Peak Wilderness at 9,000 to 11,000 feet holds snow into early July, and winter storms return in late September.
+south-boundary 7,8,9 July to September high Jasper's Cairn and Rocky passes near 6,000 ft and glacial river fords need snowmelt and low water, so early July to mid-September.
+south-lake-to-north-lake 7,8,9 July to September high Bishop, Muir and Piute passes above 11,000 ft hold snow into early July and storms return in late September.
+southeastern-serpentine-trail 3,4,5,10,11 Spring and fall medium A 30-35 day link of southern Appalachian trails is walked in spring and fall to dodge summer heat, humidity and bugs and winter ice on the higher sections.
+southern-sierra-high-route 7,8,9 July to September high Cross-country passes above 12,000 ft near Whitney hold snow into July and storms return by late September.
+southwestern-horseshoe 3,4,5,9,10,11 Spring and fall low Joining the Hayduke, Arizona and Grand Enchantment trails across Utah, Arizona and New Mexico desert means spring or fall to avoid summer heat and monsoon, with the highest ground snow-free by late spring.
+standing-stone 4,5,6,9,10 April to June and September to October medium Humid, buggy summers and icy winters on the Pennsylvania ridges leave spring and fall as the usual window.
+stein-valley-traverse 7,8,9 July to September medium The traverse tops out around 7,000 feet, where snow lingers into July, and heavy rain starts in October.
+sunapee-ragged-kearsarge 6,7,8,9,10 June to October medium New Hampshire snow and mud last into spring and black flies into early June, with foliage-season walking into early October.
+sunshine-coast 6,7,8,9 June to September medium The coast is drenched by 8-14 inches of rain a month from October to March and the mountaintop sections hold snow until June, so the dry summer months are the season.
+superior-hiking 5,6,7,8,9,10 May to October medium Lake Superior's North Shore is snowy and cold from November to April and buggy in June and July, so May to October with September and October favoured.
+susquehannock 5,6,7,8,9,10 May to October medium Northern Pennsylvania plateau stays snowy and wet through April, so late spring through early fall is the walking season.
+sycamore-canyon-az 3,4,10,11 March to April and October to November medium Low canyon country at 3,800 ft tops 90 F from June to September, so the loop belongs in the cooler spring and fall months.
+tahoe-rim 6,7,8,9,10 June to October medium The 10,000 ft ridgelines are snow-covered into June and again from late October, so thru-hikers walk from about late June to early October.
+tahoe-yosemite-trail 7,8,9 July to September high High Sierra passes up to about 10,000 feet hold snow until early July, and fall storms arrive in October.
+teton-crest 7,8,9 July to September high Crest passes above 10,000 feet hold snow until mid-July and storms and snow return by late September or October.
+teton-crest-route 7,8,9 July to September high Crest passes up to 10,700 ft hold snow into July and are wintry again by October, so July to September.
+teton-range-traverse 7,8,9 July to September high The Teton crest and Yellowstone Plateau are snow-covered until early July and wintry again by October, so July to September.
+teton-wilderness-loop 7,8,9 July to September high Two Ocean Pass and the Yellowstone River fords need snowmelt runoff to drop, which comes in mid-July, and fall storms arrive in late September.
+thames-valley-trail 5,6,7,8,9,10 May to October low Southwestern Ontario farmland trail is muddy and cold in early spring and snow-covered in winter, so it is walked from late spring to fall.
+thorofare-and-south-boundary-trail 7,8,9 July to September high Remote Yellowstone backcountry with deep snow and high river fords until early July, and snow returns in October.
+timberline 7,8,9 July to September high Mount Hood's snowfields and glacial stream crossings are at their best from mid-July through September before heavy autumn rain returns.
+toiyabe-crest 7,8,9 July to September medium Nevada crest at 10,000 feet is snow-covered into late June and cold again by October, leaving the dry summer.
+tonto-trail 1,2,3,4,11,12 November to April medium The Grand Canyon Tonto Platform is 90-100F from May to September with scarce water, so the cool months from November to April are the walking season.
+trans-adirondack-route 6,7,8,9,10 June to October low Adirondack wilderness with deep snow and mud into May, black flies in May and June, and winter returning in November.
+traversee-charlevoix 6,7,8,9,10 June to October medium The guided cabin crossing runs from after the Quebec thaw and black-fly peak through early October, avoiding the snowbound winter.
+tuscarora 3,4,5,9,10,11 March to May and September to November medium The Ridge and Valley Appalachians are hot, humid and buggy in summer and icy in winter, so spring and fall are the comfortable months.
+uinta-highline 7,8,9 July to September high Most of the trail is above 10,000 ft over 12,000 ft passes, so snow keeps it closed until early July and storms return by late September.
+vagabond-loop 3,4,5,6,7,8,9,10 March to October low A 3,500-mile circuit of Arizona, Utah, Colorado and New Mexico must start in the desert in early spring and cross the high Colorado Trail country in summer, before fall snow.
+vancouver-island 6,7,8,9 June to September medium Heavy Pacific rain from October to April and snow on the high alpine sections make early summer to September the window.
+vancouver-island-backbone 7,8,9 July to September medium Alpine ridges in the island interior hold snow until July and wet autumn storms begin in October; the packet's low elevation looks like a location error.
+warrior-trail 3,4,5,9,10,11 March to May and September to November medium Farmland ridges in southwestern Pennsylvania are overgrown, humid and buggy in summer and icy in winter.
+wasatch-traverse 7,8,9 July to September low The high Wasatch ridges and off-trail sections hold snow until late June and get early autumn storms, so midsummer fits a whole traverse.
+washington-coast-trail 5,6,7,8,9 May to September high Heavy rain from October to April and tide-dependent headlands make the drier months from May to September the usual window.
+waskahegan 5,6,7,8,9,10 May to October low Edmonton-area farmland and parkland is snow-covered and muddy from November to April, and walked from late spring to early fall.
+west-coast-trail 5,6,7,8,9 May to September high The trail is only open and reservable from May to September because of heavy autumn to spring rain and storms.
+western-uplands 5,6,7,8,9,10 May to October medium The Algonquin backcountry is frozen and snowy into April, buggy in late spring and cold by late October.
+wind-river-high-route-dixon-wilson 7,8,9 July to September medium Days above 10,000 ft on the Divide need the snow gone, which happens in mid-July, and storms return in September.
+wind-river-high-route-skurka 7,8,9 July to September high A mostly off-trail route at 10,000-12,000 ft with snowfields and big stream fords needs melt-out, which comes in mid-July and ends with September storms.
+wind-river-highline-trail 7,8,9 July to September high Bridger Wilderness benchlands and passes hold snow and high water into early July and winter returns by late September.
+wonderland 7,8,9 July to September high Mount Rainier's high ground keeps snow into July and heavy autumn rain begins in October, so mid-July to September is the window.
+wyoming-range 7,8,9 July to September high Crest-top trail at 9,000 ft or more is snowbound until early July and snows again by late September.
+yosemite-high-route 7,8,9 July to September high Mostly off-trail at 8,000 to 11,000 feet, so snowmelt, high stream crossings and early snow limit it to July through September.
+yosemite-high-sierra-camp-loop 7,8,9 July to September high Tuolumne's high passes and the camps are snow-bound until late June and shut for the season by early September, so July to September.
diff --git a/tools/season_judged_pages.json b/tools/season_judged_pages.json
new file mode 100644
index 0000000..4798f11
--- /dev/null
+++ b/tools/season_judged_pages.json
@@ -0,0 +1,98 @@
+{
+ "sierra-high-route": {
+ "why": "The pages differ: Backpacking Routes gives late July to mid-September, and Skurka warns the route is off-limits to all but expert mountaineers from November through May. It was set by judgement from both and from the climate at the passes, which are near 12,000 feet.",
+ "months_text": "The Skurka page says the route is probably off-limits to all but the most experienced mountaineers from November through May and lists hazards by month; Backpacking Routes gives late July to mid-September",
+ "sources": [
+ {
+ "url": "https://andrewskurka.com/adventures/sierra-high-route/logistical-considerations/",
+ "publisher": "Andrew Skurka",
+ "quote": "For all but the most experienced mountaineers, the SHR is probably off-limits from November through May"
+ },
+ {
+ "url": "https://backpackingroutes.com/sierra-high-route/",
+ "publisher": "Backpacking Routes",
+ "quote": "The best time to hike the Sierra High Route is late July to mid-September."
+ }
+ ]
+ },
+ "cohos": {
+ "why": "The pages differ: The Trek gives May to October and Backpacking Routes gives June to November. It was set by judgement from both and from the climate, since snow and mud last into late May and cold sets in by late October.",
+ "months_text": "The Trek 5-10; Backpacking Routes 6-11",
+ "sources": [
+ {
+ "url": "https://thetrek.co/10-trails-can-find-long-distance-solitude-2020/",
+ "publisher": "The Trek",
+ "quote": "Thru-hiking season : May to October"
+ },
+ {
+ "url": "https://backpackingroutes.com/cohos-trail/",
+ "publisher": "Backpacking Routes",
+ "quote": "Season : Summer , Fall"
+ }
+ ]
+ },
+ "ouachita": {
+ "why": "The pages differ: one gives April to November, one gives late October to late March, and one gives all year. It was set by judgement from all three and from the climate, since summers are hot and humid with ticks and winters are cold but walkable.",
+ "months_text": "The Hiking Life 4-11; Backpacking Routes 10-3; The Trek 1-12",
+ "sources": [
+ {
+ "url": "https://thehikinglife.com/2014/07/ouachita-trail/",
+ "publisher": "The Hiking Life",
+ "quote": "Season : April to November."
+ },
+ {
+ "url": "https://backpackingroutes.com/ouachita-trail/",
+ "publisher": "Backpacking Routes",
+ "quote": "Late October through late March is very possible, with the bulk of the hikers hitting it in November."
+ },
+ {
+ "url": "https://thetrek.co/10-trails-can-find-long-distance-solitude-2020/",
+ "publisher": "The Trek",
+ "quote": "Thru-hiking season: Year-round"
+ }
+ ]
+ },
+ "ice-age": {
+ "why": "The pages differ: one Trek page gives summer and fall and another gives summer only. It was set by judgement from both and from the climate, since snow and mud last through April and a hard freeze comes by November.",
+ "months_text": "The Trek list 6-11; The Trek article 6-8",
+ "sources": [
+ {
+ "url": "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/",
+ "publisher": "The Trek",
+ "quote": "Hiking season: Summer, Fall"
+ },
+ {
+ "url": "https://thetrek.co/the-best-time-of-year-to-hike-these-23-popular-long-trails/",
+ "publisher": "The Trek",
+ "quote": "The Ice Age Trail Best Time: Summer"
+ }
+ ]
+ },
+ "ozark-trail": {
+ "why": "The pages differ: one Trek page gives spring or fall and another adds winter. It was set by judgement from both and from the climate, since the heat, humidity and ticks of July and August make summer a poor choice.",
+ "months_text": "The Trek article 3-5 and 9-11; The Trek list 12-5 and 9-11",
+ "sources": [
+ {
+ "url": "https://thetrek.co/the-best-time-of-year-to-hike-these-23-popular-long-trails/",
+ "publisher": "The Trek",
+ "quote": "Best Time: Spring or Fall"
+ },
+ {
+ "url": "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/",
+ "publisher": "The Trek",
+ "quote": "Hiking season: Winter, Spring, Fall"
+ }
+ ]
+ },
+ "finger-lakes": {
+ "why": "The pages differ: one Trek page gives winter, spring, summer and fall, and a table on the same page gives spring, summer and fall. It was set by judgement from both and from the climate, since snow lies from December to March and early spring is muddy.",
+ "months_text": "The Trek trail entry 1-12; The Trek table 3-11",
+ "sources": [
+ {
+ "url": "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/",
+ "publisher": "The Trek",
+ "quote": "Hiking season: Winter, Spring, Summer, Fall"
+ }
+ ]
+ }
+}
diff --git a/tools/tests/test_estimate_season.py b/tools/tests/test_estimate_season.py
index dcadec9..69565b2 100644
--- a/tools/tests/test_estimate_season.py
+++ b/tools/tests/test_estimate_season.py
@@ -384,35 +384,88 @@ class ProposeCheckTest(unittest.TestCase):
("aaa", "Aaa", {"extra_hike": months_extra + self.ENDS}),
])
+ EST = ('season = "All year"\n'
+ 'months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n'
+ 'season_basis = "estimate"\n'
+ 'season_method = "Judged from climate. Confidence: low."\n')
+
+ def blind_doc(self, root, share=0.77, tested=100):
+ matched = int(round(share * tested))
+ doc = {"date": "2026-11-20", "tested": tested, "matched": matched,
+ "share": round(matched / tested, 2),
+ "by_confidence": {
+ "high": {"tested": tested, "matched": matched,
+ "share": round(matched / tested, 2)},
+ "medium": {"tested": 0, "matched": 0, "share": 0.0},
+ "low": {"tested": 0, "matched": 0, "share": 0.0}}}
+ with open(os.path.join(root, "tools", "season_blind_test.json"), "w") as f:
+ json.dump(doc, f)
+
+ def record_inputs(self, root, tid="aaa", **change):
+ params = E.load_params(root)
+ rec = E.refresh.load_toml(os.path.join(root, tid, "trail.toml"))
+ sig = E.inputs_signature(E.estimate(root, dict(rec, id=tid), params, mild_fetch,
+ E.references(root, mild_fetch)))
+ sig.update(change)
+ with open(os.path.join(root, "tools", "season_inputs.json"), "w") as f:
+ json.dump({tid: sig}, f)
+
+ def checked_repo(self, tmp, **kw):
+ root = self.est_repo(tmp, self.EST)
+ self.fit_doc(root)
+ self.blind_doc(root, **kw)
+ return root
+
def test_check_passes_when_nothing_changed(self):
- import tempfile, shutil
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
- root = self.est_repo(
- tmp,
- 'season = "All year"\n'
- 'months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n'
- 'season_basis = "estimate"\nseason_method = "Estimated."\n')
- self.fit_doc(root)
+ root = self.checked_repo(tmp)
+ E._REFS.clear()
+ self.record_inputs(root)
ok, lines = E.check(root, mild_fetch)
self.assertTrue(ok, lines)
- def test_check_names_the_trail_whose_estimate_changed(self):
- import tempfile, shutil
+ def test_check_flags_an_estimate_whose_machine_estimate_changed(self):
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
- root = self.est_repo(
- tmp,
- 'season = "June to July"\nmonths = [6, 7]\n'
- 'season_basis = "estimate"\nseason_method = "Estimated."\n')
- self.fit_doc(root)
+ root = self.checked_repo(tmp)
+ E._REFS.clear()
+ self.record_inputs(root, machine=[6, 7])
ok, lines = E.check(root, mild_fetch)
self.assertFalse(ok)
- self.assertTrue(any("aaa" in line and "[6, 7]" in line
+ self.assertTrue(any("aaa" in line and "inputs changed" in line and "[6, 7]" in line
for line in lines), lines)
+ def test_check_flags_an_estimate_whose_climate_digest_changed(self):
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.checked_repo(tmp)
+ E._REFS.clear()
+ self.record_inputs(root, digest="0" * 16)
+ ok, lines = E.check(root, mild_fetch)
+ self.assertFalse(ok)
+ self.assertTrue(any("aaa" in line and "inputs changed" in line for line in lines), lines)
+
+ def test_check_flags_an_estimate_with_no_recorded_inputs(self):
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.checked_repo(tmp)
+ E._REFS.clear()
+ ok, lines = E.check(root, mild_fetch)
+ self.assertFalse(ok)
+ self.assertTrue(any("aaa" in line and "no inputs are recorded" in line for line in lines), lines)
+
+ def test_check_fails_when_the_blind_test_is_under_the_bar(self):
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.checked_repo(tmp, share=0.6)
+ E._REFS.clear()
+ self.record_inputs(root)
+ ok, lines = E.check(root, mild_fetch)
+ self.assertFalse(ok)
+ self.assertTrue(any("blind test" in line for line in lines), lines)
+
def test_check_fails_when_the_fit_got_worse(self):
- import tempfile, shutil
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
# one sourced trail that mild all-year normals cannot match
@@ -420,32 +473,31 @@ class ProposeCheckTest(unittest.TestCase):
'season_basis = "source"\n' + self.ENDS)
root = self.repo_with(tmp, [("only", "Only", {"extra_hike": extra})])
self.fit_doc(root, within1=4, n=4)
+ self.blind_doc(root)
+ E._REFS.clear()
ok, lines = E.check(root, mild_fetch)
self.assertFalse(ok)
self.assertTrue(any("fit got worse" in line for line in lines), lines)
- def test_proposals_collect_cleanly(self):
- import tempfile, shutil, csv
+ def test_the_estimates_command_lists_only_estimates(self):
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
- root = self.repo_with(tmp, [("aaa", "Aaa", {"extra_hike": self.ENDS})])
- stage = os.path.join(tmp, "stage")
- os.makedirs(os.path.join(stage, "season"))
- reviewed = os.path.join(stage, "season", "estimates.reviewed.csv")
- with open(reviewed, "w", newline="") as f:
- w = csv.writer(f)
- w.writerow(["id", "proposed_months", "phrase", "kind", "flags",
- "comparable", "comparable_phrase", "note"])
- w.writerow(["aaa", "6 7 8 9", "June to September", "ends",
- "no-track", "", "", ""])
- self.assertEqual(E.proposals(root, reviewed, stage), 1)
- code, out = TR.main(root, "--dir", stage, "collect")
- self.assertEqual(code, 0, out)
- import refresh as R
- coll = R.load_toml(os.path.join(stage, "collected.toml"))
- props = coll["proposal"]
- self.assertEqual(len(props), 1)
- self.assertEqual(props[0]["status"], "proposed", out)
+ root = self.repo_with(tmp, [
+ ("aaa", "Aaa", {"extra_hike": self.EST + self.ENDS}),
+ ("bbb", "Bbb", {"extra_hike": 'season = "June"\nmonths = [6]\n'
+ 'season_basis = "source"\n' + self.ENDS}),
+ ])
+ self.assertEqual(E.estimates(root), ["aaa"])
+
+ def test_a_season_with_a_method_is_not_a_sourced_season(self):
+ tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, tmp, True)
+ root = self.repo_with(tmp, [
+ ("aaa", "Aaa", {"extra_hike": 'season = "June"\nmonths = [6]\nseason_basis = "sources"\n'
+ 'season_method = "The pages differ. Confidence: low."\n' + self.ENDS}),
+ ])
+ E._PHRASES.clear()
+ self.assertEqual(E._phrases(root), {})
class SeasonKindTest(unittest.TestCase):
diff --git a/tools/tests/test_season_judge.py b/tools/tests/test_season_judge.py
new file mode 100644
index 0000000..b9e61b7
--- /dev/null
+++ b/tools/tests/test_season_judge.py
@@ -0,0 +1,290 @@
+"""Tests for tools/season_judge.py: the packets reviewers judge a season from,
+the blind scoring, and the proposals that write the judged seasons.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import json
+import os
+import shutil
+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 season_judge as J # noqa: E402
+import season_climate as C # noqa: E402
+import season_model as M # noqa: E402
+import estimate_season as E # noqa: E402
+import test_refresh as TR # noqa: E402
+import refresh as R # noqa: E402
+import trail_history # noqa: E402
+import validate as V # noqa: E402
+
+
+class CleanTest(unittest.TestCase):
+ def test_a_sentence_that_bears_on_timing_is_removed_and_logged(self):
+ kept, removed = J.clean("A pretty ridge walk. Best in July and August. It has huts.")
+ self.assertEqual(kept, "A pretty ridge walk. It has huts.")
+ self.assertEqual(removed, ["Best in July and August."])
+
+ def test_season_words_count_but_place_names_do_not(self):
+ self.assertTrue(J.mentions_season("Snowmelt comes late."))
+ self.assertTrue(J.mentions_season("Open year-round."))
+ self.assertFalse(J.mentions_season("It crosses May Lake and Summer Lake."))
+ self.assertFalse(J.mentions_season("It passes the Hot Springs."))
+
+ def test_nothing_left_is_said_so(self):
+ kept, _ = J.clean("Best in summer.")
+ self.assertEqual(kept, "")
+ self.assertIn("none left", J.shown(kept, "x"))
+ self.assertEqual(J.shown("", None), "(not on file)")
+
+
+class SplitTest(unittest.TestCase):
+ def test_parts_are_disjoint_balanced_and_repeatable(self):
+ src = [f"s{i}" for i in range(10)]
+ oth = [f"o{i}" for i in range(7)]
+ parts = J.split_parts(src, oth, 3, 1)
+ flat = [t for p in parts for t in p]
+ self.assertEqual(sorted(flat), sorted(src + oth))
+ for part in parts:
+ self.assertIn(sum(t in src for t in part), (3, 4))
+ self.assertIn(sum(t in oth for t in part), (2, 3))
+ self.assertEqual(parts, J.split_parts(src, oth, 3, 1))
+ self.assertNotEqual(parts, J.split_parts(src, oth, 3, 2))
+
+
+def med(base):
+ return ([base] * 12, [base] * 12)
+
+
+class ComparablesTest(unittest.TestCase):
+ def test_a_trail_is_never_compared_with_its_own_part_or_itself(self):
+ part_of = {"me": 0, "mate": 0, "a": 1, "b": 2}
+ meds = {k: med(10.0) for k in part_of}
+ centres = {k: (45.0, -110.0) for k in part_of}
+ got = J.comparables("me", part_of, ["mate", "a", "b", "me"], meds, centres, k=10)
+ self.assertEqual(sorted(got), ["a", "b"])
+
+ def test_the_nearest_in_climate_and_place_come_first(self):
+ part_of = {"me": 0, "near": 1, "far": 1, "cold": 2}
+ meds = {"me": med(10.0), "near": med(10.0), "far": med(10.0), "cold": med(-5.0)}
+ centres = {"me": (45.0, -110.0), "near": (45.5, -110.0),
+ "far": (30.0, -80.0), "cold": (45.1, -110.0)}
+ got = J.comparables("me", part_of, ["near", "far", "cold"], meds, centres, k=2)
+ self.assertEqual(got, ["near", "far"])
+
+
+def info(kind="track"):
+ pts = [C.PointNormals(lat=44.0 + i, lon=-110.0, elev_m=1000.0 * (i + 1),
+ tmax_c=tuple(float(v) for v in range(12)))
+ for i in range(4)]
+ return {"points": pts, "kind": kind, "profile": (3500.0, 800.0)}
+
+
+class PacketTest(unittest.TestCase):
+ def rec(self):
+ return {"id": "tt", "name": "Test Trail", "country": "US", "regions": ["WY"],
+ "length_km": 160.9344, "kind": "trail",
+ "hike": {"summary": "A ridge walk. Best in July. It has huts.",
+ "start": "Trailhead.", "terrain": ["alpine"], "high_point_m": 3000,
+ "days": [8, 10]}}
+
+ def text(self, **kw):
+ args = dict(rec=self.rec(), info=info(), machine=[6, 7, 8],
+ comparables=[], pages=None, precip=None)
+ args.update(kw)
+ return J.packet_text(**args)
+
+ def test_the_packet_states_the_trail_in_miles_and_feet_and_hides_timing(self):
+ t = self.text()
+ self.assertIn("length: 100 miles", t)
+ self.assertIn("high point: 9843 ft", t)
+ self.assertIn("A ridge walk. It has huts.", t)
+ self.assertNotIn("Best in July", t)
+
+ def test_it_never_carries_the_trails_own_season(self):
+ rec = self.rec()
+ rec["hike"].update(season="July to September", months=[7, 8, 9], season_basis="primary")
+ t = self.text(rec=rec)
+ self.assertNotIn("July to September", t)
+
+ def test_it_gives_the_machine_estimate_and_the_climate(self):
+ t = self.text()
+ self.assertIn("Months: 6, 7, 8 (June, July, August)", t)
+ self.assertIn("| Jan |", t)
+ self.assertIn("Precipitation is not available", t)
+
+ def test_precipitation_is_given_when_supplied(self):
+ t = self.text(precip=[[25.4] * 12] * 4)
+ self.assertIn("precip in", t)
+ self.assertNotIn("Precipitation is not available", t)
+
+ def test_what_pages_say_appears_only_when_given(self):
+ self.assertNotIn("What pages say", self.text())
+ self.assertIn("Months each gives: A 5-10", self.text(pages="Publisher(s): A\nMonths each gives: A 5-10"))
+
+ def test_a_trail_with_no_climate_says_so(self):
+ t = self.text(info=dict(info(), points=[]), machine=[])
+ self.assertIn("No climate data is available", t)
+ self.assertIn("Months: none", t)
+
+
+class AnswersTest(unittest.TestCase):
+ def write(self, text):
+ d = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, d, True)
+ path = os.path.join(d, "a.tsv")
+ with open(path, "w") as f:
+ f.write(text)
+ return path
+
+ def test_good_rows_are_read_and_bad_rows_are_named(self):
+ path = self.write(
+ "aa\t7,8,9\tJuly to September\thigh\tSnow melts.\n"
+ "bb\t\tNone\thigh\tEmpty.\n"
+ "cc\t13\tX\thigh\tOut of range.\n"
+ "dd\t6\tJune\tsure\tBad confidence.\n"
+ "aa\t6\tJune\tlow\tDuplicate.\n"
+ "zz\t6\tJune\tlow\tUnknown.\n"
+ "ee\t5,6\tMay to June\tmedium\tFine.\n")
+ ans, problems = J.read_answers(path, ["aa", "bb", "cc", "dd", "ee"])
+ self.assertEqual(sorted(ans), ["aa", "ee"])
+ self.assertEqual(ans["aa"], ([7, 8, 9], "July to September", "high", "Snow melts."))
+ self.assertEqual(len(problems), 5)
+
+
+class ScoreTest(unittest.TestCase):
+ def test_matches_are_counted_within_a_month_at_each_end_by_confidence(self):
+ truth = {"a": [6, 7, 8, 9], "b": [6, 7, 8, 9], "c": [6, 7, 8, 9], "d": [1, 2, 3]}
+ ans = {"a": ([6, 7, 8, 9], "", "high", ""), # exact
+ "b": ([7, 8, 9, 10], "", "medium", ""), # one month at each end
+ "c": ([1, 2, 3], "", "low", ""), # wrong
+ "x": ([1], "", "high", "")} # not a sourced trail: ignored
+ got = J.score(ans, truth)
+ self.assertEqual(got["tested"], 4)
+ self.assertEqual(got["matched"], 2)
+ self.assertEqual(got["by_confidence"]["high"], {"tested": 1, "matched": 1})
+ self.assertEqual(got["by_confidence"]["medium"], {"tested": 1, "matched": 1})
+ self.assertEqual(got["by_confidence"]["low"], {"tested": 1, "matched": 0})
+ # d was never answered: it counts as tested and missed
+ self.assertEqual(got["unanswered"], 1)
+
+ def test_the_figure_file_round_trips_and_shares_are_computed(self):
+ figures = {"tested": 148, "matched": 114, "unanswered": 0,
+ "by_confidence": {"high": {"tested": 52, "matched": 48},
+ "medium": {"tested": 76, "matched": 55},
+ "low": {"tested": 20, "matched": 11}}}
+ d = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, d, True)
+ path = os.path.join(d, "t.json")
+ J.write_blind_test(path, figures, "2026-11-20")
+ got = J.load_blind_test(path)
+ self.assertEqual(got["date"], "2026-11-20")
+ self.assertEqual(got["tested"], 148)
+ self.assertEqual(got["matched"], 114)
+ self.assertEqual(got["share"], 0.77)
+ self.assertEqual(got["by_confidence"]["high"]["share"], 0.92)
+ self.assertEqual(got["by_confidence"]["low"]["share"], 0.55)
+
+ def test_a_loaded_file_must_add_up(self):
+ bad = {"date": "2026-11-20", "tested": 10, "matched": 5, "share": 0.5,
+ "by_confidence": {"high": {"tested": 4, "matched": 5, "share": 1.0},
+ "medium": {"tested": 3, "matched": 1, "share": 0.33},
+ "low": {"tested": 3, "matched": 1, "share": 0.33}}}
+ self.assertTrue(J.check_blind_test(bad))
+
+
+class CommittedFilesTest(unittest.TestCase):
+ def test_the_committed_blind_test_adds_up_and_passes_the_bar(self):
+ got = J.load_blind_test(os.path.join(J.ROOT, "tools", "season_blind_test.json"))
+ self.assertEqual(J.check_blind_test(got), [])
+ self.assertGreaterEqual(got["share"], E.BAR["within1_min"])
+
+ def test_every_judged_row_is_well_formed_and_matches_its_record(self):
+ ids = R.trail_ids(J.ROOT)
+ ans, problems = J.read_answers(os.path.join(J.ROOT, "tools", "season_judged.tsv"), ids)
+ self.assertEqual(problems, [])
+ self.assertEqual(sorted(ans), sorted(ids))
+ for tid in ids:
+ hike = R.load_toml(os.path.join(J.ROOT, tid, "trail.toml")).get("hike") or {}
+ if hike.get("season_basis") == "estimate" or hike.get("season_method"):
+ months, _phrase, conf, _why = ans[tid]
+ self.assertEqual(months, hike["months"], tid)
+ self.assertEqual(J.season.confidence_of(hike["season_method"]), conf, tid)
+
+
+class ProposalsTest(unittest.TestCase):
+ HIKE = 'start_lonlat = [-110.0, 43.0]\nend_lonlat = [-110.0, 43.2]\n'
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.tmp, True)
+ self.root = TR.make_repo(self.tmp, trails=[
+ ("aaa", "Aaa", {"extra_hike": self.HIKE}),
+ ("bbb", "Bbb", {"extra_hike": self.HIKE}),
+ ("ccc", "Ccc", {"extra_hike": 'season = "June"\nmonths = [6]\nseason_basis = "source"\n' + self.HIKE}),
+ ])
+ self.stage = os.path.join(self.tmp, "stage")
+ os.makedirs(self.stage)
+ self.answers = os.path.join(self.tmp, "judged.tsv")
+ with open(self.answers, "w") as f:
+ f.write("aaa\t7,8,9\tJuly to September\thigh\tSnow melts late.\n"
+ "bbb\t5,6,7,8,9,10\tMay to October\tmedium\tThe pages differ.\n"
+ "ccc\t1,2\tJanuary to February\tlow\tNot used: it has a season.\n")
+ self.pages = os.path.join(self.tmp, "pages.json")
+ with open(self.pages, "w") as f:
+ json.dump({"bbb": {
+ "why": "The pages differ: one says May to September and one says June to October. "
+ "It was set by judgement from both and from the climate.",
+ "sources": [
+ {"url": "https://a.example/bbb", "publisher": "Guide A", "quote": "Season: May to September"},
+ {"url": "https://b.example/bbb", "publisher": "Guide B", "quote": "Season: June to October"}]}}, f)
+
+ def test_only_trails_with_no_season_are_staged(self):
+ n = J.proposals(self.root, self.answers, self.pages, self.stage)
+ self.assertEqual(n, 2)
+
+ def test_collect_and_apply_write_valid_records_with_history(self):
+ J.proposals(self.root, self.answers, self.pages, self.stage)
+ code, out = TR.main(self.root, "--dir", self.stage, "collect")
+ self.assertEqual(code, 0, out)
+ coll = R.load_toml(os.path.join(self.stage, "collected.toml"))
+ self.assertEqual({p["status"] for p in coll["proposal"]}, {"proposed"}, out)
+ with open(os.path.join(self.stage, "owner.csv"), "w") as f:
+ f.write("pid,decision,digest\n")
+ for p in coll["proposal"]:
+ f.write(f"{p['pid']},accept,{p['digest']}\n")
+ code, out = TR.main(self.root, "--dir", self.stage, "collect")
+ self.assertEqual(code, 0, out)
+ code, out = TR.main(self.root, "--dir", self.stage, "apply")
+ self.assertEqual(code, 0, out)
+ a = R.load_toml(os.path.join(self.root, "aaa", "trail.toml"))
+ h = a["hike"]
+ self.assertEqual((h["season"], h["months"], h["season_basis"]),
+ ("July to September", [7, 8, 9], "estimate"))
+ self.assertTrue(h["season_method"].endswith("Confidence: high."))
+ self.assertIn("Snow melts late.", h["season_method"])
+ self.assertEqual(len(h["source"]), 3) # two the record had, and the climate data
+ self.assertEqual(h["source"][-1]["facts"], ["season", "months"])
+ self.assertIn("chelsa", h["source"][-1]["url"])
+ errors = []
+ V.check_hike("aaa", a, errors)
+ trail_history.check_entries("aaa", a, errors)
+ # (the fixture's own end-point fields are not what is under test)
+ self.assertEqual([e for e in errors if "lonlat" not in e], [], errors)
+ self.assertTrue(any("hike.season" in (e.get("fields") or []) for e in a["history"]))
+ b = R.load_toml(os.path.join(self.root, "bbb", "trail.toml"))["hike"]
+ self.assertEqual(b["season_basis"], "sources")
+ self.assertIn("The pages differ", b["season_method"])
+ self.assertEqual([s["publisher"] for s in b["source"]][-2:], ["Guide A", "Guide B"])
+ errors = []
+ V.check_hike("bbb", {"hike": b}, errors)
+ self.assertEqual([e for e in errors if "lonlat" not in e], [], errors)
+
+
+if __name__ == "__main__":
+ unittest.main()
From 191b5cfc4fb29452c6d266c54caacd9a29e35c91 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:06:59 -0700
Subject: [PATCH 11/30] Write a season for the 75 trails that had none: 69
estimates and 6 set from pages that differ
---
across-utah-route/trail.toml | 20 ++++++++++++-
alpine-trail-7/trail.toml | 20 ++++++++++++-
avon/trail.toml | 20 ++++++++++++-
batona/trail.toml | 20 ++++++++++++-
bay-circuit/trail.toml | 20 ++++++++++++-
bayou-state-trail/trail.toml | 20 ++++++++++++-
boundary-trail-mount-st-helens/trail.toml | 20 ++++++++++++-
boundary-trail-pasayten/trail.toml | 20 ++++++++++++-
bristol-hills-trail/trail.toml | 20 ++++++++++++-
brooks-range-traverse/trail.toml | 20 ++++++++++++-
bruce-trail/trail.toml | 20 ++++++++++++-
california-coastal/trail.toml | 20 ++++++++++++-
cohos/trail.toml | 25 +++++++++++++++-
conestoga-trail/trail.toml | 20 ++++++++++++-
conservation-trail/trail.toml | 20 ++++++++++++-
cranberry-lake-50/trail.toml | 20 ++++++++++++-
cross-vermont/trail.toml | 20 ++++++++++++-
deseret-hiking-route/trail.toml | 20 ++++++++++++-
desert-trail/trail.toml | 20 ++++++++++++-
donut-hole/trail.toml | 20 ++++++++++++-
eastern-continental-trail/trail.toml | 20 ++++++++++++-
eastern-sierra-high-route/trail.toml | 20 ++++++++++++-
finger-lakes/trail.toml | 20 ++++++++++++-
ganaraska/trail.toml | 20 ++++++++++++-
general-george-crook/trail.toml | 20 ++++++++++++-
georgia-loop/trail.toml | 20 ++++++++++++-
gila-centennial-loop/trail.toml | 20 ++++++++++++-
grand-valley-trail/trail.toml | 20 ++++++++++++-
great-eastern/trail.toml | 20 ++++++++++++-
great-western-divide-loop/trail.toml | 20 ++++++++++++-
high-country-pathway/trail.toml | 20 ++++++++++++-
highlands/trail.toml | 20 ++++++++++++-
hoosier-heritage-trail/trail.toml | 20 ++++++++++++-
horse-shoe/trail.toml | 20 ++++++++++++-
hot-springs-trail/trail.toml | 20 ++++++++++++-
iat-newfoundland-labrador/trail.toml | 20 ++++++++++++-
ice-age/trail.toml | 25 +++++++++++++++-
.../trail.toml | 20 ++++++++++++-
koroc-palmer-loop/trail.toml | 20 ++++++++++++-
la-cloche/trail.toml | 20 ++++++++++++-
lost-coast/trail.toml | 20 ++++++++++++-
loyalsock/trail.toml | 20 ++++++++++++-
mason-dixon/trail.toml | 20 ++++++++++++-
midland-to-mackinac-trail/trail.toml | 20 ++++++++++++-
midstate-ma/trail.toml | 20 ++++++++++++-
north-south-lbl/trail.toml | 20 ++++++++++++-
north-south/trail.toml | 20 ++++++++++++-
north-umpqua/trail.toml | 20 ++++++++++++-
oak-ridges/trail.toml | 20 ++++++++++++-
ottawa-temiskaming-highland-trail/trail.toml | 20 ++++++++++++-
ouachita/trail.toml | 30 ++++++++++++++++++-
ozark-trail/trail.toml | 25 +++++++++++++++-
paumanok-path/trail.toml | 20 ++++++++++++-
pfiffner-traverse/trail.toml | 20 ++++++++++++-
rideau-trail/trail.toml | 20 ++++++++++++-
ring-the-peak/trail.toml | 20 ++++++++++++-
sawtooth-wilderness-high-route/trail.toml | 20 ++++++++++++-
sea-to-sea-route/trail.toml | 20 ++++++++++++-
shawangunk-ridge-trail/trail.toml | 20 ++++++++++++-
shenipsit-trail/trail.toml | 20 ++++++++++++-
sierra-high-route/trail.toml | 22 ++++++++++++--
siskiyou-peaks-trail/trail.toml | 20 ++++++++++++-
sky-islands-traverse/trail.toml | 20 ++++++++++++-
solitude-loop/trail.toml | 20 ++++++++++++-
standing-stone/trail.toml | 20 ++++++++++++-
stein-valley-traverse/trail.toml | 20 ++++++++++++-
sunapee-ragged-kearsarge/trail.toml | 20 ++++++++++++-
tahoe-yosemite-trail/trail.toml | 20 ++++++++++++-
tools/season.py | 8 ++---
tools/season_judged.tsv | 2 +-
tools/tests/test_season_fit.py | 15 +++++-----
tools/tests/test_season_helpers.py | 4 +++
tuscarora/trail.toml | 20 ++++++++++++-
vagabond-loop/trail.toml | 20 ++++++++++++-
warrior-trail/trail.toml | 20 ++++++++++++-
wasatch-traverse/trail.toml | 20 ++++++++++++-
waskahegan/trail.toml | 20 ++++++++++++-
western-uplands/trail.toml | 20 ++++++++++++-
yosemite-high-route/trail.toml | 20 ++++++++++++-
79 files changed, 1468 insertions(+), 88 deletions(-)
diff --git a/across-utah-route/trail.toml b/across-utah-route/trail.toml
index c28507d..45c24fd 100644
--- a/across-utah-route/trail.toml
+++ b/across-utah-route/trail.toml
@@ -75,13 +75,22 @@ shape = "point-to-point"
terrain = ["desert", "canyon", "alpine"]
travel = "some-cross-country"
caution = "The author says no part is technical, but the route involves exposure, deep pools, long dry stretches and a Colorado River crossing that needs a packraft or a ride from a river party."
-checked = "2026-11-15"
+checked = "2026-11-20"
+season = "April to June and September to October"
+months = [4, 5, 6, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Desert heat in summer and snow in the Henrys, La Sals and Bryce country in winter leave spring and fall. Confidence: medium."
[[hike.source]]
url = "http://www.acrossutah.com/wordpress/the_route/"
publisher = "Jamal Green, Across Utah (the route's author)"
facts = ["summary", "official_url", "start", "end", "shape", "terrain", "travel", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -101,3 +110,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "http://www.acrossutah.com/wordpress/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/alpine-trail-7/trail.toml b/alpine-trail-7/trail.toml
index 7d9157d..79e3ecb 100644
--- a/alpine-trail-7/trail.toml
+++ b/alpine-trail-7/trail.toml
@@ -56,7 +56,11 @@ shape = "point-to-point"
terrain = ["alpine", "lakes"]
travel = "trail"
caution = "The Forest Service lists the trail as open to hiking, biking and motorcycle trail riding, with motorized use in specific stretches only and Jewel Basin Special Area rules to check."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Heavy winter snow at 7,000 feet in the Swan Range melts out by mid-July, and snow returns in October. Confidence: high."
[[hike.source]]
url = "https://web.archive.org/web/20201201005308/https://www.fs.usda.gov/recarea/flathead/recreation/recarea/?recid=66288&actid=51"
@@ -73,6 +77,11 @@ url = "https://www.fs.usda.gov/r01/flathead/offices/swan-lake-ranger-station"
publisher = "USDA Forest Service, Flathead National Forest"
facts = ["summary"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -102,3 +111,12 @@ basis = "The record has a published track file and a measured length in its veri
basis_url = "https://apps.fs.usda.gov/arcx/rest/services/EDW/EDW_TrailNFSPublish_01/MapServer/0"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/avon/trail.toml b/avon/trail.toml
index eb4418f..0653b8c 100644
--- a/avon/trail.toml
+++ b/avon/trail.toml
@@ -57,7 +57,11 @@ end = "Conestogo, Ontario"
shape = "point-to-point"
terrain = ["farmland"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Winter snow and early-spring mud on Ontario farmland end with the thaw, and the walk runs until late fall. Confidence: medium."
[[hike.source]]
url = "https://avontrail.ca/"
@@ -69,6 +73,11 @@ url = "https://avontrail.ca/about/"
publisher = "Avon Trail Association"
facts = ["summary", "start", "end", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -97,3 +106,12 @@ basis = "OpenStreetMap relation 3442182 gives no roles, and the Avon Trail Assoc
basis_url = "https://www.openstreetmap.org/relation/3442182"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/batona/trail.toml b/batona/trail.toml
index 673a14d..4dd56c2 100644
--- a/batona/trail.toml
+++ b/batona/trail.toml
@@ -57,7 +57,11 @@ shape = "point-to-point"
high_point = "Apple Pie Hill"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Flat Pine Barrens walking is best when it is cool, away from summer heat, ticks and biting flies. Confidence: medium."
[[hike.source]]
url = "https://batona.wildapricot.org/"
@@ -79,6 +83,11 @@ url = "https://dep.nj.gov/wp-content/uploads/parksandforests/docs/sps/batona-map
publisher = "New Jersey State Park Service"
facts = ["high_point"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -98,3 +107,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://batona.wildapricot.org/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/bay-circuit/trail.toml b/bay-circuit/trail.toml
index 0d3de02..9d37a0f 100644
--- a/bay-circuit/trail.toml
+++ b/bay-circuit/trail.toml
@@ -59,7 +59,11 @@ end = "Kingston Bay, Massachusetts"
shape = "point-to-point"
travel = "trail"
unfinished = "More than 230 miles are dedicated across 37 cooperating towns, and the final gaps are still being closed."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Humid, buggy summers and icy winters in low-lying eastern Massachusetts leave spring and fall, though it can be walked all year. Confidence: medium."
[[hike.source]]
url = "https://www.baycircuit.org/"
@@ -71,6 +75,11 @@ url = "https://www.baycircuit.org/about/"
publisher = "Bay Circuit Alliance"
facts = ["summary", "start", "end", "shape", "unfinished"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Bay Circuit Trail"
publisher = "LongTrailsWiki"
@@ -104,3 +113,12 @@ basis = "OpenStreetMap relation 12779888 gives no roles. The Bay Circuit Allianc
basis_url = "https://www.baycircuit.org/maps-guides/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/bayou-state-trail/trail.toml b/bayou-state-trail/trail.toml
index 808c698..5852e9d 100644
--- a/bayou-state-trail/trail.toml
+++ b/bayou-state-trail/trail.toml
@@ -54,7 +54,11 @@ end_lonlat = [-91.207, 29.699]
shape = "point-to-point"
terrain = ["forest"]
caution = "The association does not say how much of the route is trail and how much is road or town walking. Its trails page, read on 2026-11-19, lists the Hwy 182 bridge over the Atchafalaya River, between Berwick and Morgan City, as closed, and gives a temporary southern end at the Berwick Branch Library, 3512 5th Street. The notice carries no date of its own and gives the reopening as fall 2026. Check with the association before going."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "November to April"
+months = [1, 2, 3, 4, 11, 12]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Summer heat, humidity, mosquitoes and storms in Louisiana push hiking into the cool, dry winter and early spring. Confidence: medium."
[[hike.source]]
url = "https://www.bayoustatetrail.com/"
@@ -86,6 +90,11 @@ url = "https://services1.arcgis.com/fXHQyq63u0UsTeSM/ArcGIS/rest/services/LDWF_B
publisher = "Louisiana Department of Wildlife and Fisheries, boat launches layer: Ivan Lake Boat Ramp on Ivan Lake Road, inside Ivan Lake Recreation Area; the point is the wildlife agency's boat ramp, not a surveyed trailhead"
facts = ["start_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -132,3 +141,12 @@ basis = "The association's trails page, read on 2026-11-19, still lists the brid
basis_url = "https://www.bayoustatetrail.com/trails"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: November to April."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/boundary-trail-mount-st-helens/trail.toml b/boundary-trail-mount-st-helens/trail.toml
index 736198d..2c2613b 100644
--- a/boundary-trail-mount-st-helens/trail.toml
+++ b/boundary-trail-mount-st-helens/trail.toml
@@ -58,13 +58,22 @@ terrain = ["alpine", "forest"]
travel = "trail"
permit = "Some trailheads that access this trail require a valid Recreation Pass, per the Forest Service."
caution = "East of Bear Meadows the trail is open to motorcycles as well as hikers, horses and bicycles. The Forest Service states the trail is closed to ATV use."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "July to October"
+months = [7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Cascade ridges around 5,000 feet hold snow until July, and heavy rain starts in late October. Confidence: high."
[[hike.source]]
url = "https://www.fs.usda.gov/r06/giffordpinchot/recreation/trails/trail-1-boundary"
publisher = "USDA Forest Service, Gifford Pinchot National Forest"
facts = ["summary", "official_url", "start", "end", "shape", "terrain", "travel", "permit", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -85,3 +94,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.fs.usda.gov/r06/giffordpinchot/recreation/trails/trail-1-boundary"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/boundary-trail-pasayten/trail.toml b/boundary-trail-pasayten/trail.toml
index 1f1b9b0..279e48d 100644
--- a/boundary-trail-pasayten/trail.toml
+++ b/boundary-trail-pasayten/trail.toml
@@ -57,7 +57,11 @@ shape = "point-to-point"
terrain = ["alpine", "forest"]
travel = "trail"
permit = "A free self-issuing wilderness permit, filled out at the trailhead, is required to enter the Pasayten Wilderness."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The Pasayten high country at 5,500 to 7,500 feet is under snow until early July, and snow returns in October. Confidence: high."
[[hike.source]]
url = "https://www.fs.usda.gov/r06/okanogan-wenatchee/recreation/trails/boundary-trail"
@@ -74,6 +78,11 @@ url = "https://www.fs.usda.gov/trails/pacific-northwest-nst/geographic-areas"
publisher = "U.S. Forest Service, Pacific Northwest National Scenic Trail"
facts = ["summary"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -94,3 +103,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.fs.usda.gov/r06/okanogan-wenatchee/recreation/trails/boundary-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/bristol-hills-trail/trail.toml b/bristol-hills-trail/trail.toml
index 5690a6b..ab9d72c 100644
--- a/bristol-hills-trail/trail.toml
+++ b/bristol-hills-trail/trail.toml
@@ -55,7 +55,11 @@ end = "Main Finger Lakes Trail near Mitchellsville, New York"
shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Snow and mud make winter and early spring uncommon for walking, so the comfortable months run from late spring through fall. Confidence: medium."
[[hike.source]]
url = "https://cnyhiking.com/The%20Bristol%20Hills%20Trail.htm"
@@ -67,6 +71,11 @@ url = "https://www.gofingerlakes.org/locations/gannett-hill-park/"
publisher = "Go Finger Lakes (Finger Lakes Land Trust)"
facts = ["summary", "start"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -87,3 +96,12 @@ basis = "The pages named in the logo note were searched, and none offers usable
basis_url = "https://fingerlakestrail.org/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/brooks-range-traverse/trail.toml b/brooks-range-traverse/trail.toml
index dff11b9..e49a6ef 100644
--- a/brooks-range-traverse/trail.toml
+++ b/brooks-range-traverse/trail.toml
@@ -71,7 +71,11 @@ shape = "point-to-point"
terrain = ["tundra", "alpine"]
travel = "mostly-cross-country"
caution = "There is almost no trail, and much of the route is floated by packraft, so it needs packrafting skills as well as route-finding."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "June to September"
+months = [6, 7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Arctic tundra is frozen and snowbound most of the year, with river breakup in early June and freeze-up and snow by mid-September. Confidence: low."
[[hike.source]]
url = "https://thingstolucat.com/brooks-range-traverse/"
@@ -98,6 +102,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/1404349"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -126,3 +135,12 @@ basis = "The trip reports give routes, maps and photos but no track file or GPX
basis_url = "https://thingstolucat.com/brooks-range-traverse/"
asked_by = "a reviewer"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/bruce-trail/trail.toml b/bruce-trail/trail.toml
index a644f9b..32e25b7 100644
--- a/bruce-trail/trail.toml
+++ b/bruce-trail/trail.toml
@@ -56,7 +56,11 @@ shape = "point-to-point"
days = [30, 30]
travel = "trail"
permit = "Parking reservations are needed at some parks, and camping is allowed only at designated sites, often by reservation."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The Niagara Escarpment is icy and muddy through winter and early spring, so end-to-end hikes run from the April thaw to the end of October. Confidence: medium."
[[hike.source]]
url = "https://brucetrail.org/explore-the-trail/"
@@ -68,6 +72,11 @@ url = "https://www.brucetrail.org/"
publisher = "Bruce Trail Conservancy"
facts = ["summary"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Bruce Trail"
publisher = "LongTrailsWiki"
@@ -92,3 +101,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://brucetrail.org/wp-content/uploads/2022/07/BTC_arrow-icon.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/california-coastal/trail.toml b/california-coastal/trail.toml
index 8b9a769..5b4490b 100644
--- a/california-coastal/trail.toml
+++ b/california-coastal/trail.toml
@@ -57,7 +57,11 @@ official_url = "https://www.coastal.ca.gov/coastal-trail/"
terrain = ["coast"]
travel = "trail-and-road"
unfinished = "The state counts about 875 miles, about 70 percent, as built along a coastline of about 1,230 miles, and there is no official through route. A hiker reports having walked the whole coast from end to end, in eight section hikes, by connecting the built parts with their own choices."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The coast can be walked all year, but winter storms bring heavy rain in the north and leave some sections passable only at low tide, so a full walk suits the dry months. Confidence: low."
[[hike.source]]
url = "https://www.coastal.ca.gov/coastal-trail/"
@@ -69,6 +73,11 @@ url = "https://github.com/swaits/longhikes/issues/1"
publisher = "A hiker, on the dataset's public issue tracker"
facts = ["unfinished"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "California Coastal Trail (incomplete)"
publisher = "LongTrailsWiki"
@@ -129,3 +138,12 @@ basis = "The page quotes the note to visitors, and the prefix only repeated the
basis_url = "https://github.com/swaits/longhikes/issues/1#issuecomment-6928214012"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/cohos/trail.toml b/cohos/trail.toml
index 7a44602..cbe3c43 100644
--- a/cohos/trail.toml
+++ b/cohos/trail.toml
@@ -58,7 +58,11 @@ high_point_m = 1917
days = [9, 14]
terrain = ["forest", "alpine"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "sources"
+season_method = "The pages differ: The Trek gives May to October and Backpacking Routes gives June to November. It was set by judgement from both and from the climate, since snow and mud last into late May and cold sets in by late October. Confidence: medium."
[[hike.source]]
url = "https://www.cohostrail.org/"
@@ -75,6 +79,16 @@ url = "https://www.cohostrail.org/the-trail/"
publisher = "Cohos Trail Association"
facts = ["summary", "high_point", "terrain", "travel"]
+[[hike.source]]
+url = "https://thetrek.co/10-trails-can-find-long-distance-solitude-2020/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
+[[hike.source]]
+url = "https://backpackingroutes.com/cohos-trail/"
+publisher = "Backpacking Routes"
+facts = ["season", "months"]
+
[[link]]
title = "Cohos Trail"
publisher = "LongTrailsWiki"
@@ -99,3 +113,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://www.cohostrail.org/wp-content/uploads/2015/01/cohos-trail-logo.jpg"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was set from pages that differ: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "The pages that state a season differ and none is the managing body, association or route author, so it was set by judgement from all of them and the climate estimate."
+basis_url = "https://thetrek.co/10-trails-can-find-long-distance-solitude-2020/"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/conestoga-trail/trail.toml b/conestoga-trail/trail.toml
index c9514e7..06c62ba 100644
--- a/conestoga-trail/trail.toml
+++ b/conestoga-trail/trail.toml
@@ -54,13 +54,22 @@ official_url = "https://www.lancasterhikingclub.com/copy-of-conestoga-trail"
shape = "point-to-point"
terrain = ["forest", "farmland"]
travel = "trail-and-road"
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The low Lancaster County hills are hot, humid and tick-ridden in summer, so the cool months suit it best. Confidence: medium."
[[hike.source]]
url = "https://www.lancasterhikingclub.com/copy-of-conestoga-trail"
publisher = "Lancaster Hiking Club"
facts = ["official_url", "summary", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -80,3 +89,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.lancasterhikingclub.com/copy-of-conestoga-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/conservation-trail/trail.toml b/conservation-trail/trail.toml
index 40fd553..739dd15 100644
--- a/conservation-trail/trail.toml
+++ b/conservation-trail/trail.toml
@@ -52,7 +52,11 @@ end = "Rainbow Bridge, Niagara Falls, New York"
end_lonlat = [-79.067, 43.09]
shape = "point-to-point"
terrain = ["forest"]
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Low-elevation western New York is snowy in winter and muddy in March, and can be walked from April until late fall. Confidence: medium."
[[hike.source]]
url = "https://sites.google.com/view/foothillstrailclub/about-the-trail"
@@ -69,6 +73,11 @@ url = "https://nominatim.openstreetmap.org/ui/details.html?osmtype=W&osmid=99097
publisher = "OpenStreetMap contributors, via Nominatim (ODbL): Rainbow Bridge, United States side, OpenStreetMap way 990979149"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -97,3 +106,12 @@ basis = "OpenStreetMap contributors, via Nominatim (ODbL): Rainbow Bridge, Unite
basis_url = "https://nominatim.openstreetmap.org/ui/details.html?osmtype=W&osmid=990979149"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/cranberry-lake-50/trail.toml b/cranberry-lake-50/trail.toml
index b75bbdc..ed7961b 100644
--- a/cranberry-lake-50/trail.toml
+++ b/cranberry-lake-50/trail.toml
@@ -58,7 +58,11 @@ days = [3, 5]
terrain = ["forest", "lakes"]
travel = "trail"
permit = "A free permit from the local forest ranger is needed for groups of ten or more, or to camp more than three days in one spot."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Adirondack snow and mud in spring and black flies into June leave summer and fall as the usual window. Confidence: medium."
[[hike.source]]
url = "https://cranberrylake50.org/"
@@ -75,6 +79,11 @@ url = "https://cranberrylake50.org/plan-your-trip/"
publisher = "Cranberry Lake 50 (Five Ponds Partners)"
facts = ["permit"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Cranberry Lake 50"
publisher = "LongTrailsWiki"
@@ -108,3 +117,12 @@ basis = "The page of Cranberry Lake 50 (Five Ponds Partners) says: \"groups of 1
basis_url = "https://cranberrylake50.org/plan-your-trip/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/cross-vermont/trail.toml b/cross-vermont/trail.toml
index 528d465..ee949d8 100644
--- a/cross-vermont/trail.toml
+++ b/cross-vermont/trail.toml
@@ -58,13 +58,22 @@ end = "Lake Champlain, Vermont"
shape = "point-to-point"
travel = "trail-and-road"
unfinished = "About half the route is still on busier roads, and the association is building more trail toward a complete off-road route across the state."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A low-elevation route of mostly rail trail and quiet roads, where winter snow and mud season bracket a long snow-free stretch from May to October. Confidence: medium."
[[hike.source]]
url = "https://crossvermont.org/our_trail/index.php"
publisher = "Cross Vermont Trail Association"
facts = ["official_url", "summary", "start", "end", "shape", "travel", "unfinished"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -84,3 +93,12 @@ basis = "The pages named in the logo note were searched, and none offers usable
basis_url = "https://crossvermont.org/our_trail/index.php"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/deseret-hiking-route/trail.toml b/deseret-hiking-route/trail.toml
index f2b2a11..18620ae 100644
--- a/deseret-hiking-route/trail.toml
+++ b/deseret-hiking-route/trail.toml
@@ -72,7 +72,11 @@ shape = "point-to-point"
terrain = ["canyon", "alpine"]
travel = "trail-and-road"
caution = "The route is unmarked and not designated by any state or federal agency, and about 40 percent of it is dirt road."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A route from southern Utah desert canyons to the Pioneer Mountains of Idaho needs the high ground clear of snow and the south not scorching. Confidence: low."
[[hike.source]]
url = "http://www.lbhikes.com/p/a-complete-guide-to-deseret-hiking-route.html"
@@ -84,6 +88,11 @@ url = "https://www.blm.gov/visit/stateline-campground"
publisher = "Bureau of Land Management (public domain): Stateline Campground, given as the northern end of the Arizona National Scenic Trail"
facts = ["start_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -121,3 +130,12 @@ basis = "The author's guide page sends the maps, data book and GPX only after pr
basis_url = "http://www.lbhikes.com/p/a-complete-guide-to-deseret-hiking-route.html"
asked_by = "a reviewer"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/desert-trail/trail.toml b/desert-trail/trail.toml
index 5b8ac40..cb7d99d 100644
--- a/desert-trail/trail.toml
+++ b/desert-trail/trail.toml
@@ -71,13 +71,22 @@ shape = "point-to-point"
terrain = ["desert"]
travel = "mostly-cross-country"
caution = "There is no trail on the ground and no signs: the route is found by map and experience, and water sources are few and far between."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to June and September to October"
+months = [4, 5, 6, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Waterless desert is too hot in summer and snowy in winter, so a full walk runs through spring and early fall. Confidence: low."
[[hike.source]]
url = "https://deserttrail.net"
publisher = "Desert Survivors (the route's present keeper)"
facts = ["official_url", "summary", "start", "end", "shape", "terrain", "travel", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -97,3 +106,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://deserttrail.net/images/DTLogo.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/donut-hole/trail.toml b/donut-hole/trail.toml
index a22bc93..3471243 100644
--- a/donut-hole/trail.toml
+++ b/donut-hole/trail.toml
@@ -57,13 +57,22 @@ start = "Jericho, Pennsylvania"
end = "Farrandsville, near Lock Haven, Pennsylvania"
shape = "point-to-point"
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to June and September to October"
+months = [4, 5, 6, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Unbridged streams run high in early spring, and the valleys are hot, humid and buggy in midsummer, so the shoulder months suit best. Confidence: low."
[[hike.source]]
url = "https://www.kta-hike.org/donut-hole-trail.html"
publisher = "Keystone Trails Association"
facts = ["official_url", "summary", "start", "end", "shape", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Donut Hole Trail"
publisher = "LongTrailsWiki"
@@ -88,3 +97,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.kta-hike.org/donut-hole-trail.html"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/eastern-continental-trail/trail.toml b/eastern-continental-trail/trail.toml
index 55d1396..903c4e1 100644
--- a/eastern-continental-trail/trail.toml
+++ b/eastern-continental-trail/trail.toml
@@ -73,7 +73,11 @@ end_lonlat = [-64.164, 48.752]
shape = "point-to-point"
days = [300, 300]
travel = "trail-and-road"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "January to October"
+months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A thru-hike of about 300 days starts in the Florida winter and has to finish in the Gaspe before the November snows. Confidence: low."
[[hike.source]]
url = "https://nimblewillnomad.com/books/"
@@ -95,6 +99,11 @@ url = "https://geogratis.gc.ca/services/geoname/en/geonames/EGLSG"
publisher = "Natural Resources Canada, Canadian Geographical Names Database"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Eastern Continental Trail"
publisher = "LongTrailsWiki"
@@ -146,3 +155,12 @@ basis = "The Open Library record gives Ten Million Steps: Nimblewill Nomad's Epi
basis_url = "https://openlibrary.org/books/OL8257206M"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: January to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/eastern-sierra-high-route/trail.toml b/eastern-sierra-high-route/trail.toml
index 5d96aab..36210d0 100644
--- a/eastern-sierra-high-route/trail.toml
+++ b/eastern-sierra-high-route/trail.toml
@@ -75,7 +75,11 @@ terrain = ["alpine"]
travel = "mostly-cross-country"
permit = "A wilderness permit is required year round for overnight trips from the Duck Pass trailhead, and from May 1 through November 1 overnight visitors there are limited to 30 people per day."
caution = "The author says the route is consistently difficult, with steep and sometimes loose talus, scree and sand."
-checked = "2026-11-15"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Cross-country passes above 10,500 feet need the snow to have melted, which is from mid-July through September. Confidence: high."
[[hike.source]]
url = "https://danstenziano.com/products/eastern-sierra-high-route-guide"
@@ -97,6 +101,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/267526"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -116,3 +125,12 @@ basis = "The page the guide links to is titled \"Eastern Sierra High Route Guide
basis_url = "https://danstenziano.com/products/eastern-sierra-high-route-guide"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/finger-lakes/trail.toml b/finger-lakes/trail.toml
index f8c37ca..5658d83 100644
--- a/finger-lakes/trail.toml
+++ b/finger-lakes/trail.toml
@@ -58,13 +58,22 @@ start = "Allegany State Park, New York"
end = "Slide Mountain, Catskills, New York"
shape = "network"
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "sources"
+season_method = "The pages differ: one Trek page gives winter, spring, summer and fall, and a table on the same page gives spring, summer and fall. It was set by judgement from both and from the climate, since snow lies from December to March and early spring is muddy. Confidence: medium."
[[hike.source]]
url = "https://fingerlakestrail.org/"
publisher = "Finger Lakes Trail Conference"
facts = ["official_url", "summary", "start", "end", "shape", "travel"]
+[[hike.source]]
+url = "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
[[link]]
title = "Finger Lakes Trail"
publisher = "LongTrailsWiki"
@@ -89,3 +98,12 @@ basis = "The length was first checked against another site's list, then against
basis_url = "https://fingerlakestrail.org/wp-content/uploads/FLTC_Files/FLTNews/FLTNews2022-3.pdf"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was set from pages that differ: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "The pages that state a season differ and none is the managing body, association or route author, so it was set by judgement from all of them and the climate estimate."
+basis_url = "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/ganaraska/trail.toml b/ganaraska/trail.toml
index 0f24c5a..49b8f69 100644
--- a/ganaraska/trail.toml
+++ b/ganaraska/trail.toml
@@ -57,13 +57,22 @@ official_url = "https://www.ganaraska-hiking-trail.org/"
start = "Port Hope, Ontario"
end = "Bruce Trail, near Collingwood, Ontario"
shape = "point-to-point"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Southern Ontario is snowy in winter and muddy in March, and the trail can be walked from April until late fall. Confidence: medium."
[[hike.source]]
url = "https://www.ganaraska-hiking-trail.org/"
publisher = "Ganaraska Hiking Trail Association"
facts = ["official_url", "summary", "start", "end", "shape"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -119,3 +128,12 @@ basis = "The page quotes the note to visitors, and the prefix only repeated the
basis_url = "https://www.ganaraska-hiking-trail.org/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/general-george-crook/trail.toml b/general-george-crook/trail.toml
index deb14d9..35b7e34 100644
--- a/general-george-crook/trail.toml
+++ b/general-george-crook/trail.toml
@@ -56,7 +56,11 @@ official_url = "https://www.fs.usda.gov/r03/apache-sitgreaves/recreation/trails/
shape = "point-to-point"
travel = "trail"
caution = "The Forest Service's National Recreation Trail record says the trail can be hard to find in some places."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "April to June and September to October"
+months = [4, 5, 6, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Rim country is snowy in winter, and the July and August monsoon brings lightning and storms, leaving spring and fall. Confidence: medium."
[[hike.source]]
url = "https://www.fs.usda.gov/r03/apache-sitgreaves/recreation/trails/general-crook-trail"
@@ -68,6 +72,11 @@ url = "https://www.nrtapplication.org/trails/general-george-crook"
publisher = "National Recreation Trails database (nrtapplication.org), from the trail's 1979 application"
facts = ["summary", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -123,3 +132,12 @@ basis = "The page quotes the note to visitors, and the prefix only repeated the
basis_url = "https://apps.fs.usda.gov/arcx/rest/services/EDW/EDW_TrailNFSPublish_01/MapServer/0"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/georgia-loop/trail.toml b/georgia-loop/trail.toml
index a5835d0..75f0984 100644
--- a/georgia-loop/trail.toml
+++ b/georgia-loop/trail.toml
@@ -76,13 +76,22 @@ shape = "loop"
terrain = ["forest"]
travel = "trail"
caution = "The Association describes the loop as the toughest hike in Georgia."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The north Georgia mountains are hot, humid and stormy in summer and cold and icy on the ridges in winter. Confidence: medium."
[[hike.source]]
url = "https://bmta.org/backpacking-hikes/"
publisher = "Benton MacKaye Trail Association"
facts = ["summary", "official_url", "shape", "terrain", "travel", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -112,3 +121,12 @@ basis = "The page the guide links to is titled \"Benton MacKaye Trail Guide –
basis_url = "https://bmta.org/product/benton-mackaye-trail-guide-ga/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/gila-centennial-loop/trail.toml b/gila-centennial-loop/trail.toml
index 1bff552..0ebd402 100644
--- a/gila-centennial-loop/trail.toml
+++ b/gila-centennial-loop/trail.toml
@@ -52,7 +52,11 @@ terrain = ["canyon"]
travel = "trail"
permit = "Individual hikers need no pass or permit; organised groups need a permit from the Forest Service."
caution = "The Forest Service says the stretch of West Fork Trail 151 along Cooper Canyon to Turkeyfeather Pass is not passable, so check the loop map there. A local trail group reported in November 2024 that the Forest Service crew had cleared the last impassable part of the loop, and that walkers found rough tread in places, such as Trail 159 above Turkey Creek and Trail 101 near private land at Double Spring. The Forest Service says West Fork Trail 151 has many river crossings per mile, and that water in the Gila can be unreliable and must be treated."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Gila canyons at 6,000 feet are hot from June to August, with monsoon storms and flash floods, and cold in winter. Confidence: medium."
[[hike.source]]
url = "https://www.fs.usda.gov/r03/gila/recreation/gila-wilderness-area"
@@ -74,6 +78,11 @@ url = "https://myemail.constantcontact.com/Gila-Trails-News.html?soid=1140320514
publisher = "Gila Trails News (Gila Back Country Horsemen and Gila Trails Info), November 2024 update"
facts = ["caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[guide]]
title = "Gila Wilderness Centennial Loop Trail Map - 24K"
author = "USDA Forest Service, Gila National Forest"
@@ -95,3 +104,12 @@ basis = "The Forest Service's Gila Wilderness page says the 100-mile Centennial
basis_url = "https://www.fs.usda.gov/r03/gila/recreation/gila-wilderness-area"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/grand-valley-trail/trail.toml b/grand-valley-trail/trail.toml
index ff6d3dd..0660bac 100644
--- a/grand-valley-trail/trail.toml
+++ b/grand-valley-trail/trail.toml
@@ -54,13 +54,22 @@ official_url = "https://gvta.on.ca/Grand-Valley-Trails"
start = "Belwood, Ontario"
end = "Port Maitland, Ontario"
shape = "point-to-point"
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A low-elevation southern Ontario footpath that can be walked in all but deep winter and the muddy early spring. Confidence: medium."
[[hike.source]]
url = "https://gvta.on.ca/Grand-Valley-Trails"
publisher = "Grand Valley Trails Association"
facts = ["summary", "official_url", "start", "end", "shape"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -80,3 +89,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://gvta.on.ca/resources/banner-option2D.jpg"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/great-eastern/trail.toml b/great-eastern/trail.toml
index 3ba7da7..c461f5b 100644
--- a/great-eastern/trail.toml
+++ b/great-eastern/trail.toml
@@ -60,7 +60,11 @@ shape = "point-to-point"
travel = "trail"
unfinished = "The trail is made of existing trails that are still being linked, and new trail is needed where gaps remain. Backpacker reported in 2022 that the association had completed over 70 percent since 2007, and that the first end-to-end thru-hike, by two hikers, was in 2013."
days = [120, 180]
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A very long Appalachian walk, started in spring in Alabama and carried through summer humidity and into fall to avoid winter in the north. Confidence: low."
[[hike.source]]
url = "https://www.greateasterntrail.net/about-us/"
@@ -72,6 +76,11 @@ url = "https://www.backpacker.com/trips/trips-by-state/pennsylvania-trails/the-g
publisher = "Backpacker"
facts = ["unfinished", "days"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -145,3 +154,12 @@ basis = "OpenStreetMap's wiki page for route relations says the empty role shoul
basis_url = "https://wiki.openstreetmap.org/wiki/Relation:route"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/great-western-divide-loop/trail.toml b/great-western-divide-loop/trail.toml
index 11f8bc0..ebcd578 100644
--- a/great-western-divide-loop/trail.toml
+++ b/great-western-divide-loop/trail.toml
@@ -67,7 +67,11 @@ start = "Crescent Meadow, Sequoia National Park"
start_lonlat = [-118.748, 36.559]
shape = "loop"
terrain = ["forest", "alpine"]
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Kaweah Gap and the Great Western Divide hold deep snow into early July, and autumn storms return by October. Confidence: medium."
[[hike.source]]
url = "https://www.nps.gov/seki/planyourvisit/high-sierra-trail.htm"
@@ -89,6 +93,11 @@ url = "https://www.brianlucido.com/sequoia-great-western-divide-loop/"
publisher = "Brian Lucido"
facts = ["shape"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -126,3 +135,12 @@ basis = "The record's own guide and source entries already cite the author's pag
basis_url = "https://www.brianlucido.com/sequoia-great-western-divide-loop/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/high-country-pathway/trail.toml b/high-country-pathway/trail.toml
index 503a658..2e9ca46 100644
--- a/high-country-pathway/trail.toml
+++ b/high-country-pathway/trail.toml
@@ -58,7 +58,11 @@ days = [7, 7]
terrain = ["forest"]
travel = "trail"
caution = "Mountain bikers use the pathway as well as hikers."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Northern Michigan forest is snowbound in winter and muddy in early spring, and walkable from May to October, with bugs the main summer complaint. Confidence: medium."
[[hike.source]]
url = "https://www.michigan.org/property/high-country-pathway"
@@ -70,6 +74,11 @@ url = "https://www.trailscouncil.org/high-country-pathway/"
publisher = "Top of Michigan Trails Council"
facts = ["summary", "start", "shape", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -89,3 +98,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.michigan.gov/recsearch/trails/high-country-pathway"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/highlands/trail.toml b/highlands/trail.toml
index 5b4f117..4d58e57 100644
--- a/highlands/trail.toml
+++ b/highlands/trail.toml
@@ -56,13 +56,22 @@ end = "Hudson River, New York"
shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The low New Jersey and New York Highlands ridges are hot, humid and buggy in summer and icy in midwinter. Confidence: medium."
[[hike.source]]
url = "https://nynjtc.org/highlands-trail"
publisher = "New York-New Jersey Trail Conference"
facts = ["official_url", "summary", "start", "end", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -82,3 +91,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://www.nynjtc.org/wp-content/uploads/2024/08/HT-Blaze-Transp-w_-Wht.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/hoosier-heritage-trail/trail.toml b/hoosier-heritage-trail/trail.toml
index 3fec14c..f4f4545 100644
--- a/hoosier-heritage-trail/trail.toml
+++ b/hoosier-heritage-trail/trail.toml
@@ -68,7 +68,11 @@ shape = "point-to-point"
travel = "trail-and-road"
start_lonlat = [-85.863, 38.462]
end_lonlat = [-86.477, 39.323]
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Indiana has hot, humid summers with ticks and thick vegetation, so spring and fall are the most comfortable months. Confidence: medium."
[[hike.source]]
url = "https://hoosierheritagetrail.org/"
@@ -90,6 +94,11 @@ url = "https://github.com/swaits/longhikes/issues/2#issuecomment-6927004842"
publisher = "Hoosier Heritage Trail Association (said by its president on the dataset's issue tracker, 2026-11-16)"
facts = ["summary", "start", "end", "shape", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Knobstone Hiking Trail"
publisher = "Knobstone Hiking Trail Association"
@@ -161,3 +170,12 @@ basis = "The association's Downloads page offers the 2026 mapset, the address an
basis_url = "https://hoosierheritagetrail.org/downloads/"
asked_by = "the trail association's president"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/horse-shoe/trail.toml b/horse-shoe/trail.toml
index a7a0985..2ed8811 100644
--- a/horse-shoe/trail.toml
+++ b/horse-shoe/trail.toml
@@ -57,13 +57,22 @@ start = "Valley Forge National Historical Park, Pennsylvania"
end = "the Appalachian Trail, Dauphin County, Pennsylvania"
shape = "point-to-point"
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Southeast Pennsylvania has humid, buggy summers and icy winters, which leaves spring and fall. Confidence: medium."
[[hike.source]]
url = "https://cart.hstrail.org/"
publisher = "Horse-Shoe Trail Conservancy"
facts = ["official_url", "summary", "start", "end", "shape", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Horse-Shoe Trail"
publisher = "LongTrailsWiki"
@@ -88,3 +97,12 @@ basis = "The pages named in the logo note were searched, and none offers usable
basis_url = "https://cart.hstrail.org/wp-content/uploads/2019/10/horse-shoe_trail_header_1000_logo-1.jpg"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/hot-springs-trail/trail.toml b/hot-springs-trail/trail.toml
index 0ef11b1..d590178 100644
--- a/hot-springs-trail/trail.toml
+++ b/hot-springs-trail/trail.toml
@@ -75,7 +75,11 @@ shape = "point-to-point"
days = [110, 110]
terrain = ["alpine", "lakes"]
travel = "some-cross-country"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to September"
+months = [4, 5, 6, 7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A northbound route of about 110 days from coastal California to Idaho needs the Sierra and the northern mountains clear of snow, so it runs from spring to early fall. Confidence: low."
[[hike.source]]
url = "https://outsideways.com/routes/us/hot-springs-trail/"
@@ -87,6 +91,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/1661401"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["start_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Hot Springs Trail"
publisher = "LongTrailsWiki"
@@ -120,3 +129,12 @@ basis = "The Open Library record gives The Hot Springs Trail: Official Guidebook
basis_url = "https://www.amazon.com/Hot-Springs-Trail-Official-Guidebook/dp/1505613922"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/iat-newfoundland-labrador/trail.toml b/iat-newfoundland-labrador/trail.toml
index fcbbf0d..4983a42 100644
--- a/iat-newfoundland-labrador/trail.toml
+++ b/iat-newfoundland-labrador/trail.toml
@@ -61,7 +61,11 @@ shape = "point-to-point"
travel = "trail-and-road"
unfinished = "The chapter's stated goal is a 750 km extension of the trail; as of 2023 it is made of T'Railway sections, gravel logging roads, backcountry trails and routes, and secondary highways."
days = [35, 50]
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "June to September"
+months = [6, 7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Western Newfoundland is cold, snowy and boggy until June, and storms and snow return in October. Confidence: medium."
[[hike.source]]
url = "https://iatnl.org/thru-hikers/"
@@ -83,6 +87,11 @@ url = "https://iatnl.org/services/thru-hiker-route-details-directions/"
publisher = "International Appalachian Trail Newfoundland and Labrador"
facts = ["days"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "International Appalachian Trail"
publisher = "LongTrailsWiki"
@@ -134,3 +143,12 @@ basis = "The page of International Appalachian Trail Newfoundland and Labrador s
basis_url = "https://iatnl.org/services/thru-hiker-route-details-directions/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/ice-age/trail.toml b/ice-age/trail.toml
index 33a5a96..098e092 100644
--- a/ice-age/trail.toml
+++ b/ice-age/trail.toml
@@ -65,7 +65,11 @@ travel = "trail-and-road"
unfinished = "The trail is about half complete: nearly 700 miles are yellow-blazed Ice Age Trail, and about 500 miles of unmarked connecting routes, mostly on quiet country roads, link the blazed segments."
caution = "Primitive camping is not permitted on many segments, so overnight plans vary widely from night to night."
permit = "No National Park Pass or fee is needed to use the trail."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "sources"
+season_method = "The pages differ: one Trek page gives summer and fall and another gives summer only. It was set by judgement from both and from the climate, since snow and mud last through April and a hard freeze comes by November. Confidence: medium."
[[hike.source]]
url = "https://www.iceagetrail.org/explore/explore-the-trail/ice-age-trail/"
@@ -87,6 +91,16 @@ url = "https://www.nps.gov/iatr/planyourvisit/fees.htm"
publisher = "National Park Service"
facts = ["permit"]
+[[hike.source]]
+url = "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
+[[hike.source]]
+url = "https://thetrek.co/the-best-time-of-year-to-hike-these-23-popular-long-trails/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
[[link]]
title = "Ice Age National Scenic Trail"
publisher = "LongTrailsWiki"
@@ -156,3 +170,12 @@ basis = "The page of National Park Service says: \"A National Park Pass is not r
basis_url = "https://www.nps.gov/iatr/planyourvisit/fees.htm"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was set from pages that differ: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "The pages that state a season differ and none is the managing body, association or route author, so it was set by judgement from all of them and the climate estimate."
+basis_url = "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/international-appalachian-trail-maine/trail.toml b/international-appalachian-trail-maine/trail.toml
index d4f1e1c..eb3c6cf 100644
--- a/international-appalachian-trail-maine/trail.toml
+++ b/international-appalachian-trail-maine/trail.toml
@@ -57,7 +57,11 @@ shape = "point-to-point"
terrain = ["forest", "farmland"]
travel = "trail-and-road"
caution = "Much of the route is on roads, because the chapter has relied on landowners' permission to secure the route."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Northern Maine is snowbound and muddy until late May and frozen from November, and fall is best once the bugs fade. Confidence: medium."
[[hike.source]]
url = "https://maineiat.org/?p=412"
@@ -84,6 +88,11 @@ url = "https://nominatim.openstreetmap.org/ui/details.html?osmtype=N&osmid=12949
publisher = "OpenStreetMap contributors, via Nominatim (ODbL): Barnard Mountain Trailhead, OpenStreetMap node 12949585422"
facts = ["start_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "International Appalachian Trail"
publisher = "LongTrailsWiki"
@@ -117,3 +126,12 @@ basis = "The National Park Service's page for the Barnard Mountain Trailhead say
basis_url = "https://www.nps.gov/places/barnard-mountain-trailhead.htm"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/koroc-palmer-loop/trail.toml b/koroc-palmer-loop/trail.toml
index 5579ba6..31c2c82 100644
--- a/koroc-palmer-loop/trail.toml
+++ b/koroc-palmer-loop/trail.toml
@@ -56,7 +56,11 @@ terrain = ["alpine", "tundra"]
travel = "mostly-cross-country"
permit = "Hikers must register before the trip with both Torngat Mountains National Park and Parc national Kuururjuaq, and de-register after leaving the parks."
caution = "Stream crossings on the Koroc River and its tributaries can be fast and very cold, and they grow harder after heavy rain."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "July to August"
+months = [7, 8]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The Torngat Mountains in the Arctic are snowbound until late June and freeze again by September, leaving a short July and August window. Confidence: medium."
[[hike.source]]
url = "https://parks.canada.ca/pn-np/nl/torngats/activ/randonee-hiking1/koroc"
@@ -68,6 +72,11 @@ url = "https://parcs.canada.ca/pn-np/nl/torngats/activ/randonee-hiking1/koroc"
publisher = "Parks Canada"
facts = ["summary", "shape", "days"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -88,3 +97,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://parks.canada.ca/pn-np/nl/torngats/activ/randonee-hiking1/koroc"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to August."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/la-cloche/trail.toml b/la-cloche/trail.toml
index d423dda..450fa4d 100644
--- a/la-cloche/trail.toml
+++ b/la-cloche/trail.toml
@@ -57,7 +57,11 @@ days = [7, 10]
terrain = ["forest", "lakes"]
travel = "trail"
permit = "Backcountry campsites along the trail are reserved through Ontario Parks."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Killarney is snowbound in winter and buggy in spring, so the warm months are the main window, with September and early October the best. Confidence: medium."
[[hike.source]]
url = "https://www.ontarioparks.ca/park/killarney"
@@ -69,6 +73,11 @@ url = "https://www.ontarioparks.ca/park/killarney/activities"
publisher = "Ontario Parks"
facts = ["start", "days"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -88,3 +97,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.ontarioparks.ca/park/killarney"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/lost-coast/trail.toml b/lost-coast/trail.toml
index 601512f..9229ddf 100644
--- a/lost-coast/trail.toml
+++ b/lost-coast/trail.toml
@@ -58,7 +58,11 @@ terrain = ["coast"]
travel = "trail"
permit = "Overnight camping on the King Range sections needs a Backcountry Permit, booked through Recreation.gov; Sinkyone Wilderness State Park has its own rules for camping."
caution = "On the northern section the BLM tells hikers to research the tides before booking a permit."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "May to September"
+months = [5, 6, 7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Heavy winter rain, slides and high tides make parts of the coast impassable, so the dry months with workable low tides are used. Confidence: high."
[[hike.source]]
url = "https://www.blm.gov/visit/lost-coast-trail"
@@ -70,6 +74,11 @@ url = "https://www.parks.ca.gov/?page_id=28158"
publisher = "California State Parks"
facts = ["summary", "start", "end", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -89,3 +98,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.blm.gov/visit/lost-coast-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/loyalsock/trail.toml b/loyalsock/trail.toml
index 8da361c..f80ee91 100644
--- a/loyalsock/trail.toml
+++ b/loyalsock/trail.toml
@@ -61,7 +61,11 @@ terrain = ["forest"]
travel = "trail"
caution = "Fires are banned along parts of the trail and during the spring fire season, and the club advises hikers to stay off the trail during bear and deer season, which runs about three weeks from the Monday before Thanksgiving."
permit = "No permit is needed to camp one night at a site; a free Loyalsock State Forest camping permit is needed to stay more than one night at one location."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "April to June and September to October"
+months = [4, 5, 6, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Rocky, wet terrain in northern Pennsylvania is best in the cool shoulder seasons, before the humid, buggy summer. Confidence: medium."
[[hike.source]]
url = "https://alpineclubofwilliamsport.com/loyalsock-trail-information/"
@@ -78,6 +82,11 @@ url = "https://alpineclubofwilliamsport.com/faqs/"
publisher = "Alpine Club of Williamsport"
facts = ["permit"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Loyalsock Trail"
publisher = "LongTrailsWiki"
@@ -111,3 +120,12 @@ basis = "The page of Alpine Club of Williamsport says: \"You don't need a permit
basis_url = "https://alpineclubofwilliamsport.com/faqs/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/mason-dixon/trail.toml b/mason-dixon/trail.toml
index dc60f27..1bbeb9a 100644
--- a/mason-dixon/trail.toml
+++ b/mason-dixon/trail.toml
@@ -58,13 +58,22 @@ end = "Chadds Ford, Pennsylvania, on the Brandywine River"
shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The low Susquehanna valley is hot and humid in summer, so the cool spring and fall months suit best. Confidence: medium."
[[hike.source]]
url = "https://masondixontrail.wixsite.com/mdts"
publisher = "Mason-Dixon Trail System"
facts = ["official_url", "summary", "start", "end", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Mason-Dixon Trail"
publisher = "LongTrailsWiki"
@@ -98,3 +107,12 @@ basis = "OpenStreetMap relation 1820324 names one way of each pair Mason-Dixon T
basis_url = "https://www.openstreetmap.org/relation/1820324"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/midland-to-mackinac-trail/trail.toml b/midland-to-mackinac-trail/trail.toml
index 8059428..2333552 100644
--- a/midland-to-mackinac-trail/trail.toml
+++ b/midland-to-mackinac-trail/trail.toml
@@ -55,7 +55,11 @@ terrain = ["forest"]
travel = "trail"
caution = "The 2018 guide states there is no GPS track for the trail and that its maps are bound to be wrong in places."
permit = "Camping along the trail on public land is free, but camping on state land needs a Michigan DNR permit."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Snow and mud last into April in northern Michigan, and the walk is comfortable from June through early fall. Confidence: medium."
[[hike.source]]
url = "https://www.fs.usda.gov/r09/huron-manistee/recreation/trails/midland-mackinaw-trail"
@@ -77,6 +81,11 @@ url = "https://nominatim.openstreetmap.org/ui/details.html?osmtype=R&osmid=13498
publisher = "OpenStreetMap contributors, via Nominatim (ODbL): Mackinaw City, OpenStreetMap relation 134987"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -124,3 +133,12 @@ basis = "The record's own sources: the 2018 guide states there is no GPS track f
basis_url = "https://www.fs.usda.gov/r09/huron-manistee/recreation/trails/midland-mackinaw-trail"
asked_by = "a reviewer"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/midstate-ma/trail.toml b/midstate-ma/trail.toml
index 147f146..9aa6806 100644
--- a/midstate-ma/trail.toml
+++ b/midstate-ma/trail.toml
@@ -59,7 +59,11 @@ shape = "point-to-point"
high_point = "Mount Wachusett"
high_point_m = 611
travel = "trail"
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "April to June and September to November"
+months = [4, 5, 6, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The gentle central Massachusetts hills are pleasant in spring and fall, with humid, buggy summers and cold, icy winters. Confidence: medium."
[[hike.source]]
url = "https://www.midstatetrail.org/"
@@ -71,6 +75,11 @@ url = "https://www.midstatetrail.org/about-the-midstate-trail/old-growth-forest/
publisher = "Midstate Trail Committee"
facts = ["high_point"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -90,3 +99,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://www.midstatetrail.org/wp-content/uploads/2017/06/follow_triangle.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/north-south-lbl/trail.toml b/north-south-lbl/trail.toml
index 265f298..5b4ba14 100644
--- a/north-south-lbl/trail.toml
+++ b/north-south-lbl/trail.toml
@@ -57,7 +57,11 @@ shape = "point-to-point"
terrain = ["forest", "lakes"]
travel = "trail"
permit = "Each person aged 18 or older needs a Land Between the Lakes Backcountry Camping Permit."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The forests of western Kentucky and Tennessee are hot, humid and tick-ridden in summer, so spring and fall are favoured. Confidence: medium."
[[hike.source]]
url = "https://www.landbetweenthelakes.us/outdoors-recreation/trails-3/"
@@ -74,6 +78,11 @@ url = "https://www.landbetweenthelakes.us/help-center/rules-and-regulations/"
publisher = "USDA Forest Service, Land Between the Lakes NRA"
facts = ["permit"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -103,3 +112,12 @@ basis = "The page of USDA Forest Service, Land Between the Lakes NRA says: \"Eac
basis_url = "https://www.landbetweenthelakes.us/help-center/rules-and-regulations/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/north-south/trail.toml b/north-south/trail.toml
index 99eb527..fb3abfc 100644
--- a/north-south/trail.toml
+++ b/north-south/trail.toml
@@ -54,7 +54,11 @@ official_url = "https://www.rigis.org/datasets/north-south-trail"
shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Rhode Island woods are humid and buggy in summer and cold in winter. Confidence: medium."
[[hike.source]]
url = "https://www.rigis.org/datasets/north-south-trail"
@@ -66,6 +70,11 @@ url = "https://dem.ri.gov/sites/g/files/xkgbur861/files/programs/bnatres/fishwil
publisher = "Rhode Island Department of Environmental Management"
facts = ["summary", "terrain"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "North-South Trail"
publisher = "LongTrailsWiki"
@@ -90,3 +99,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.rigis.org/datasets/north-south-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/north-umpqua/trail.toml b/north-umpqua/trail.toml
index 0d9ff89..0121ec9 100644
--- a/north-umpqua/trail.toml
+++ b/north-umpqua/trail.toml
@@ -55,7 +55,11 @@ official_url = "https://www.fs.usda.gov/r06/umpqua/recreation/groups/north-umpqu
shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The upper Cascade sections near 6,000 feet hold snow into June and see heavy rain and snow from late October, though the river canyon can be walked earlier. Confidence: medium."
[[hike.source]]
url = "https://www.fs.usda.gov/r06/umpqua/recreation/groups/north-umpqua-trail-1414"
@@ -72,6 +76,11 @@ url = "https://www.blm.gov/visit/north-umpqua-wild-and-scenic-river"
publisher = "Bureau of Land Management"
facts = ["summary", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "North Umpqua Trail"
publisher = "LongTrailsWiki"
@@ -105,3 +114,12 @@ basis = "The record has a published track file and a measured length in its veri
basis_url = "https://apps.fs.usda.gov/arcx/rest/services/EDW/EDW_TrailNFSPublish_01/MapServer/0"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/oak-ridges/trail.toml b/oak-ridges/trail.toml
index da98011..a3d2016 100644
--- a/oak-ridges/trail.toml
+++ b/oak-ridges/trail.toml
@@ -57,7 +57,11 @@ shape = "point-to-point"
terrain = ["forest", "farmland"]
travel = "trail-and-road"
caution = "There are no overnight accommodations on the trail and camping is not permitted."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The southern Ontario moraine is snowy and muddy over winter and can be walked from April until late fall. Confidence: medium."
[[hike.source]]
url = "https://www.oakridgestrail.org/end-to-end-hike/"
@@ -69,6 +73,11 @@ url = "https://www.oakridgestrail.org/chapters/"
publisher = "Oak Ridges Trail Association"
facts = ["summary", "start", "end", "terrain"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -88,3 +97,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://www.oakridgestrail.org/wp-content/uploads/2024/07/favicon.jpg"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/ottawa-temiskaming-highland-trail/trail.toml b/ottawa-temiskaming-highland-trail/trail.toml
index df31ca3..711d30b 100644
--- a/ottawa-temiskaming-highland-trail/trail.toml
+++ b/ottawa-temiskaming-highland-trail/trail.toml
@@ -57,7 +57,11 @@ shape = "point-to-point"
terrain = ["forest", "lakes"]
travel = "trail"
caution = "The trail planner calls it a rugged wilderness trail."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Northeastern Ontario forest is snowbound and muddy until May, with black flies in early summer, and cold by November. Confidence: medium."
[[hike.source]]
url = "https://nastawgantrails.org/our-trails"
@@ -84,6 +88,11 @@ url = "https://geogratis.gc.ca/services/geoname/en/geonames/FDNSB"
publisher = "Natural Resources Canada (Canadian Geographical Names)"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -103,3 +112,12 @@ basis = "The pages named in the logo note were searched, and none offers usable
basis_url = "https://nastawgantrails.org/our-trails"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/ouachita/trail.toml b/ouachita/trail.toml
index 6d3e99a..d01d69a 100644
--- a/ouachita/trail.toml
+++ b/ouachita/trail.toml
@@ -62,7 +62,11 @@ terrain = ["forest"]
travel = "trail"
days = [14, 21]
permit = "No permits are required for the trail."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "March to May and October to November"
+months = [3, 4, 5, 10, 11]
+season_basis = "sources"
+season_method = "The pages differ: one gives April to November, one gives late October to late March, and one gives all year. It was set by judgement from all three and from the climate, since summers are hot and humid with ticks and winters are cold but walkable. Confidence: medium."
[[hike.source]]
url = "https://www.friendsoftheouachita.org/about-the-ot"
@@ -79,6 +83,21 @@ url = "https://www.treelinereview.com/where-to-go/ouachita-trail"
publisher = "Treeline Review"
facts = ["days", "permit"]
+[[hike.source]]
+url = "https://thehikinglife.com/2014/07/ouachita-trail/"
+publisher = "The Hiking Life"
+facts = ["season", "months"]
+
+[[hike.source]]
+url = "https://backpackingroutes.com/ouachita-trail/"
+publisher = "Backpacking Routes"
+facts = ["season", "months"]
+
+[[hike.source]]
+url = "https://thetrek.co/10-trails-can-find-long-distance-solitude-2020/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
[[link]]
title = "Ouachita Trail"
publisher = "LongTrailsWiki"
@@ -121,3 +140,12 @@ basis = "The page of Treeline Review says: \"Time to hike the entire trail: 2-3
basis_url = "https://www.treelinereview.com/where-to-go/ouachita-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was set from pages that differ: March to May and October to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "The pages that state a season differ and none is the managing body, association or route author, so it was set by judgement from all of them and the climate estimate."
+basis_url = "https://thehikinglife.com/2014/07/ouachita-trail/"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/ozark-trail/trail.toml b/ozark-trail/trail.toml
index eeed09f..c90b0b1 100644
--- a/ozark-trail/trail.toml
+++ b/ozark-trail/trail.toml
@@ -59,7 +59,11 @@ end = "Western edge of the Mark Twain National Forest, Missouri"
shape = "point-to-point"
travel = "trail"
unfinished = "The St. Louis to Arkansas border route is not complete; about 230 miles form the contiguous thru-hike backbone."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "sources"
+season_method = "The pages differ: one Trek page gives spring or fall and another adds winter. It was set by judgement from both and from the climate, since the heat, humidity and ticks of July and August make summer a poor choice. Confidence: medium."
[[hike.source]]
url = "https://ozarktrail.com/thru-hiking/"
@@ -76,6 +80,16 @@ url = "https://www.fs.usda.gov/r09/marktwain/recreation/ozark-trail"
publisher = "USDA Forest Service, Mark Twain National Forest"
facts = ["start", "end"]
+[[hike.source]]
+url = "https://thetrek.co/the-best-time-of-year-to-hike-these-23-popular-long-trails/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
+[[hike.source]]
+url = "https://thetrek.co/a-list-of-long-distance-trails-in-the-us/"
+publisher = "The Trek"
+facts = ["season", "months"]
+
[[link]]
title = "Ozark Trail"
publisher = "LongTrailsWiki"
@@ -118,3 +132,12 @@ basis = "OpenStreetMap relation 16710911 names the two ways Eleven Point Low Rou
basis_url = "https://www.openstreetmap.org/relation/16710911"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was set from pages that differ: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "The pages that state a season differ and none is the managing body, association or route author, so it was set by judgement from all of them and the climate estimate."
+basis_url = "https://thetrek.co/the-best-time-of-year-to-hike-these-23-popular-long-trails/"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/paumanok-path/trail.toml b/paumanok-path/trail.toml
index 3a52a97..0f79099 100644
--- a/paumanok-path/trail.toml
+++ b/paumanok-path/trail.toml
@@ -55,7 +55,11 @@ start = "Rocky Point, New York"
end = "Montauk Point, New York"
shape = "point-to-point"
terrain = ["forest", "coast"]
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Long Island is humid and tick-heavy in summer, and the pine barrens are pleasant in the cool shoulder seasons. Confidence: medium."
[[hike.source]]
url = "https://southamptontrails.org/history/"
@@ -67,6 +71,11 @@ url = "https://www.ligreenbelt.org/about-greenbelt-trails"
publisher = "Long Island Greenbelt Trail Conference"
facts = ["summary", "terrain"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -86,3 +95,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://southamptontrails.org/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/pfiffner-traverse/trail.toml b/pfiffner-traverse/trail.toml
index c7edb78..c50ccf0 100644
--- a/pfiffner-traverse/trail.toml
+++ b/pfiffner-traverse/trail.toml
@@ -75,7 +75,11 @@ days = [6, 10]
terrain = ["alpine", "forest", "lakes"]
travel = "some-cross-country"
permit = "The Rocky Mountain National Park portion requires use of designated backcountry campsites, arranged through the park permit system described in the guide."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A Continental Divide crest route above 11,000 feet with off-trail passes needs the snow gone, which is from July until the first big September storms. Confidence: high."
[[hike.source]]
url = "https://andrewskurka.com/adventures/pfiffner-traverse-colorado-rockies/"
@@ -102,6 +106,11 @@ url = "https://nominatim.openstreetmap.org/ui/details.html?osmtype=N&osmid=45276
publisher = "OpenStreetMap contributors, via Nominatim (ODbL): Milner Pass, OpenStreetMap node 4527663577"
facts = ["start_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -139,3 +148,12 @@ basis = "The page the guide links to is titled \"Pfiffner Traverse Guide -- Down
basis_url = "https://andrewskurka.com/product/pfiffner-traverse-guide-maps/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/rideau-trail/trail.toml b/rideau-trail/trail.toml
index 8faf36b..ba5e7c0 100644
--- a/rideau-trail/trail.toml
+++ b/rideau-trail/trail.toml
@@ -56,7 +56,11 @@ end = "Ottawa, Ontario"
shape = "point-to-point"
caution = "Many parts of the trail network close during the Ontario fall hunting season, and overnight accommodation is sparse along much of the trail."
days = [9, 16]
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Eastern Ontario is snowy and muddy over winter, and the trail can be walked from April until late fall. Confidence: medium."
[[hike.source]]
url = "https://www.rideautrail.org/discover-the-trail/"
@@ -73,6 +77,11 @@ url = "https://www.rideautrail.org/discover-the-trail/faq/"
publisher = "Rideau Trail Association"
facts = ["days"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Rideau Trail"
publisher = "LongTrailsWiki"
@@ -97,3 +106,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://www.rideautrail.org/wp-content/uploads/2022/06/RTA_icon.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/ring-the-peak/trail.toml b/ring-the-peak/trail.toml
index 89eb61a..04ef3cc 100644
--- a/ring-the-peak/trail.toml
+++ b/ring-the-peak/trail.toml
@@ -52,13 +52,22 @@ high_point_m = 3444
travel = "trail-and-road"
unfinished = "About 80 percent of the route is complete, and evaluation and planning continue for the remaining 20 percent."
caution = "Many of the trails are covered by snow in winter."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A loop around Pikes Peak that mixes stretches near 11,000 feet with lower trails, and is snow-free from about June to October. Confidence: low."
[[hike.source]]
url = "https://friendsofthepeak.org/ring-the-peak-2/"
publisher = "Friends of the Peak"
facts = ["official_url", "summary", "shape", "high_point", "travel", "unfinished", "caution"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -78,3 +87,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://friendsofthepeak.org/ring-the-peak-2/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/sawtooth-wilderness-high-route/trail.toml b/sawtooth-wilderness-high-route/trail.toml
index 3587a0e..1f5aa30 100644
--- a/sawtooth-wilderness-high-route/trail.toml
+++ b/sawtooth-wilderness-high-route/trail.toml
@@ -70,7 +70,11 @@ terrain = ["alpine", "lakes"]
travel = "mostly-cross-country"
permit = "A free wilderness permit is obtained by self-registration at the trailhead, and there is no fee to access the Sawtooth Wilderness."
caution = "The planned route was about 89 miles with over 50 miles off-trail; the hike its author recorded covered 67 miles."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Mostly cross-country passes near 9,000 feet and above need the snow gone, which is from mid-July through September. Confidence: high."
[[hike.source]]
url = "https://seekinglost.com/sawtooth-wilderness-high-route-8-day-solo-hike-aug-2017/"
@@ -82,6 +86,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/388386"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["start_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -110,3 +119,12 @@ basis = "The author of Seeking Lost names himself as Eric Poulin in the descript
basis_url = "https://voyagedenver.com/interview/check-out-eric-poulins-story/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/sea-to-sea-route/trail.toml b/sea-to-sea-route/trail.toml
index 3473597..317b7a5 100644
--- a/sea-to-sea-route/trail.toml
+++ b/sea-to-sea-route/trail.toml
@@ -75,13 +75,22 @@ summary = "The Sea-to-Sea Route is a network of existing long-distance hiking tr
official_url = "https://andrewskurka.com/adventures/sea-to-sea-route/overview/"
shape = "network"
unfinished = "An 800-mile gap in North Dakota and Montana along the Missouri River and a 30-mile gap in Vermont interrupt the network."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to October"
+months = [4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A 7,775-mile coast-to-coast network across the northern prairie, the Rockies and the Cascades can only be walked from spring thaw to autumn snow. Confidence: low."
[[hike.source]]
url = "https://andrewskurka.com/adventures/sea-to-sea-route/overview/"
publisher = "Andrew Skurka"
facts = ["summary", "official_url", "shape", "unfinished"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -119,3 +128,12 @@ basis = "The page the guide links to is titled \"Great Western Loop and Sea-to-S
basis_url = "https://andrewskurka.com/product/slideshows-on-disk-great-western-loop-and-sea-to-sea-route/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/shawangunk-ridge-trail/trail.toml b/shawangunk-ridge-trail/trail.toml
index d9618fc..5de5729 100644
--- a/shawangunk-ridge-trail/trail.toml
+++ b/shawangunk-ridge-trail/trail.toml
@@ -59,13 +59,22 @@ shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
unfinished = "The Trail Conference calls the trail a work in progress: it is blazed to Mountain Rest Road near Mohonk Mountain House, and local roads lead on from there."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A Hudson Valley ridge with humid, buggy summers and icy winters, so spring and fall are the most comfortable months. Confidence: medium."
[[hike.source]]
url = "https://secure.nynjtc.org/node/874"
publisher = "New York-New Jersey Trail Conference"
facts = ["official_url", "summary", "start", "end", "shape", "terrain", "travel", "unfinished"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -85,3 +94,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://secure.nynjtc.org/region/shawangunk-ridge-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/shenipsit-trail/trail.toml b/shenipsit-trail/trail.toml
index 6703a35..58fd572 100644
--- a/shenipsit-trail/trail.toml
+++ b/shenipsit-trail/trail.toml
@@ -56,13 +56,22 @@ end = "West Stafford, Connecticut"
shape = "point-to-point"
terrain = ["forest"]
travel = "trail"
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Central Connecticut has humid, buggy summers and cold, icy winters, so spring and fall are best. Confidence: medium."
[[hike.source]]
url = "https://ctwoodlands.org/trails/shenipsit-trail/"
publisher = "Connecticut Forest and Park Association"
facts = ["official_url", "summary", "start", "end", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -83,3 +92,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://ctwoodlands.org/trails/shenipsit-trail/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/sierra-high-route/trail.toml b/sierra-high-route/trail.toml
index a2f5085..6bc9241 100644
--- a/sierra-high-route/trail.toml
+++ b/sierra-high-route/trail.toml
@@ -89,7 +89,11 @@ terrain = ["alpine", "lakes"]
travel = "mostly-cross-country"
days = [14, 21]
permit = "A permit is needed from the agency that manages the trailhead where you start."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "sources"
+season_method = "The pages differ: Backpacking Routes gives late July to mid-September, and Skurka warns the route is off-limits to all but expert mountaineers from November through May. It was set by judgement from both and from the climate at the passes, which are near 12,000 feet. Confidence: high."
[[hike.source]]
url = "https://www.mountaineers.org/books/books/sierra-high-route-2nd-edition-traversing-timberline-country"
@@ -114,7 +118,12 @@ facts = ["end_lonlat"]
[[hike.source]]
url = "https://andrewskurka.com/adventures/sierra-high-route/logistical-considerations/"
publisher = "Andrew Skurka (the route's author)"
-facts = ["permit"]
+facts = ["permit", "season", "months"]
+
+[[hike.source]]
+url = "https://backpackingroutes.com/sierra-high-route/"
+publisher = "Backpacking Routes"
+facts = ["season", "months"]
[[link]]
title = "Sierra High Route"
@@ -167,3 +176,12 @@ basis = "The page the guide links to is titled \"Sierra High Route Mapset & Data
basis_url = "https://andrewskurka.com/product/sierra-high-route-map-set-databook/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was set from pages that differ: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "The pages that state a season differ and none is the managing body, association or route author, so it was set by judgement from all of them and the climate estimate."
+basis_url = "https://andrewskurka.com/adventures/sierra-high-route/logistical-considerations/"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/siskiyou-peaks-trail/trail.toml b/siskiyou-peaks-trail/trail.toml
index d5e56af..260afe9 100644
--- a/siskiyou-peaks-trail/trail.toml
+++ b/siskiyou-peaks-trail/trail.toml
@@ -79,7 +79,11 @@ terrain = ["alpine", "lakes"]
travel = "some-cross-country"
permit = "The Forest Service requires a free wilderness permit to enter the Mount Shasta Wilderness, and a Summit Pass above 10,000 feet on the mountain."
caution = "The route's last summit is Mt Shasta, a glaciated volcano that the Forest Service says has no trail to its top. Booksellers' copies of the guidebook's description disagree (read 2026-11-19): one says no advanced mountaineering equipment or specialty training is required in summer, though basic rock scrambling and navigation skills are, and another says advanced mountaineering equipment and specialty training may be required."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The summits and cirque lakes are snowbound until late June, and Shasta is climbed in summer. Confidence: medium."
[[hike.source]]
url = "https://outsideways.com/routes/us/siskiyou-peaks-trail/"
@@ -106,6 +110,11 @@ url = "https://nominatim.openstreetmap.org/lookup?osm_ids=R186688,R12859263&form
publisher = "OpenStreetMap contributors, via Nominatim (ODbL): the town boundaries of Ashland (relation 186688) and Mount Shasta (relation 12859263), at their centres"
facts = ["start_lonlat", "end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -126,3 +135,12 @@ basis = "The AbeBooks listing gives the 2017 CreateSpace paperback with ISBN 978
basis_url = "https://www.abebooks.com/9781983447525/Siskiyou-Peaks-Trail-Ashland-Shasta-1983447528/plp"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/sky-islands-traverse/trail.toml b/sky-islands-traverse/trail.toml
index 699759d..dd9eee2 100644
--- a/sky-islands-traverse/trail.toml
+++ b/sky-islands-traverse/trail.toml
@@ -72,7 +72,11 @@ shape = "point-to-point"
terrain = ["desert", "forest", "canyon"]
travel = "some-cross-country"
caution = "Since 2023 its author has withdrawn the detailed route information and does not encourage hiking the exact layout, saying fires and floods have reclaimed many miles of trail."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Summer heat and the July and August monsoon storms in southeastern Arizona push the walk into spring and fall. Confidence: low."
[[hike.source]]
url = "https://simblissity.net/skit.shtml"
@@ -84,6 +88,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/11334"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Sky Islands Traverse"
publisher = "LongTrailsWiki"
@@ -99,3 +108,12 @@ fields = ["record"]
basis = "The record's own source entry: Brett Tucker."
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/solitude-loop/trail.toml b/solitude-loop/trail.toml
index b1b6b42..d66ee5b 100644
--- a/solitude-loop/trail.toml
+++ b/solitude-loop/trail.toml
@@ -57,7 +57,11 @@ terrain = ["alpine", "forest", "lakes"]
travel = "trail"
caution = "Part of the trail lies in a special regulation area where visitors must pack out all human waste, and uses allowed vary from segment to segment."
permit = "A free self-issued Forest Service registration, signed and dated for each visit, is needed to enter Cloud Peak Wilderness, which the loop circles."
-checked = "2026-11-19"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Cloud Peak Wilderness at 9,000 to 11,000 feet holds snow into early July, and winter storms return in late September. Confidence: high."
[[hike.source]]
url = "https://www.fs.usda.gov/r02/bighorn/recreation/trails/solitude-loop-trail-038"
@@ -69,6 +73,11 @@ url = "https://www.fs.usda.gov/r02/bighorn/alerts/forest-special-order-02-02-26-
publisher = "USDA Forest Service, Bighorn National Forest"
facts = ["permit"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -107,3 +116,12 @@ basis = "The page of USDA Forest Service, Bighorn National Forest says: \"Enteri
basis_url = "https://www.fs.usda.gov/r02/bighorn/alerts/forest-special-order-02-02-26-01-cloud-peak-wilderness-regulations"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/standing-stone/trail.toml b/standing-stone/trail.toml
index b9dde56..43cc048 100644
--- a/standing-stone/trail.toml
+++ b/standing-stone/trail.toml
@@ -60,7 +60,11 @@ terrain = ["forest"]
travel = "trail"
high_point = "Greenwood fire tower"
high_point_m = 725
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "April to June and September to October"
+months = [4, 5, 6, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Humid, buggy summers and icy winters on the Pennsylvania ridges leave spring and fall as the usual window. Confidence: medium."
[[hike.source]]
url = "https://www.standingstonetrail.org/"
@@ -72,6 +76,11 @@ url = "https://www.standingstonetrail.org/about"
publisher = "Standing Stone Trail Club"
facts = ["high_point"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Standing Stone Trail"
publisher = "LongTrailsWiki"
@@ -96,3 +105,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://static.wixstatic.com/media/30a84d_b3362299a6fc4aa097db41e071b2789f.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: April to June and September to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/stein-valley-traverse/trail.toml b/stein-valley-traverse/trail.toml
index 4821ac8..2265bc3 100644
--- a/stein-valley-traverse/trail.toml
+++ b/stein-valley-traverse/trail.toml
@@ -58,7 +58,11 @@ terrain = ["forest", "alpine", "lakes"]
travel = "some-cross-country"
permit = "BC Parks' park brochure says there is no hiker registration in the Stein Valley."
caution = "BC Parks says solid route finding skills are a necessity, because sections of trail may be wet, steep or difficult to see, and the upper valley above treeline is a route marked in places with cairns."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The traverse tops out around 7,000 feet, where snow lingers into July, and heavy rain starts in October. Confidence: medium."
[[hike.source]]
url = "https://bcparks.ca/stein-valley-nlakapamux-heritage-park/"
@@ -75,6 +79,11 @@ url = "https://nrs.objectstore.gov.bc.ca/kuwyyf/stein_valley_brochure_d174525f71
publisher = "BC Parks"
facts = ["summary", "start", "end", "shape", "permit"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -95,3 +104,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://bcparks.ca/stein-valley-nlakapamux-heritage-park/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/sunapee-ragged-kearsarge/trail.toml b/sunapee-ragged-kearsarge/trail.toml
index 17c83c9..dcff223 100644
--- a/sunapee-ragged-kearsarge/trail.toml
+++ b/sunapee-ragged-kearsarge/trail.toml
@@ -56,13 +56,22 @@ official_url = "https://www.srkg.org/"
shape = "loop"
terrain = ["forest", "lakes"]
travel = "trail"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "June to October"
+months = [6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. New Hampshire snow and mud last into spring and black flies into early June, with foliage-season walking into early October. Confidence: medium."
[[hike.source]]
url = "https://www.srkg.org/"
publisher = "Sunapee-Ragged-Kearsarge Greenway Coalition"
facts = ["summary", "official_url", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -82,3 +91,12 @@ basis = "The emblem is shown by its holder or by the managing agency on the page
basis_url = "https://www.srkg.org/wp-content/uploads/2026/01/srkg-1024.png"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: June to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/tahoe-yosemite-trail/trail.toml b/tahoe-yosemite-trail/trail.toml
index 3fd02df..028c2f5 100644
--- a/tahoe-yosemite-trail/trail.toml
+++ b/tahoe-yosemite-trail/trail.toml
@@ -71,7 +71,11 @@ shape = "point-to-point"
terrain = ["alpine", "forest", "lakes"]
travel = "some-cross-country"
caution = "The route is unofficial; the Forest Service describes even its northernmost part at Meeks Bay as the unofficial Tahoe-Yosemite Trail."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. High Sierra passes up to about 10,000 feet hold snow until early July, and fall storms arrive in October. Confidence: high."
[[hike.source]]
url = "https://shop.adventurewithkeen.com/wilderness-press/"
@@ -93,6 +97,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/255168"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Tahoe-Yosemite Trail"
publisher = "LongTrailsWiki"
@@ -126,3 +135,12 @@ basis = "The Open Library record gives The Tahoe-Yosemite Trail, Thomas Winnett,
basis_url = "https://openlibrary.org/books/OL2377803M"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/tools/season.py b/tools/season.py
index 7c9a351..979fdbf 100644
--- a/tools/season.py
+++ b/tools/season.py
@@ -204,7 +204,8 @@ def phrase_for(months):
One run reads "June to September", a run over the year end reads
"November to March", separate runs are joined with "and", one month
- reads "July" and twelve read "All year".
+ reads "July" and twelve read "All year". Separate runs come in calendar
+ order, so spring and fall read "March to May and October to November".
"""
got = _months(months)
if len(got) == 12:
@@ -220,9 +221,8 @@ def phrase_for(months):
runs.append((start, prev))
if len(runs) > 1 and runs[0][0] == 1 and runs[-1][1] == 12:
runs = [(runs[-1][0], runs[0][1])] + runs[1:-1]
- first = span(got)[0]
- while runs and runs[0][0] != first:
- runs.append(runs.pop(0))
+ # calendar order, except that a run over the year end comes first
+ runs.sort(key=lambda run: (run[0] <= run[1], run[0]))
def words(run):
a, b = run
diff --git a/tools/season_judged.tsv b/tools/season_judged.tsv
index 93518e6..798dadd 100644
--- a/tools/season_judged.tsv
+++ b/tools/season_judged.tsv
@@ -145,7 +145,7 @@ ocean-to-lake 1,2,3,11,12 November to March high South Florida is hot, wet and b
oregon-coast 5,6,7,8,9 May to September medium The coast gets 10-16 inches of rain a month from November to March and the drier months from May to September make beach walking and creek crossings workable.
oregon-desert 4,5,6,9,10 Spring and fall medium High desert at 3,000-8,000 ft is hot and waterless in July and August and cold in winter, so spring and fall are the walking windows.
ottawa-temiskaming-highland-trail 6,7,8,9,10 June to October medium Northeastern Ontario forest is snowbound and muddy until May, with black flies in early summer, and cold by November.
-ouachita 3,4,5,10,11 October to November and March to May medium The pages differ: one gives April to November, one gives late October to late March, and one gives all year. It was set by judgement from all three and from the climate, since summers are hot and humid with ticks and winters are cold but walkable.
+ouachita 3,4,5,10,11 March to May and October to November medium The pages differ: one gives April to November, one gives late October to late March, and one gives all year. It was set by judgement from all three and from the climate, since summers are hot and humid with ticks and winters are cold but walkable.
ozark-highlands 3,4,5,10,11 Spring and fall medium Arkansas Ozark summers are hot, humid and buggy and winters are cold but popular for leaf-off views, so spring and fall are the typical seasons.
ozark-trail 3,4,5,9,10,11 March to May and September to November medium The pages differ: one Trek page gives spring or fall and another adds winter. It was set by judgement from both and from the climate, since the heat, humidity and ticks of July and August make summer a poor choice.
pacific-crest 4,5,6,7,8,9,10 April to October medium A thru-hike starts at the desert border in April or May, crosses the Sierra after the June to July snowmelt, and must finish the Washington Cascades by early October.
diff --git a/tools/tests/test_season_fit.py b/tools/tests/test_season_fit.py
index 3a2c968..d0e0255 100644
--- a/tools/tests/test_season_fit.py
+++ b/tools/tests/test_season_fit.py
@@ -41,7 +41,10 @@ class SeasonFitFileTest(unittest.TestCase):
self.assertEqual(fit["rule_version"], E.RULE_VERSION)
self.assertEqual(fit["passes"], E.passes_bar(fit["loo"], fit["bar"]))
- def test_estimates_only_with_a_passing_fit(self):
+ def test_estimates_only_over_the_bar_by_the_blind_test(self):
+ """The machine estimate on its own is under the bar and is never
+ written to a record. Estimated seasons are judged, and the judged
+ method must pass the bar in its blind test."""
estimated = []
for tid in refresh.trail_ids(V.ROOT):
rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
@@ -49,12 +52,10 @@ class SeasonFitFileTest(unittest.TestCase):
estimated.append(tid)
if not estimated:
self.skipTest("no estimated seasons on file yet")
- fit = load_fit()
- self.assertTrue(fit["passes"], fit)
- held = fit["loo"]
- self.assertGreaterEqual(held["within1"] / held["n"],
- E.BAR["within1_min"])
-
+ import season_judge
+ blind = season_judge.load_blind_test()
+ self.assertEqual(season_judge.check_blind_test(blind), [])
+ self.assertGreaterEqual(blind["share"], E.BAR["within1_min"])
if __name__ == "__main__":
unittest.main()
diff --git a/tools/tests/test_season_helpers.py b/tools/tests/test_season_helpers.py
index 0e8dd25..edca163 100644
--- a/tools/tests/test_season_helpers.py
+++ b/tools/tests/test_season_helpers.py
@@ -54,6 +54,10 @@ class PhraseTest(unittest.TestCase):
self.assertEqual(season.phrase_for([11, 12, 1, 2, 3]), "November to March")
self.assertEqual(season.phrase_for([4, 5, 9, 10]),
"April to May and September to October")
+ self.assertEqual(season.phrase_for([3, 4, 5, 10, 11]),
+ "March to May and October to November")
+ self.assertEqual(season.phrase_for([11, 12, 1, 2, 6, 7, 8]),
+ "November to February and June to August")
self.assertEqual(season.phrase_for([7]), "July")
self.assertEqual(season.phrase_for(list(range(1, 13))), "All year")
diff --git a/tuscarora/trail.toml b/tuscarora/trail.toml
index 1be52ba..6c0c73b 100644
--- a/tuscarora/trail.toml
+++ b/tuscarora/trail.toml
@@ -56,13 +56,22 @@ end = "Appalachian Trail atop Blue Mountain near Duncannon, Pennsylvania"
shape = "point-to-point"
terrain = ["forest", "farmland"]
travel = "trail-and-road"
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The Ridge and Valley Appalachians are hot, humid and buggy in summer and icy in winter, so spring and fall are the comfortable months. Confidence: medium."
[[hike.source]]
url = "https://www.patc.net/tuscarora-trail"
publisher = "Potomac Appalachian Trail Club"
facts = ["summary", "official_url", "start", "end", "shape", "terrain", "travel"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
[[link]]
title = "Tuscarora Trail"
publisher = "LongTrailsWiki"
@@ -87,3 +96,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.patc.net/tuscarora-trail"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/vagabond-loop/trail.toml b/vagabond-loop/trail.toml
index b463cbd..d538c57 100644
--- a/vagabond-loop/trail.toml
+++ b/vagabond-loop/trail.toml
@@ -66,13 +66,22 @@ official_url = "https://www.freedirtmonger.com/p/vagabond-loop-four-corners-conn
start = "Mexican border on the Arizona Trail, Arizona"
shape = "loop"
terrain = ["desert"]
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "March to October"
+months = [3, 4, 5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. A 3,500-mile circuit of Arizona, Utah, Colorado and New Mexico must start in the desert in early spring and cross the high Colorado Trail country in summer, before fall snow. Confidence: low."
[[hike.source]]
url = "https://www.freedirtmonger.com/p/vagabond-loop-four-corners-connection-1.html"
publisher = "Ryan \"Dirtmonger\" Sylva"
facts = ["summary", "official_url", "start", "shape", "terrain"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -101,3 +110,12 @@ basis = "The author's page carried a description and no track, and its domain no
basis_url = "https://www.freedirtmonger.com/p/vagabond-loop-four-corners-connection-1.html"
asked_by = "a reviewer"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/warrior-trail/trail.toml b/warrior-trail/trail.toml
index 4f12bb4..f701e0a 100644
--- a/warrior-trail/trail.toml
+++ b/warrior-trail/trail.toml
@@ -54,7 +54,11 @@ end_lonlat = [-80.743, 39.92]
shape = "point-to-point"
terrain = ["farmland"]
caution = "The trail passes through private property, and walkers are asked to be courteous to the landowners and the volunteers who maintain it."
-checked = "2026-11-14"
+checked = "2026-11-20"
+season = "March to May and September to November"
+months = [3, 4, 5, 9, 10, 11]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Farmland ridges in southwestern Pennsylvania are overgrown, humid and buggy in summer and icy in winter. Confidence: medium."
[[hike.source]]
url = "https://visitgreene.org/?p=1265"
@@ -71,6 +75,11 @@ url = "https://www.usgs.gov/us-board-on-geographic-names/domestic-names"
publisher = "U.S. Geological Survey, Geographic Names Information System (GNIS 1176170 Greensboro, PA; 1543607 Moundsville, WV)"
facts = ["start_lonlat", "end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -90,3 +99,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://visitgreene.org/?p=1265"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: March to May and September to November."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/wasatch-traverse/trail.toml b/wasatch-traverse/trail.toml
index 4824d3f..f0c437a 100644
--- a/wasatch-traverse/trail.toml
+++ b/wasatch-traverse/trail.toml
@@ -69,13 +69,22 @@ terrain = ["alpine", "forest"]
travel = "some-cross-country"
caution = "The off-trail sections range from straightforward scrambling to heavy bushwhacking, and detailed maps and a compass are essential."
days = [11, 11]
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The high Wasatch ridges and off-trail sections hold snow until late June and get early autumn storms, so midsummer fits a whole traverse. Confidence: low."
[[hike.source]]
url = "https://www.eathomas.com/other-long-trails/wasatchoverview"
publisher = "Liz Thomas"
facts = ["summary", "official_url", "start", "end", "shape", "terrain", "travel", "caution", "days"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -95,3 +104,12 @@ basis = "The route page lists the paper maps the author used and offers no track
basis_url = "https://www.eathomas.com/other-long-trails/wasatchoverview"
asked_by = "a reviewer"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/waskahegan/trail.toml b/waskahegan/trail.toml
index 2f554a0..ee1517b 100644
--- a/waskahegan/trail.toml
+++ b/waskahegan/trail.toml
@@ -51,7 +51,11 @@ shape = "loop"
terrain = ["farmland", "prairie"]
travel = "trail"
caution = "Much of the trail is on private land; the agreement with landowners allows travel only on the marked trail, crossing fences by the stiles provided."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Edmonton-area farmland and parkland is snow-covered and muddy from November to April, and walked from late spring to early fall. Confidence: low."
[[hike.source]]
url = "https://waskahegantrail.ca/about-2/"
@@ -68,6 +72,11 @@ url = "https://explore-mag.com/The-10-Best-Hiking-Trails-Near-Edmonton/"
publisher = "Explore magazine"
facts = ["shape"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -96,3 +105,12 @@ basis = "Explore magazine's list of hiking trails near Edmonton gives the Waskah
basis_url = "https://explore-mag.com/The-10-Best-Hiking-Trails-Near-Edmonton/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/western-uplands/trail.toml b/western-uplands/trail.toml
index d5b5b6b..f12eb09 100644
--- a/western-uplands/trail.toml
+++ b/western-uplands/trail.toml
@@ -58,7 +58,11 @@ shape = "loop"
terrain = ["forest", "lakes"]
travel = "trail"
permit = "Backcountry campsites on the trail are reserved site by site through Ontario Parks, and the reservation letter is the camping permit."
-checked = "2026-11-16"
+checked = "2026-11-20"
+season = "May to October"
+months = [5, 6, 7, 8, 9, 10]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. The Algonquin backcountry is frozen and snowy into April, buggy in late spring and cold by late October. Confidence: medium."
[[hike.source]]
url = "https://www.ontarioparks.ca/park/algonquin/backcountry/activities"
@@ -75,6 +79,11 @@ url = "https://www.ontarioparks.ca/backcountry/overnighthiking"
publisher = "Ontario Parks"
facts = ["summary", "shape"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -95,3 +104,12 @@ basis = "The pages named in the logo note were searched, and none shows an emble
basis_url = "https://www.ontarioparks.ca/park/algonquin/backcountry/activities"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: May to October."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
diff --git a/yosemite-high-route/trail.toml b/yosemite-high-route/trail.toml
index 03376f9..806ca6c 100644
--- a/yosemite-high-route/trail.toml
+++ b/yosemite-high-route/trail.toml
@@ -75,7 +75,11 @@ days = [7, 14]
terrain = ["alpine", "lakes", "forest"]
travel = "mostly-cross-country"
permit = "A Yosemite wilderness permit is required year-round for any overnight stay in the Yosemite Wilderness."
-checked = "2026-11-13"
+checked = "2026-11-20"
+season = "July to September"
+months = [7, 8, 9]
+season_basis = "estimate"
+season_method = "Judged from the climate at the trail's elevation and from similar trails. Mostly off-trail at 8,000 to 11,000 feet, so snowmelt, high stream crossings and early snow limit it to July through September. Confidence: high."
[[hike.source]]
url = "https://andrewskurka.com/adventures/yosemite-high-route/"
@@ -102,6 +106,11 @@ url = "https://edits.nationalmap.gov/apps/gaz-domestic/public/summary/253804"
publisher = "U.S. Geological Survey, Geographic Names Information System"
facts = ["end_lonlat"]
+[[hike.source]]
+url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+publisher = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
+facts = ["season", "months"]
+
# History of this record, oldest first. Add to it; never rewrite it.
# See docs/schema.md, section [[history]].
@@ -130,3 +139,12 @@ basis = "The page the guide links to is titled \"Yosemite High Route Guide - Sku
basis_url = "https://andrewskurka.com/product/yosemite-high-route-guide/"
asked_by = "the dataset's own check"
outcome = "applied"
+
+[[history]]
+date = "2026-11-20"
+change = "A season was estimated: July to September."
+fields = ["hike.season", "hike.months", "hike.season_basis", "hike.season_method"]
+basis = "No page states a season. It was set by judgement from the climate at the trail's elevation and from similar trails."
+basis_url = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
+asked_by = "the dataset's own check"
+outcome = "applied"
From 713fff78df0db91615dbe03dca2f2826d77c3feb Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:10:13 -0700
Subject: [PATCH 12/30] Record the inputs of every estimate for the monthly
check, and test that every trail has a season with its provenance
---
tools/season.py | 8 +
tools/season_inputs.json | 621 +++++++++++++++++++++++++++++
tools/tests/test_season_basis.py | 5 +
tools/tests/test_season_records.py | 87 ++++
4 files changed, 721 insertions(+)
create mode 100644 tools/season_inputs.json
create mode 100644 tools/tests/test_season_records.py
diff --git a/tools/season.py b/tools/season.py
index 979fdbf..e828ed1 100644
--- a/tools/season.py
+++ b/tools/season.py
@@ -90,6 +90,14 @@ def check_season(tid, hike, errors):
elif basis == "estimate":
errors.append(f"{tid}: hike.season_method is required with season_basis \"estimate\"")
+ if basis == "estimate" and has_months and isinstance(hike.get("months"), list):
+ try:
+ if hike.get("season") != phrase_for(hike["months"]):
+ errors.append(f"{tid}: the season phrase of an estimate must be built from its "
+ f"months: {phrase_for(hike['months'])!r}")
+ except (ValueError, TypeError):
+ errors.append(f"{tid}: hike.months must be month numbers 1 to 12")
+
naming_season = _naming(sources, "season")
if basis != "estimate" and any(_is_climate(x) for x in naming_season):
errors.append(
diff --git a/tools/season_inputs.json b/tools/season_inputs.json
new file mode 100644
index 0000000..82877e8
--- /dev/null
+++ b/tools/season_inputs.json
@@ -0,0 +1,621 @@
+{
+ "across-utah-route": {
+ "digest": "1582bd31f8f00ced",
+ "machine": [
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "alpine-trail-7": {
+ "digest": "efd5e277fbf3b6c1",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "avon": {
+ "digest": "a9120a59a9a1907d",
+ "machine": [
+ 4,
+ 5,
+ 6,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "batona": {
+ "digest": "3dbdb3e8b17d2b98",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10,
+ 11
+ ]
+ },
+ "bay-circuit": {
+ "digest": "bdb128943b1900ae",
+ "machine": [
+ 4,
+ 5,
+ 6,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "bayou-state-trail": {
+ "digest": "c7c4147060628fa7",
+ "machine": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 11,
+ 12
+ ]
+ },
+ "boundary-trail-mount-st-helens": {
+ "digest": "01312d045fd17c20",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "boundary-trail-pasayten": {
+ "digest": "e97c07b0f68a15a9",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "bristol-hills-trail": {
+ "digest": "a5fa7af7ebab8d67",
+ "machine": [
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "brooks-range-traverse": {
+ "digest": "8a3c5ef0f30bc7f8",
+ "machine": [
+ 8
+ ]
+ },
+ "bruce-trail": {
+ "digest": "ed62c99709c54267",
+ "machine": [
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "california-coastal": {
+ "digest": "5c7fa4913f78b36c",
+ "machine": [
+ 5,
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "conestoga-trail": {
+ "digest": "31f1d48bf322e3a7",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "conservation-trail": {
+ "digest": "21bfcf5403bcbfdf",
+ "machine": [
+ 5,
+ 6,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "cranberry-lake-50": {
+ "digest": "87772fc46ebb73ca",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "cross-vermont": {
+ "digest": "de8f9f0acea8bd21",
+ "machine": [
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "deseret-hiking-route": {
+ "digest": "191f5e4f5cc698cb",
+ "machine": [
+ 3,
+ 4,
+ 5,
+ 10,
+ 11
+ ]
+ },
+ "desert-trail": {
+ "digest": "132108d83a002b0d",
+ "machine": [
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "donut-hole": {
+ "digest": "dcc41463939e95a7",
+ "machine": [
+ 4,
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "eastern-continental-trail": {
+ "digest": "d40390952a719154",
+ "machine": [
+ 5,
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "eastern-sierra-high-route": {
+ "digest": "34c0558ddeedd3f2",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "ganaraska": {
+ "digest": "b414a50c65a31b82",
+ "machine": [
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "general-george-crook": {
+ "digest": "f2896d5fe13e417f",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "georgia-loop": {
+ "digest": "35f1d5133569d0c0",
+ "machine": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 10,
+ 11,
+ 12
+ ]
+ },
+ "gila-centennial-loop": {
+ "digest": "08f4ed745b5d2560",
+ "machine": [
+ 3,
+ 4,
+ 5,
+ 9,
+ 10,
+ 11
+ ]
+ },
+ "grand-valley-trail": {
+ "digest": "5f4505a160f8f245",
+ "machine": [
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "great-eastern": {
+ "digest": "b77ec5d870bbcc88",
+ "machine": [
+ 4,
+ 5,
+ 10
+ ]
+ },
+ "great-western-divide-loop": {
+ "digest": "dd7b6f503f72081b",
+ "machine": [
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "high-country-pathway": {
+ "digest": "b59fdbbf3b1ac6f8",
+ "machine": [
+ 5,
+ 6,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "highlands": {
+ "digest": "8212eeadd24218c3",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "hoosier-heritage-trail": {
+ "digest": "f550667eab910362",
+ "machine": [
+ 3,
+ 4,
+ 5,
+ 10,
+ 11
+ ]
+ },
+ "horse-shoe": {
+ "digest": "aeff26cf6c7e0143",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "hot-springs-trail": {
+ "digest": "fc73ad4cf711d615",
+ "machine": [
+ 2,
+ 3,
+ 4,
+ 5,
+ 10,
+ 11
+ ]
+ },
+ "iat-newfoundland-labrador": {
+ "digest": "91eadce2b4ef4c7f",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "international-appalachian-trail-maine": {
+ "digest": "8f488d4dc2b03636",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "koroc-palmer-loop": {
+ "digest": "e18e82c08b6dfd5d",
+ "machine": [
+ 8
+ ]
+ },
+ "la-cloche": {
+ "digest": "61ce29ac5892d1b8",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "lost-coast": {
+ "digest": "971c47b8714b706f",
+ "machine": [
+ 5,
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "loyalsock": {
+ "digest": "7e8067a31ec5da6c",
+ "machine": [
+ 4,
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "mason-dixon": {
+ "digest": "54cad0c500a1e861",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "midland-to-mackinac-trail": {
+ "digest": "c5ed1765cac4534f",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "midstate-ma": {
+ "digest": "edc133c6ae5007c7",
+ "machine": [
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "north-south": {
+ "digest": "86641545fa67fd0c",
+ "machine": [
+ 4,
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "north-south-lbl": {
+ "digest": "25b3d5d788753ae6",
+ "machine": [
+ 3,
+ 4,
+ 5,
+ 10,
+ 11
+ ]
+ },
+ "north-umpqua": {
+ "digest": "14231792880f7042",
+ "machine": [
+ 5,
+ 10
+ ]
+ },
+ "oak-ridges": {
+ "digest": "0646d355131c000c",
+ "machine": [
+ 5,
+ 6,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "ottawa-temiskaming-highland-trail": {
+ "digest": "77fbbe8137415f41",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "paumanok-path": {
+ "digest": "588eea3017f04c4c",
+ "machine": [
+ 7,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "pfiffner-traverse": {
+ "digest": "61965112f0b75445",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "rideau-trail": {
+ "digest": "55d2219b607959d1",
+ "machine": [
+ 5,
+ 6,
+ 8,
+ 9,
+ 10
+ ]
+ },
+ "ring-the-peak": {
+ "digest": "858d219cc4ecd8f6",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "sawtooth-wilderness-high-route": {
+ "digest": "0f4f2e2bf5e9bc6e",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "sea-to-sea-route": {
+ "digest": "eb6dbcb347f7a83d",
+ "machine": [
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "shawangunk-ridge-trail": {
+ "digest": "d3b38e00538fd900",
+ "machine": [
+ 4,
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "shenipsit-trail": {
+ "digest": "a713c4e4a679b6fa",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "siskiyou-peaks-trail": {
+ "digest": "2b4dff26c8e71b80",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "sky-islands-traverse": {
+ "digest": "eed4f15ecdf6114d",
+ "machine": [
+ 3,
+ 4,
+ 5,
+ 9,
+ 10,
+ 11
+ ]
+ },
+ "solitude-loop": {
+ "digest": "c091a7bb7336deb5",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "standing-stone": {
+ "digest": "cdc4f7ed39a2c205",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "stein-valley-traverse": {
+ "digest": "59cd7e9a35c5c732",
+ "machine": [
+ 6,
+ 9
+ ]
+ },
+ "sunapee-ragged-kearsarge": {
+ "digest": "f5d7131d547be861",
+ "machine": [
+ 8,
+ 9
+ ]
+ },
+ "tahoe-yosemite-trail": {
+ "digest": "23aa94cfbefd3f86",
+ "machine": [
+ 8,
+ 9
+ ]
+ },
+ "tuscarora": {
+ "digest": "606d9fe137a8347d",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "vagabond-loop": {
+ "digest": "33378ec42f73f8d5",
+ "machine": [
+ 4,
+ 10
+ ]
+ },
+ "warrior-trail": {
+ "digest": "cecd19f5c7ba6ae4",
+ "machine": [
+ 4,
+ 5,
+ 9,
+ 10
+ ]
+ },
+ "wasatch-traverse": {
+ "digest": "1582bd31f8f00ced",
+ "machine": [
+ 5,
+ 6,
+ 9,
+ 10
+ ]
+ },
+ "waskahegan": {
+ "digest": "d7993fbe810051fd",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "western-uplands": {
+ "digest": "464d6cd6bfe3257c",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ },
+ "yosemite-high-route": {
+ "digest": "eee24b0c39473ab0",
+ "machine": [
+ 7,
+ 8,
+ 9
+ ]
+ }
+}
diff --git a/tools/tests/test_season_basis.py b/tools/tests/test_season_basis.py
index 7b9da90..61c0805 100644
--- a/tools/tests/test_season_basis.py
+++ b/tools/tests/test_season_basis.py
@@ -117,6 +117,11 @@ class SeasonBasisTest(unittest.TestCase):
def test_an_estimate_with_a_method_and_a_climate_source_passes(self):
self.assertEqual(estimate(), [])
+ def test_an_estimate_phrase_is_built_from_its_months(self):
+ errors = estimate(season="Summer")
+ self.assertTrue(any("built from" in e for e in errors), errors)
+ self.assertEqual(check(season="Summer"), []) # a page's own words stand
+
def test_an_estimate_needs_a_method(self):
errors = estimate(season_method=None)
self.assertTrue(any("season_method" in e for e in errors), errors)
diff --git a/tools/tests/test_season_records.py b/tools/tests/test_season_records.py
new file mode 100644
index 0000000..70d70bc
--- /dev/null
+++ b/tools/tests/test_season_records.py
@@ -0,0 +1,87 @@
+"""Tests over the real records: every trail has a season, with its provenance.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import os
+import sys
+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 # noqa: E402
+import validate as V # noqa: E402
+
+RECORDS = {tid: refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
+ for tid in refresh.trail_ids(V.ROOT)}
+
+
+def hikes():
+ for tid, rec in RECORDS.items():
+ yield tid, rec.get("hike") or {}
+
+
+class EveryTrailHasASeasonTest(unittest.TestCase):
+ def test_every_record_has_season_months_and_a_basis(self):
+ for tid, hike in hikes():
+ self.assertTrue(hike.get("season"), tid)
+ self.assertTrue(hike.get("months"), tid)
+ self.assertIn(hike.get("season_basis"), season.BASES, tid)
+
+ def test_the_basis_fits_the_sources(self):
+ for tid, hike in hikes():
+ errors = []
+ season.check_season(tid, hike, errors)
+ self.assertEqual(errors, [], tid)
+
+ def test_every_estimate_has_a_method_with_its_confidence_and_a_climate_source(self):
+ found = 0
+ for tid, hike in hikes():
+ if hike.get("season_basis") != "estimate":
+ continue
+ found += 1
+ self.assertIn(season.confidence_of(hike.get("season_method")), season.CONFIDENCES, tid)
+ naming = [s for s in hike["source"] if "season" in s["facts"]]
+ self.assertEqual(len(naming), 1, tid)
+ self.assertEqual(naming[0]["facts"], ["season", "months"], tid)
+ self.assertIn("chelsa-climate.org", naming[0]["url"], tid)
+ self.assertGreater(found, 0)
+
+ def test_no_season_from_a_page_cites_climate_data(self):
+ for tid, hike in hikes():
+ if hike.get("season_basis") == "estimate":
+ continue
+ for source in hike.get("source") or []:
+ if "season" in source["facts"]:
+ self.assertNotIn("chelsa", source["url"], tid)
+
+ def test_no_record_says_a_season_is_missing(self):
+ for tid, hike in hikes():
+ for field in ("summary", "caution"):
+ text = str(hike.get(field) or "").lower()
+ self.assertNotIn("no season", text, tid)
+ self.assertNotIn("season on file", text, tid)
+
+ def test_the_estimated_phrase_is_built_from_its_months(self):
+ for tid, hike in hikes():
+ if hike.get("season_basis") == "estimate":
+ self.assertEqual(hike["season"], season.phrase_for(hike["months"]), tid)
+
+ def test_a_season_with_a_method_has_its_confidence_in_the_method(self):
+ judged = [t for t, h in hikes() if h.get("season_method")]
+ self.assertEqual(len(judged), 75)
+ for tid in judged:
+ self.assertTrue(season.confidence_of(RECORDS[tid]["hike"]["season_method"]), tid)
+
+ def test_a_judged_season_changed_its_record_history(self):
+ for tid, hike in hikes():
+ if hike.get("season_method"):
+ changed = [e for e in RECORDS[tid]["history"]
+ if "hike.season_method" in (e.get("fields") or [])]
+ self.assertEqual(len(changed), 1, tid)
+
+
+if __name__ == "__main__":
+ unittest.main()
From e95131833bfc646ee11a93ae28a6f220ba0f5c2b Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:26:51 -0700
Subject: [PATCH 13/30] Show an estimated season as an estimate on the trail
page, in lists and tables, and in the month filter; say how seasons are
sourced and tested on the reference page
---
glossary.toml | 2 +-
web/assets/app.js | 47 ++++++++--------
web/assets/style.css | 5 ++
web/olt/browse.py | 15 +++--
web/olt/datafiles.py | 13 +++++
web/olt/facets.py | 89 ++++++++++++++++++++++++++++--
web/olt/home.py | 27 +++++----
web/olt/placefacets.py | 2 +-
web/olt/reference.py | 34 +++++++++++-
web/olt/regions.py | 2 +-
web/olt/seo.py | 3 +-
web/olt/standing.py | 4 +-
web/olt/summary.py | 4 +-
web/olt/trail.py | 22 ++++++--
web/tests/test_facets.py | 92 +++++++++++++++++++++++++++++--
web/tests/test_filter_bar.py | 92 ++++++++++++++++++++-----------
web/tests/test_hike.py | 27 ++++++++-
web/tests/test_structured_data.py | 15 ++++-
web/tests/test_trust.py | 29 ++++++++--
web/tests/test_views.py | 60 +++++++++++++++++++-
20 files changed, 481 insertions(+), 103 deletions(-)
diff --git a/glossary.toml b/glossary.toml
index e48cb61..a89aef0 100644
--- a/glossary.toml
+++ b/glossary.toml
@@ -116,7 +116,7 @@ see = ["/lists/weekend/", "/lists/one-to-two-weeks/", "/lists/a-month-or-more/",
[[term]]
id = "season"
term = "Season"
-definition = "The months in which the whole trail is usually walked, as a source states them. It is not the dates a park or a hut is open. Only some records state one."
+definition = "The months in which the whole trail is usually walked. Where a page states them, that is shown. Otherwise they are estimated from the climate at the trail's elevation and from similar trails, and the page says so: an estimated season reads “About” with a note. It is not the dates a park or a hut is open."
see = ["/lists/"]
[[term]]
diff --git a/web/assets/app.js b/web/assets/app.js
index dce1f5e..f4d2be8 100644
--- a/web/assets/app.js
+++ b/web/assets/app.js
@@ -1940,9 +1940,10 @@
var OLD_POLICY = { open: 'free', sold: 'sold', withheld: 'unpublished', unclear: 'elsewhere' };
/* facet-counts:begin — pure, with no page: web/tests/test_filter_counts.py runs this under node.
- A row: {search: [name, author, places, summary], where: [], km, time, months: [], terrain: [], kind, walking, shape, gpx}.
- A state: {words: [], where, min, max (km; max may be Infinity), month, kind, and a list for
- each of time, terrain, walking, shape, gpx}. */
+ A row: {search: [name, author, places, summary], where: [], km, time, months: [], estimate, terrain: [], kind, walking, shape, gpx}.
+ A state: {words: [], where, min, max (km; max may be Infinity), month, stated, kind, and a list for
+ each of time, terrain, walking, shape, gpx}. stated: with a month chosen, leave out the rows whose
+ season is an estimate. */
var FacetCount = (function () {
var FACETS = ['where', 'length', 'time', 'month', 'terrain', 'kind', 'walking', 'shape', 'gpx'];
function has(list, v) { return list.indexOf(v) !== -1; }
@@ -1991,6 +1992,9 @@
if (skip !== 'length' && (d.km < s.min || d.km > s.max)) return false;
if (skip !== 'time' && s.time.length && !has(s.time, d.time)) return false;
if (skip !== 'month' && s.month && !has(d.months, s.month)) return false;
+ /* Leaving estimates out belongs to the month: it holds in counting each month too, so the
+ number beside a month is what choosing it, with estimates left out, shows. */
+ if (s.month && s.stated && d.estimate) return false;
if (skip !== 'terrain' && s.terrain.length && !d.terrain.some(function (t) { return has(s.terrain, t); })) return false;
if (skip !== 'kind' && s.kind && d.kind !== s.kind) return false;
if (skip !== 'walking' && s.walking.length && !has(s.walking, d.walking)) return false;
@@ -2052,15 +2056,14 @@
var rows = Array.prototype.map.call(resultsRoot.querySelectorAll('.entry[data-id]'), function (li) {
var d = li.dataset;
return { li: li, id: d.id, search: FacetCount.textsOf(d.search), where: split(d.where), km: Number(d.km), time: d.time || '',
- months: split(d.months), terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
+ months: split(d.months), estimate: d.estimate === 'yes', terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
shape: d.shape || '', gpx: d.gpx || '' };
});
var lists = Array.prototype.slice.call(resultsRoot.querySelectorAll('ol.entries'));
var count = resultsRoot.querySelector('.results-count');
var noun = (count && count.dataset.noun) || 'trails';
var empty = resultsRoot.querySelector('.empty-state');
- var unseasoned = resultsRoot.querySelector('[data-unseasoned]');
- var unseasonedText = resultsRoot.querySelector('[data-unseasoned-text]');
+ var seasonAlways = resultsRoot.hasAttribute('data-season-shown');
var active = form.querySelector('.filters__active');
var lenHint = document.getElementById('len-hint');
var listHead = resultsRoot.querySelector('.list-head');
@@ -2160,6 +2163,7 @@
maxRaw: maxRaw,
swapped: swapped,
month: value(el.month),
+ stated: !!(el.stated && el.stated.checked && value(el.month)),
kind: radio('kind')
};
MULTI.forEach(function (name) { s[name] = checked(name); });
@@ -2287,6 +2291,7 @@
if (s.min) p.set('min', s.minRaw);
if (s.max !== Infinity) p.set('max', s.maxRaw);
if (s.month) p.set('month', s.month);
+ if (s.month && s.stated) p.set('stated', '1');
if (s.kind) p.set('kind', s.kind);
MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); });
if (sort && sort.value !== defaultSort && sort.value !== 'nearest') p.set('sort', sort.value);
@@ -2332,6 +2337,7 @@
if (el.month) {
var month = p.get('month') || '';
el.month.value = hasOption(el.month, month) ? month : '';
+ if (el.stated) el.stated.checked = !!el.month.value && p.get('stated') === '1';
}
var kind = p.get('kind') || '';
if (kind === 'designated') kind = 'trail';
@@ -2460,16 +2466,19 @@
count.appendChild(document.createTextNode(' ' + words));
}
if (empty) empty.hidden = shown.length > 0;
- /* With a month chosen, say how many trails that pass everything else are left out for having no
- season on file, counted over the same rows as the list. */
- if (unseasoned && el.month) {
- var noSeason = 0;
- if (s.month) rows.forEach(function (d) { if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++; });
- unseasoned.hidden = noSeason === 0;
- if (noSeason) {
- unseasonedText.textContent = noSeason + (noSeason === 1 ? ' trail with no season on file is not shown.'
- : ' trails with no season on file are not shown.');
+ /* A month's rows show their season, and the way to leave estimated seasons out is offered once a
+ month is chosen and some of the trails that pass everything else have an estimated season. */
+ if (!seasonAlways) resultsRoot.toggleAttribute('data-season-shown', !!s.month);
+ if (el.stated) {
+ var open = false;
+ if (s.month) {
+ var withEstimates = Object.assign({}, s, { stated: false });
+ open = rows.some(function (d) { return d.estimate && FacetCount.passes(d, withEstimates, ''); });
}
+ el.stated.disabled = !s.month;
+ if (!s.month) el.stated.checked = false;
+ var box = el.stated.closest('label');
+ if (box) box.hidden = !open && !el.stated.checked;
}
if (listHead) listHead.hidden = shown.length === 0;
relabel(s, c);
@@ -2499,14 +2508,6 @@
form.addEventListener('change', function () { apply(true); });
form.addEventListener('submit', function (e) { e.preventDefault(); });
form.addEventListener('reset', function () { setTimeout(function () { apply(true); }, 0); });
- resultsRoot.querySelectorAll('[data-unseasoned-show]').forEach(function (b) {
- /* Showing them is clearing the month; the rest of the filters stay. */
- b.addEventListener('click', function () {
- if (!el.month) return;
- el.month.value = '';
- el.month.dispatchEvent(new Event('change', { bubbles: true }));
- });
- });
resultsRoot.querySelectorAll('[data-reset]').forEach(function (b) {
b.addEventListener('click', function () { form.reset(); el.q.focus(); });
});
diff --git a/web/assets/style.css b/web/assets/style.css
index 342659e..9f1ce6e 100644
--- a/web/assets/style.css
+++ b/web/assets/style.css
@@ -1247,6 +1247,11 @@ html.js .filters__panels:not([data-open]) { display: none; }
.results-note { margin-block: calc(-1 * var(--space-1)) var(--space-3); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
.results-note[hidden] { display: none; }
.results-note__show { padding: 0; border: 0; background: none; color: var(--link); font: inherit; text-decoration: underline; cursor: pointer; }
+/* A row's season: shown on a month's list, and while a month is chosen (app.js). */
+.entry__season { display: none; }
+[data-season-shown] .entry__season { display: block; }
+.field__check { display: block; margin-block-start: var(--space-1); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
+.field__check[hidden] { display: none; }
.key {
display: flex;
flex-wrap: wrap;
diff --git a/web/olt/browse.py b/web/olt/browse.py
index c8e08e3..fb66b42 100644
--- a/web/olt/browse.py
+++ b/web/olt/browse.py
@@ -78,7 +78,7 @@ GROUPS = (
("walking", "By kind of walking", "Loops, high routes, walking with no trail, and trails not yet finished."),
("terrain", "By terrain", "The main kinds of country a trail crosses."),
("holder", "By who looks after it", "Trails whose designation names the holder."),
- ("month", "By month", "Trails whose season on file includes the month. Only some trails have a season."),
+ ("month", "By month", "Trails normally hiked in the month. Estimated seasons are marked."),
("where", "By country and GPX", "Where a trail is, and whether its page has a track to download."),
)
@@ -115,7 +115,7 @@ def time_note(recs, records):
def _month_list(m):
name = facets.MONTHS[m - 1]
return List(f"hike-in-{name.lower()}", f"Hiking in {name}",
- f"Trails whose season on file includes {name}.",
+ f"Trails normally hiked in {name}. Estimated seasons are marked.",
lambda r, m=m: m in facets.months(r),
page_title=f"Long Trails to Hike in {name}: {{n}} Trails", group="month", note=month_note(name),
min_size=MONTH_MIN)
@@ -123,9 +123,14 @@ def _month_list(m):
def month_note(name):
def note(recs, records):
- have = sum(1 for r in records if facets.months(r))
- return (f"Only {have} of the {len(records)} trails have a season on file, so this page covers those "
- f"{have}. It is not every trail that can be walked in {name}.")
+ est = sum(1 for r in recs if facets.season_estimated(r))
+ stated = len(recs) - est
+ if not est:
+ return f"A source states the season for all {stated}."
+ if not stated:
+ return "No source states the season for these, so each is estimated from climate."
+ return (f"A source states the season for {stated} of these. For the other {est} it is "
+ f"estimated from climate, and marked.")
return note
diff --git a/web/olt/datafiles.py b/web/olt/datafiles.py
index aeb9180..c648570 100644
--- a/web/olt/datafiles.py
+++ b/web/olt/datafiles.py
@@ -4,11 +4,13 @@
collections.toml [[collection]] named sets of trails set side by side (olt/standing.py)
[[list]] which lists the home page shows, and in what order (olt/home.py)
authors.toml [[author]] route authors, and the words about the people among them (olt/authors.py)
+ tools/season_blind_test.json how the judged seasons did against the seasons pages state (olt/reference.py)
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
is looked for in the repository being built and then in this one, so a test repository without
one still builds.
"""
+import json
import os
import tomllib
@@ -40,3 +42,14 @@ def authors(repo_root):
def lists(repo_root):
"""The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row."""
return load(repo_root, "collections.toml", "list")
+
+
+def blind_test(repo_root):
+ """The blind test of the judged seasons (tools/season_blind_test.json, written by
+ tools/season_judge.py score), or None when there is none."""
+ for base in (repo_root, REAL_ROOT):
+ path = os.path.join(base or REAL_ROOT, "tools", "season_blind_test.json")
+ if os.path.isfile(path):
+ with open(path, encoding="utf-8") as f:
+ return json.load(f)
+ return None
diff --git a/web/olt/facets.py b/web/olt/facets.py
index 5410974..44723c0 100644
--- a/web/olt/facets.py
+++ b/web/olt/facets.py
@@ -172,8 +172,15 @@ def months(rec):
return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12})
-def season_text(rec):
- """The phrase on the trail page: [hike].season, else built from the months."""
+def season_estimated(rec):
+ """True when no page states the season: it was estimated (season_basis "estimate"), or set by
+ judgement from pages that differ (it carries a season_method). Such a season reads "About"."""
+ h = hike.table(rec)
+ return bool(h.get("season")) and (h.get("season_basis") == "estimate" or bool((h.get("season_method") or "").strip()))
+
+
+def season_phrase(rec):
+ """The phrase on the trail page as the record gives it: [hike].season, else built from the months."""
phrase = (hike.table(rec).get("season") or "").strip()
if phrase:
return phrase[:1].upper() + phrase[1:]
@@ -185,6 +192,74 @@ def season_text(rec):
return words.join_names(MONTHS[m - 1] for m in ms)
+def season_text(rec):
+ """The season as a page shows it: the phrase, or "About ..." where it is estimated, so an
+ estimate never reads as a stated fact ("About June to September", "About all year")."""
+ phrase = season_phrase(rec)
+ if not phrase or not season_estimated(rec):
+ return phrase
+ if phrase.lower().startswith("about"):
+ return phrase
+ if phrase.lower() == "all year":
+ phrase = phrase.lower()
+ return "About " + phrase
+
+
+def season_kind(rec):
+ """How the season is known: "stated" (a page states it), "judged" (set by judgement from pages
+ that differ), "estimated" (no page states one), or "" when the trail has no season."""
+ if not hike.table(rec).get("season"):
+ return ""
+ if not season_estimated(rec):
+ return "stated"
+ return "judged" if season_basis(rec) == "sources" else "estimated"
+
+
+SEASON_CONFIDENCE = re.compile(r"\s*Confidence: (high|medium|low)\.\s*$")
+JUDGED_LEAD = "Judged from the climate at the trail's elevation and from similar trails."
+
+
+def season_confidence(rec):
+ """"high", "medium" or "low" from the end of the season's method; "" when it names none."""
+ found = SEASON_CONFIDENCE.search(hike.table(rec).get("season_method") or "")
+ return found.group(1) if found else ""
+
+
+def season_reason(rec):
+ """What the season's method says sets the season, without its standard first sentence and its
+ closing confidence."""
+ text = SEASON_CONFIDENCE.sub("", (hike.table(rec).get("season_method") or "").strip()).strip()
+ if text.startswith(JUDGED_LEAD):
+ text = text[len(JUDGED_LEAD):].strip()
+ return text
+
+
+def season_pages_differ(rec):
+ """True for a season set by judgement from pages that state different seasons."""
+ return season_estimated(rec) and season_basis(rec) == "sources"
+
+
+def season_note(rec):
+ """Says an estimated season is not a page's statement, how it was worked out, what sets it
+ there and how far to trust it; "" when a page states the season."""
+ if not season_estimated(rec):
+ return ""
+ reason = season_reason(rec)
+ if season_pages_differ(rec):
+ lead = "No one page states this season."
+ else:
+ lead = ("No page states a season. This is estimated from the climate at the trail's "
+ "elevation and from similar trails.")
+ parts = [lead]
+ if reason:
+ parts.append(reason)
+ conf = season_confidence(rec)
+ if conf:
+ parts.append(f"Confidence: {conf}.")
+ parts.append("People do walk it outside these months.")
+ return " ".join(parts)
+
+
SEASON_BASIS_TEXT = {
"primary": "The season comes from the page of the body that manages the trail or the trail's own association or, for a route, its author.",
"sources": "Two or more pages from different publishers agree on the season.",
@@ -203,10 +278,12 @@ def season_basis(rec):
def season_basis_line(rec):
"""One sentence for "About this data"; "" when the season has no recorded basis."""
basis = season_basis(rec)
- if basis == "estimate":
- method = (hike.table(rec).get("season_method") or "").strip()
- return (method + " No page states a season.").strip()
- return SEASON_BASIS_TEXT.get(basis, "")
+ if not season_estimated(rec):
+ return SEASON_BASIS_TEXT.get(basis, "")
+ method = (hike.table(rec).get("season_method") or "").strip()
+ if season_pages_differ(rec):
+ return (method + " It is a judgement, not any one page's statement.").strip()
+ return (method + " No page states a season.").strip()
# Terrain, Walking, Shape ----------------------------------------------------
diff --git a/web/olt/home.py b/web/olt/home.py
index 508acae..d920161 100644
--- a/web/olt/home.py
+++ b/web/olt/home.py
@@ -193,6 +193,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
if search:
data["search"] = searchtext.attribute(rec)
attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items())
+ estimated = facets.season_estimated(rec)
+ if estimated:
+ attrs += ' data-estimate="yes"'
if common.line_differs(rec):
attrs += ' data-partial="yes"'
h = f"h{level}"
@@ -203,6 +206,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
desc = entry_desc(rec)
desc_html = f'\n
{esc(desc)}
' if desc else ""
time_html = esc(facets.time_text(rec)) + (' estimate' if est else "")
+ season_html = (f'\n
{facets.SEASON}
{esc(facets.season_text(rec))}'
+ + ('estimate' if estimated else "") + "
"
+ if facets.months(rec) else "")
climb_html = (f'\n
Climb
{words.elevation(climb_m, "stack")}'
f'computed
') if climb_m is not None else ""
if hidden:
@@ -227,7 +233,7 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
{extra}
"""
@@ -352,10 +358,14 @@ def finder_form(records, c=None, steps=None, where="all"):
""")
if facets.offered(records, "season") and _narrows(c, "month", range(1, 13)):
month_opts = "".join(_opt(str(i), m, c[f"month:{i}"]) for i, m in enumerate(facets.MONTHS, 1) if c[f"month:{i}"])
+ # A way to leave estimated seasons out, offered only where some of these trails have one.
+ stated_box = ('\n '
+ if any(facets.season_estimated(r) for r in records) else "")
first.append(f"""
-
Trails usually walked in that month.
+
Trails usually walked in that month. Estimated seasons are marked.
{stated_box}
{_missing(records, "season")}
""")
if _narrows(c, "kind", facets.KINDS):
@@ -535,7 +545,7 @@ def key(official=True):
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False, top=3,
- ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None):
+ ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None, season=False):
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
Every list carries the same "Sort by" control. The rows are written in
@@ -544,6 +554,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
finder: a list driven by the filter bar over it (listing(): live count, empty state).
every: the list holds every trail (the home page's).
+ season: show each row's season (a month's list), as app.js does when a month is chosen.
groups: [(heading, trails, extra_fn)] to list the trails under headings (level `top`);
sorting is within each group and the groups keep their order. A heading may be a pair
(heading HTML, intro HTML): the intro is a sentence under the heading (an author's summary).
@@ -624,18 +635,14 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
tools = sort_select(default_sort, saved=saved, ranked=ranked, wholly=wholly)
dflt = SAVED_ORDER[0] if saved else "rank" if ranked else HERE_ORDER if wholly else default_sort
finder_attr = " data-finder" if finder else ""
- # Under the count, while a month is chosen: how many trails are left out for having no season on
- # file, and a way to see them (app.js fills it in from the rows, the same ones the list is).
- unseasoned = ('\n
'
- '
'
- if finder else "")
- return Markup(f"""
+ season_attr = " data-season-shown" if season else ""
+ return Markup(f"""
- {home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where=""), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
+ {home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where="", season=lst.group == "month"), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
about=summary.facts(recs, records, place=(name, [info["key"]])), about_title=f"About these trails in {name}")}
{nav}
diff --git a/web/olt/reference.py b/web/olt/reference.py
index 53af67f..428b7b3 100644
--- a/web/olt/reference.py
+++ b/web/olt/reference.py
@@ -96,6 +96,32 @@ def verified(records):
return out
+def _pct(share):
+ return f"{share * 100:.0f} percent"
+
+
+def season_section(records, blind):
+ """The paragraphs and table saying where seasons come from, how many trails have each kind, and how
+ the estimates did in the blind test (read from tools/season_blind_test.json, never typed)."""
+ n = len(records)
+ kinds = collections.Counter(facets.season_kind(r) for r in records)
+ basis = collections.Counter(facets.season_basis(r) for r in records if facets.season_kind(r) == "stated")
+ rows = [["The body that manages the trail, its association, or for a route its author", str(basis["primary"])],
+ ["Two or more pages from different publishers that agree", str(basis["sources"])],
+ ["One page", str(basis["source"])],
+ ["Pages that differ, so set by judgement from all of them", str(kinds["judged"])],
+ ["No page states one, so estimated from climate", str(kinds["estimated"])],
+ ["All trails", str(n)]]
+ out = [f"""
Every trail has a season. Where a page states one, the season is that page’s. Where the pages that state one differ and none is the trail’s holder, its association or its route’s author, the season is set by judgement from all of them and the climate, and the page says so. Where no page states one, the season is estimated from the climate at the trail’s elevation and from similar trails: it reads “About” with a note, is marked in lists and is left out of the data search engines read. People do walk many trails outside their estimated months, and an estimate is replaced when a page that states a season is found.
+ {pagekit.table(["Where a trail's season comes from", "Trails"], rows, caption="Where the seasons come from", numeric=(1,))}"""]
+ if blind:
+ by = blind["by_confidence"]
+ conf = ", ".join(f"{name} {by[name]['matched']} of {by[name]['tested']} ({_pct(by[name]['share'])})"
+ for name in ("high", "medium", "low") if by[name]["tested"])
+ out.append(f"""
How the estimates were tested. On {esc(blind["date"])} the method was run blind on {blind["tested"]} trails whose seasons a page does state, with those seasons hidden. It matched {blind["matched"]} of them ({_pct(blind["share"])}) within one month at each end of the season the page states. By the confidence it gave each estimate: {esc(conf)}. This measures how the method did where the answer is known, not a promise for any one trail.
""")
+ return "\n ".join(out)
+
+
def method_page(records, site, repo_root):
"""(title, description, body) for /method/."""
meaning = schema_meanings(repo_root)
@@ -120,12 +146,15 @@ def method_page(records, site, repo_root):
(a, b), (c, d_) = facets.PACE_KM, facets.PACE_KM_CROSS
coverage = []
for label, fn in (("A usual time stated by a source", lambda r: not facets.time_days(r)[2]),
- ("A season", lambda r: bool(facets.months(r))), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
+ ("A season a page states", lambda r: facets.season_kind(r) == "stated"),
+ ("A season set from pages that differ", lambda r: facets.season_kind(r) == "judged"),
+ ("A season estimated from climate", lambda r: facets.season_kind(r) == "estimated"), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
("Terrain", lambda r: bool(facets.terrain(r))), ("What the walking is", lambda r: bool(facets.walking(r))),
("A computed climb that covers the whole trail", lambda r: facets.row_climb_m(r) is not None),
("A track included here", common.has_line)):
have = sum(1 for r in records if fn(r))
coverage.append([label, str(have), str(n - have)])
+ season_html = season_section(records, datafiles.blind_test(repo_root))
rows = [[label, str(k), f"{k / len(ver) * 100:.0f}%" if ver else ""] for label, k in bands]
body = (pagekit.head("How the figures are measured", (
f"What each figure on this site means, and how far to trust it. {len(ver)} of the {n} trails have a track whose "
@@ -145,7 +174,8 @@ def method_page(records, site, repo_root):
Climb is the total ascent along the track.{(" It uses " + esc(model) + ", sampled every " + words.fmt_int(spacing) + " metres, with " + esc(smoothing[:1].lower() + smoothing[1:]) + ".") if model and spacing else ""} {esc(limits_text)}
A climb is ranked or shown in a list only where its track covers the whole trail: a track that covers part of the trail, or more than the trail, would mislead.
Season and high point
-
{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} Not every record has them, so a page built from them says how many records it covers.
+
{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))}
+ {season_html}
What the records have
{pagekit.table(["Figure", "Records with it", "Records without"], coverage, caption="How many records carry each figure", numeric=(1, 2))}
- {home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead),
+ {home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead, season=lst.group == "month"),
home.overview_map(recs, f"Map of the trails in the list {lst.title}"),
about=f"{about}{before}{f'
{esc(note.strip())}
' if note else ''}
{rule}
",
about_title="About this list")}
diff --git a/web/olt/seo.py b/web/olt/seo.py
index f61744b..d6abd26 100644
--- a/web/olt/seo.py
+++ b/web/olt/seo.py
@@ -284,7 +284,8 @@ def _properties(rec):
props.append(_pv("Shape", facets.SHAPES[shape]))
props.append(_pv("Start", h.get("start", "")) if h.get("start") else None)
props.append(_pv("End", h.get("end", "")) if h.get("end") else None)
- props.append(_pv("Usual season", h["season"]) if h.get("season") else None)
+ # Only a season a page states: an estimate is not a fact about the trail to hand to a search engine.
+ props.append(_pv("Usual season", h["season"]) if h.get("season") and not facets.season_estimated(rec) else None)
if common.is_route(rec):
route = rec.get("route", {})
props.append(_pv("Route author", route["creator"]) if route.get("creator") else None)
diff --git a/web/olt/standing.py b/web/olt/standing.py
index 19b5f11..de0f2e5 100644
--- a/web/olt/standing.py
+++ b/web/olt/standing.py
@@ -45,14 +45,16 @@ def time_cell(rec):
def season_cell(rec):
- return facets.season_text(rec) or "Not on file"
+ return facets.season_text(rec)
def figures_note(recs):
"""What the times and climbs of these trails mean, with the caveats the records state."""
est = sum(1 for r in recs if facets.time_days(r)[2])
+ unstated = sum(1 for r in recs if facets.season_estimated(r))
parts = [f"Times that start with “About” are estimated from the length ({est} of these). "
"Otherwise a source states the time.",
+ f"Seasons that start with “About” are estimated from climate ({unstated} of these)." if unstated else "",
climb_caveat(recs)]
return " ".join(p for p in parts if p)
diff --git a/web/olt/summary.py b/web/olt/summary.py
index 242f2da..9a41fe4 100644
--- a/web/olt/summary.py
+++ b/web/olt/summary.py
@@ -148,7 +148,9 @@ def detail(rec):
out.append(f"Its high point is {esc(name + ', ') if name else ''}{words.elevation(m)}.")
season = facets.season_text(rec)
if season:
- out.append(f"Season: {esc(season)}.")
+ how = (", judged from pages that differ" if facets.season_pages_differ(rec)
+ else ", estimated from climate" if facets.season_estimated(rec) else "")
+ out.append(f"Season: {esc(season)}{how}.")
rest = _rest_of_summary(rec)
if rest:
out.append(f'{esc(rest)}')
diff --git a/web/olt/trail.py b/web/olt/trail.py
index 21e3391..5a5f11f 100644
--- a/web/olt/trail.py
+++ b/web/olt/trail.py
@@ -282,6 +282,7 @@ def _name_html(rec):
MAX_BRIEF = 4 # sentences in the "In brief" paragraph
+PINNED = -1 # the priority of a sentence that is kept besides those (an estimated season)
MONTH_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
SEASON_WORDS = ("spring", "summer", "fall", "autumn", "winter", "late", "early", "mid", "from", "about")
SENTENCE_VERBS = re.compile(r"\b(is|are|can|start|starts|hikes?|hiked|travelled|traveled|bring|brings|closed|best)\b", re.I)
@@ -292,6 +293,13 @@ def season_sentence(rec):
seasons, ("sentence", "Northbound hikes start late February to early April") for one the record
already words as a sentence, or None when the record has none or it is too long to say briefly.
The caller adds the full stop. Only the record's own words are used."""
+ if facets.season_estimated(rec):
+ # Never worded as a fact, and never joined to the GPX clause with "and".
+ phrase = facets.season_phrase(rec).rstrip(". ")
+ phrase = phrase.lower() if phrase.lower() == "all year" else phrase
+ if facets.season_pages_differ(rec):
+ return ("estimate", f"The pages differ on the season; it is judged to be about {phrase}")
+ return ("estimate", f"No source gives a season; the climate suggests about {phrase}")
text = facets.season_text(rec).strip().rstrip(". ")
if not text:
return None
@@ -431,19 +439,23 @@ def brief_sentences(rec):
# When to walk it and whether this site has a GPX: one sentence where the season is a plain range.
clause = gpx_clause(rec) or ("this site has no GPX for it" + _see_clause(rec))
season = season_sentence(rec)
- if season and not re.search(r"[,;]", season[1]):
+ if season and season[0] != "estimate" and not re.search(r"[,;]", season[1]):
# "The usual season is May to July, and this page has a GPX of the track to download."
items.append((3, 5, f"{esc(season[1])}, and {esc(clause)}."))
else:
if season:
- items.append((3.5, 5, esc(season[1]) + "."))
+ # An estimated season is always said, so it is never left for a reader to take as a fact
+ # by omission: it is the one sentence that may stand beyond MAX_BRIEF.
+ items.append((PINNED if season[0] == "estimate" else 3.5, 5, esc(season[1]) + "."))
items.append((3, 6, esc(clause[:1].upper() + clause[1:]) + "."))
permit = permit_sentence(rec)
if permit:
items.append((6, 7, esc(permit)))
# At most MAX_BRIEF sentences: the lowest priorities are kept, shown in reading order.
- kept = sorted(sorted(items, key=lambda i: (i[0], i[1]))[:MAX_BRIEF], key=lambda i: i[1])
+ pinned = [i for i in items if i[0] == PINNED]
+ rest = sorted((i for i in items if i[0] != PINNED), key=lambda i: (i[0], i[1]))[:MAX_BRIEF]
+ kept = sorted(rest + pinned, key=lambda i: i[1])
return [text for _, _, text in kept]
@@ -624,7 +636,7 @@ def glance(rec, records=None):
rows.append(glance_row(facets.TIME, facets.time_text(rec), time_note(rec, records)))
season = facets.season_text(rec)
if season:
- rows.append(glance_row(facets.SEASON, season))
+ rows.append(glance_row(facets.SEASON, season, facets.season_note(rec)))
if facets.walking(rec):
walking = facets.WALKING_VALUES[facets.walking(rec)]
if facets.walking(rec) in facets.CROSS_COUNTRY:
@@ -692,7 +704,7 @@ def glance(rec, records=None):
unfinished = ""
if h.get("unfinished"):
unfinished = f'
Not finished. {common.rich(common.sentence(h["unfinished"]))}
'
- missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain),
+ missing = [name for name, have in ((facets.TERRAIN, terrain),
(facets.WALKING, facets.walking(rec)),
(PERMITS, h.get("permit"))) if not have]
pending = ""
diff --git a/web/tests/test_facets.py b/web/tests/test_facets.py
index b1cbb9d..8255463 100644
--- a/web/tests/test_facets.py
+++ b/web/tests/test_facets.py
@@ -173,6 +173,59 @@ class PlaceTest(unittest.TestCase):
self.assertIn('Colorado', crumbs)
+def est_hike(**kw):
+ h = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate",
+ "season_method": "Judged from the climate at the trail's elevation and from similar trails. "
+ "Snow keeps the high passes closed until June. Confidence: medium."}
+ h.update(kw)
+ return h
+
+
+class SeasonTextTest(unittest.TestCase):
+ def test_an_estimated_season_reads_about_and_has_a_note(self):
+ rec = fake(1, hike=est_hike())
+ self.assertTrue(facets.season_estimated(rec))
+ self.assertEqual(facets.season_text(rec), "About June to September")
+ note = facets.season_note(rec)
+ for want in ("No page states a season", "estimated from the climate at the trail's elevation and from "
+ "similar trails", "Snow keeps the high passes closed until June.", "Confidence: medium.",
+ "People do walk it outside these months."):
+ self.assertIn(want, note)
+ self.assertNotIn("Judged from", note) # the standard lead is said once, in the note's own words
+
+ def test_a_stated_season_is_unchanged_and_has_no_note(self):
+ rec = fake(1, hike={"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "primary"})
+ self.assertFalse(facets.season_estimated(rec))
+ self.assertEqual(facets.season_text(rec), "June to September")
+ self.assertEqual(facets.season_note(rec), "")
+
+ def test_an_estimated_all_year_season_reads_about_all_year(self):
+ rec = fake(1, hike=est_hike(season="All year", months=list(range(1, 13))))
+ self.assertEqual(facets.season_text(rec), "About all year")
+
+ def test_it_is_not_estimated_without_a_basis_or_a_method(self):
+ self.assertFalse(facets.season_estimated(fake(1, hike={"season": "May", "months": [5]})))
+ self.assertFalse(facets.season_estimated(fake(1)))
+ self.assertEqual(facets.season_kind(fake(1)), "")
+
+ def test_a_season_judged_from_pages_that_differ_says_so(self):
+ rec = fake(1, hike=est_hike(season_basis="sources", season_method=(
+ "The pages differ: one gives May to October and one gives June to November. It was set by "
+ "judgement from both and from the climate. Confidence: medium.")))
+ self.assertTrue(facets.season_estimated(rec))
+ self.assertEqual(facets.season_kind(rec), "judged")
+ self.assertEqual(facets.season_text(rec), "About June to September")
+ note = facets.season_note(rec)
+ self.assertIn("No one page states this season.", note)
+ self.assertIn("The pages differ", note)
+ self.assertNotIn("estimated from the climate at the trail's elevation", note)
+ self.assertIn("It is a judgement", facets.season_basis_line(rec))
+
+ def test_the_basis_line_gives_the_method_for_an_estimate(self):
+ line = facets.season_basis_line(fake(1, hike=est_hike()))
+ self.assertTrue(line.endswith("Confidence: medium. No page states a season."), line)
+
+
class MissingValuesTest(unittest.TestCase):
def recs(self, n_with, n_without):
return ([fake(i, hike={"months": [7, 8], "season": "July and August", "terrain": ["alpine"]})
@@ -189,22 +242,24 @@ class MissingValuesTest(unittest.TestCase):
self.assertIn('name="terrain"', form)
def test_missing_count_is_said(self):
+ # the generic mechanism, shown with terrain: no real trail lacks a season any more
form = home.finder_form(self.recs(10, 12))
- self.assertIn('data-missing="season" hidden>12 trails have no season on file.', form)
self.assertIn('data-missing="terrain" hidden>12 trails have no terrain on file.', form)
- self.assertEqual(facets.missing_text(1, "season"), "1 trail has no season on file.")
- self.assertEqual(facets.missing_text(0, "season"), "")
+ self.assertEqual(facets.missing_text(1, "terrain"), "1 trail has no terrain on file.")
+ self.assertEqual(facets.missing_text(0, "terrain"), "")
# full coverage: no note
- self.assertNotIn('data-missing="season"', home.finder_form(self.recs(5, 0)))
+ self.assertNotIn('data-missing="terrain"', home.finder_form(self.recs(5, 0)))
def test_rows_without_a_value_carry_none(self):
- # the script leaves out a row whose data-months is empty while a month is chosen
row = home.entry(fake(1))
- self.assertIn('data-months=""', row)
self.assertIn('data-terrain=""', row)
row = home.entry(fake(1, hike={"months": [7, 8, 9]}))
self.assertIn('data-months="7 8 9"', row)
+ def test_every_real_trail_has_months(self):
+ for rec in records.load_records(ROOT):
+ self.assertTrue(facets.months(rec), rec["id"])
+
def test_script_leaves_out_missing_values(self):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
@@ -287,6 +342,31 @@ class BuiltVocabularyTest(unittest.TestCase):
self.maxDiff = None
self.assertEqual(bad[:40], [])
+ def test_no_page_says_only_some_trails_have_a_season(self):
+ found = []
+ for dirpath, _dirs, files in os.walk(OUT):
+ for name in files:
+ if name.endswith(".html") and "changelog" not in dirpath: # its old entries say what was
+ path = os.path.join(dirpath, name)
+ with open(path, encoding="utf-8") as f:
+ doc = f.read()
+ for phrase in ("Only some trails have a season", "season on file", "Not on file",
+ "data-unseasoned", "Show them"):
+ if phrase in doc:
+ found.append((os.path.relpath(path, OUT), phrase))
+ self.assertEqual(found[:10], [])
+
+ def test_an_estimated_season_reads_about_on_its_page_and_a_stated_one_does_not(self):
+ est = [r for r in records.load_records(ROOT) if facets.season_estimated(r)]
+ stated = [r for r in records.load_records(ROOT) if not facets.season_estimated(r)]
+ self.assertEqual(len(est) + len(stated), 223)
+ for rec in est[:10]:
+ doc = self.read(f"trails/{rec['id']}/index.html")
+ self.assertIn(facets.season_text(rec), html.unescape(doc), rec["id"])
+ self.assertIn("People do walk it outside these months.", html.unescape(doc), rec["id"])
+ for rec in stated[:10]:
+ self.assertNotIn("People do walk it outside these months.", html.unescape(self.read(f"trails/{rec['id']}/index.html")))
+
def test_navigation_has_four_sections_and_saved(self):
doc = self.read("index.html")
nav = re.search(r'', doc).group(1)
diff --git a/web/tests/test_filter_bar.py b/web/tests/test_filter_bar.py
index e5538eb..84e9fb1 100644
--- a/web/tests/test_filter_bar.py
+++ b/web/tests/test_filter_bar.py
@@ -235,13 +235,13 @@ def rows_of(body):
d = {k: html.unescape(v) for k, v in re.findall(r' data-([a-z]+)="([^"]*)"', attrs)}
split = lambda v: [x for x in v.split(" ") if x] # noqa: E731
out.append({"id": d["id"], "search": [" " + t + " " for t in d["search"].split("|")], "where": split(d["where"]), "km": float(d["km"]),
- "time": d["time"], "months": split(d["months"]), "terrain": split(d["terrain"]),
+ "time": d["time"], "months": split(d["months"]), "estimate": d.get("estimate") == "yes", "terrain": split(d["terrain"]),
"kind": d["kind"], "walking": d["walking"], "shape": d["shape"], "gpx": d["gpx"]})
return out
def state(**kw):
- s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "kind": "",
+ s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "stated": False, "kind": "",
"time": [], "terrain": [], "walking": [], "shape": [], "gpx": []}
s.update(kw)
return s
@@ -366,45 +366,75 @@ class PanelInTheFlowTest(unittest.TestCase):
self.assertIn("if (window.location.hash === '#filters') showPanels(true);", js)
-class UnseasonedNoteTest(unittest.TestCase):
- """A month filter says how many trails it leaves out for having no season on file."""
+class LeaveOutEstimatesTest(unittest.TestCase):
+ """The month filter can leave estimated seasons out, and says nothing about trails with no season."""
- def test_a_finder_list_has_the_note_and_it_starts_hidden(self):
+ def test_the_month_field_has_the_checkbox_and_it_starts_disabled(self):
recs = recordsmod.load_records(ROOT)
- body = str(home.results(recs, finder=True))
- self.assertIn('
', body)
- self.assertIn('data-unseasoned-show>Show them', body)
- self.assertNotIn("data-unseasoned", str(home.results(recs)))
+ form = home.finder_form(recs)
+ field = form[form.index('data-facet="month"'):]
+ field = field[:field.index("
")]
+ self.assertIn('', field)
+ self.assertIn("Leave out estimated seasons", field)
- def test_the_script_counts_it_over_the_rows_of_the_list_and_show_them_clears_the_month(self):
+ def test_there_is_no_checkbox_where_no_trail_has_an_estimated_season(self):
+ recs = [r for r in recordsmod.load_records(ROOT) if not facets.season_estimated(r)]
+ self.assertNotIn('name="stated"', home.finder_form(recs))
+
+ def test_the_results_have_no_unseasoned_note(self):
+ recs = recordsmod.load_records(ROOT)
+ for body in (str(home.results(recs, finder=True)), str(home.results(recs))):
+ self.assertNotIn("data-unseasoned", body)
+ self.assertNotIn("Show them", body)
+ self.assertNotIn("no season on file", body)
js = read(WEB, "assets", "app.js")
- self.assertIn("if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++;", js)
- self.assertIn("' trails with no season on file are not shown.'", js)
- self.assertIn("el.month.value = '';", js)
+ self.assertNotIn("unseasoned", js.lower())
+ self.assertNotIn("no season on file", js)
+
+ def test_a_row_carries_whether_its_season_is_an_estimate(self):
+ est = next(r for r in recordsmod.load_records(ROOT) if facets.season_estimated(r))
+ stated = next(r for r in recordsmod.load_records(ROOT) if not facets.season_estimated(r))
+ self.assertIn('data-estimate="yes"', str(home.entry(est)))
+ self.assertNotIn("data-estimate", str(home.entry(stated)))
+
+ def test_the_script_reads_the_checkbox_and_writes_it_in_the_address(self):
+ js = read(WEB, "assets", "app.js")
+ self.assertIn("if (s.month && s.stated && d.estimate) return false;", js)
+ self.assertIn("if (s.month && s.stated) p.set('stated', '1');", js)
+ self.assertIn("estimate: d.estimate === 'yes'", js)
@unittest.skipUnless(NODE, "node is not installed")
- def test_the_number_is_the_trails_that_pass_everything_else_and_have_no_season(self):
- recs = recordsmod.load_records(ROOT)
- rows = rows_of(home.render(recs, SITE, ROOT))
+ def test_with_stated_on_estimated_rows_leave_the_month_and_the_counts_follow(self):
+ def row(i, months, estimate):
+ return {"id": f"t{i}", "search": [" ", " ", " ", " "], "where": [], "km": 100.0, "time": "week",
+ "months": [str(m) for m in months], "estimate": estimate, "terrain": [], "kind": "trail", "walking": "",
+ "shape": "", "gpx": "none"}
+ rows = [row(1, [7], True), row(2, [7], False), row(3, [7, 8], False), row(4, [8], True)]
+ off = run_counts(rows, state(month="7"))
+ on = run_counts(rows, state(month="7", stated=True))
+ self.assertEqual((off["total"], off["month"]["7"], off["month"]["8"]), (3, 3, 2))
+ self.assertEqual((on["total"], on["month"]["7"], on["month"]["8"]), (2, 2, 1))
+ # with no month chosen it does nothing
+ self.assertEqual(run_counts(rows, state(stated=True))["total"], 4)
+ # and the shown number is the rows that pass
prog = facet_count_source() + """
var input = JSON.parse(require('fs').readFileSync(0, 'utf8'));
input.s.max = Infinity;
-var n = 0, shown = 0;
-input.rows.forEach(function (d) {
- if (FacetCount.passes(d, input.s, '')) shown++;
- else if (!d.months.length && FacetCount.passes(d, input.s, 'month')) n++;
-});
-process.stdout.write(JSON.stringify([shown, n]));
+process.stdout.write(JSON.stringify(input.rows.filter(function (d) { return FacetCount.passes(d, input.s, ''); }).length));
"""
- for s in (state(month="8"), state(month="8", kind="route"), state(month="8", where="US-CA")):
- out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": s}),
- capture_output=True, text=True, check=True)
- shown, n = json.loads(out.stdout)
- def base(r):
- return ((not s["kind"] or facets.kind(r) == s["kind"])
- and (not s["where"] or s["where"] in facets.where_tokens(r)))
- self.assertEqual(shown, sum(1 for r in recs if base(r) and 8 in facets.months(r)))
- self.assertEqual(n, sum(1 for r in recs if base(r) and not facets.months(r)))
+ out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": state(month="7", stated=True)}),
+ capture_output=True, text=True, check=True)
+ self.assertEqual(json.loads(out.stdout), on["total"])
+
+ @unittest.skipUnless(NODE, "node is not installed")
+ def test_on_the_real_trails_the_counts_leave_out_exactly_the_estimates(self):
+ recs = recordsmod.load_records(ROOT)
+ rows = rows_of(home.render(recs, SITE, ROOT))
+ for month in (1, 7):
+ c = run_counts(rows, state(month=str(month), stated=True))
+ want = sum(1 for r in recs if month in facets.months(r) and not facets.season_estimated(r))
+ self.assertEqual(c["total"], want)
+ self.assertEqual(c["month"][str(month)], want)
if __name__ == "__main__":
diff --git a/web/tests/test_hike.py b/web/tests/test_hike.py
index d49e5e3..81916f8 100644
--- a/web/tests/test_hike.py
+++ b/web/tests/test_hike.py
@@ -137,6 +137,29 @@ class TrailPageTest(unittest.TestCase):
self.assertNotIn("The season comes from", trail.hike_sources_block(rec))
self.assertEqual(facets.season_basis(rec), "")
+ def test_an_estimated_season_row_carries_the_note(self):
+ rec = sample_record("X Trail")
+ rec["hike"] = dict(FULL_HIKE, season="April to October", months=[4, 5, 6, 7, 8, 9, 10],
+ season_basis="estimate",
+ season_method="Judged from the climate at the trail's elevation and from similar "
+ "trails. Snow and mud last into March. Confidence: high.")
+ t = text(top_part(render(rec)))
+ self.assertIn("Season About April to October", t)
+ self.assertIn("No page states a season.", t)
+ self.assertIn("Confidence: high.", t)
+ self.assertIn("People do walk it outside these months.", t)
+ self.assertIn("No source gives a season; the climate suggests about April to October.", t)
+ self.assertNotIn("The usual season is", t)
+ block = html.unescape(trail.hike_sources_block(rec))
+ self.assertIn("Snow and mud last into March. Confidence: high. No page states a season.", block)
+
+ def test_a_stated_season_row_has_no_note(self):
+ rec = sample_record("X Trail")
+ rec["hike"] = dict(FULL_HIKE, season_basis="primary")
+ t = text(top_part(render(rec)))
+ self.assertIn("Season March to October", t)
+ self.assertNotIn("No page states a season", t)
+
def test_partial_hike_table(self):
rec = sample_record("X Trail")
rec["hike"] = {"shape": "loop", "start": "Lake Camp", "days": [4, 6], "checked": "2026-11-13"}
@@ -144,7 +167,7 @@ class TrailPageTest(unittest.TestCase):
t = text(top)
self.assertIn("Shape Loop. Starts and ends at Lake Camp", t)
self.assertIn("Time 4 to 6 days", t)
- self.assertIn("Season, terrain, walking and permits are not on file for this trail yet.", t)
+ self.assertIn("Terrain, walking and permits are not on file for this trail yet.", t)
for absent in ("Season March", "High point", "Terrain Alpine", "Permits", "Not finished", "Official site"):
self.assertNotIn(absent, t, absent)
# no summary: the lede is built from the record
@@ -175,7 +198,7 @@ class TrailPageTest(unittest.TestCase):
self.assertIn("Where Arizona , United States", t)
# every trail has a time: here estimated from its 100 km, and labelled so
self.assertIn("Time About 4 to 5 days Estimated from the length, at 12 to 19 mi 20 to 30 km a day.", t)
- self.assertIn("Season, terrain, walking and permits are not on file for this trail yet.", t)
+ self.assertIn("Terrain, walking and permits are not on file for this trail yet.", t)
self.assertNotIn("Where the hiking facts come from", body)
# no track: the page says so plainly and points at the source
self.assertIn("No GPX here", t)
diff --git a/web/tests/test_structured_data.py b/web/tests/test_structured_data.py
index 32448a5..4f5e65d 100644
--- a/web/tests/test_structured_data.py
+++ b/web/tests/test_structured_data.py
@@ -201,6 +201,17 @@ class JsonLdTest(unittest.TestCase):
count += 1
self.assertEqual(count, len(self.records))
+ def test_no_estimated_season_appears_in_structured_data(self):
+ seen = 0
+ for rec in self.records:
+ h = rec.get("hike", {})
+ if not (h.get("season_basis") == "estimate" or h.get("season_method")):
+ continue
+ seen += 1
+ page = self.pages[f"trails/{rec['id']}/index.html"]
+ self.assertNotIn("Usual season", page, rec["id"])
+ self.assertGreater(seen, 0)
+
def test_a_trail_states_only_what_its_record_holds(self):
built_derived = {r["id"]: r["derived"] for r in json.loads(read("data/trails.json"))}
for rec in self.records:
@@ -211,7 +222,9 @@ class JsonLdTest(unittest.TestCase):
self.assertEqual(props[("Published length", "KMT")]["value"], rec["length_km"], rec["id"])
h = rec.get("hike", {})
self.assertEqual(("Start", None) in props, bool(h.get("start")), rec["id"])
- self.assertEqual(("Usual season", None) in props, bool(h.get("season")), rec["id"])
+ self.assertEqual(("Usual season", None) in props,
+ bool(h.get("season") and h.get("season_basis") != "estimate" and not h.get("season_method")),
+ rec["id"])
self.assertEqual(any(k[0] == "Highest point" for k in props),
bool(h.get("high_point_m") or h.get("high_point")), rec["id"])
if h.get("official_url"):
diff --git a/web/tests/test_trust.py b/web/tests/test_trust.py
index eb62c0f..4defd47 100644
--- a/web/tests/test_trust.py
+++ b/web/tests/test_trust.py
@@ -16,7 +16,7 @@ WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
-from olt import common, docs, hike, records, seo, site, trail # noqa: E402
+from olt import common, docs, facets, hike, records, seo, site, trail # noqa: E402
SITE = site.load()
@@ -160,6 +160,21 @@ class InBrief(unittest.TestCase):
("range", "The usual season is spring and fall"))
self.assertIsNone(season("Best travelled " + "in the later part of the summer " * 5))
+ def test_an_estimated_season_sentence_says_no_source_gives_one(self):
+ rec = sparse_record()
+ rec["hike"] = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate",
+ "season_method": "Judged from the climate. Snow. Confidence: low."}
+ self.assertEqual(trail.season_sentence(rec),
+ ("estimate", "No source gives a season; the climate suggests about June to September"))
+ rec["hike"]["season_basis"] = "sources"
+ self.assertEqual(trail.season_sentence(rec),
+ ("estimate", "The pages differ on the season; it is judged to be about June to September"))
+ rec["hike"].update(season="All year", months=list(range(1, 13)), season_basis="estimate")
+ self.assertEqual(trail.season_sentence(rec)[1], "No source gives a season; the climate suggests about all year")
+ # the sentence stands alone: it is never joined to the GPX clause with "and"
+ paragraph = " ".join(trail.brief_sentences(rec))
+ self.assertIn("No source gives a season; the climate suggests about all year.", paragraph)
+
def test_a_permit_is_said_only_when_it_is_short(self):
short = sparse_record()
short["hike"] = {"permit": "No permit is needed to hike it."}
@@ -217,7 +232,8 @@ class InBrief(unittest.TestCase):
s = self.sentences(rec)
paragraph = " ".join(s)
self.assertGreaterEqual(len(s), 2, rec["id"])
- self.assertLessEqual(len(s), 4, rec["id"])
+ # four sentences, and a fifth where the season is an estimate, which is always said
+ self.assertLessEqual(len(s), 4 + facets.season_estimated(rec), rec["id"])
self.assertIn("GPX", paragraph, rec["id"])
self.assertNotRegex(paragraph, r"\b(Season|Permits are noted)\b", rec["id"])
for bad in ("None", "{", "}", " ", " ,", " .", "unknown", "not known", "n/a"):
@@ -232,8 +248,13 @@ class InBrief(unittest.TestCase):
self.assertIn("usually takes", paragraph, rec["id"])
else:
self.assertNotIn("usually takes", paragraph, rec["id"])
- if not (h.get("season") or h.get("months")):
- self.assertNotRegex(paragraph, r"usual season|walked all year|Northbound|season", rec["id"])
+ self.assertTrue(h.get("season"), rec["id"])
+ if facets.season_estimated(rec):
+ self.assertIn("No source gives a season" if not facets.season_pages_differ(rec)
+ else "The pages differ on the season", paragraph, rec["id"])
+ self.assertNotIn("The usual season is", paragraph, rec["id"])
+ else:
+ self.assertNotIn("No source gives a season", paragraph, rec["id"])
if "No permit" in paragraph or "permit" in paragraph.lower():
self.assertIn(common.sentence(h.get("permit", "")), paragraph, rec["id"])
self.assertEqual("highest point" in paragraph,
diff --git a/web/tests/test_views.py b/web/tests/test_views.py
index 1c8a2c3..92b76bb 100644
--- a/web/tests/test_views.py
+++ b/web/tests/test_views.py
@@ -8,6 +8,7 @@ These do not need the built site.
"""
import os
import re
+from html import unescape as html_unescape
import shutil
import tempfile
import sys
@@ -117,7 +118,7 @@ class MonthListTest(unittest.TestCase):
self.assertEqual(keys(recs, "hike-in-july"), ["t1"])
self.assertEqual(keys(recs, "hike-in-august"), ["t2"])
- def test_a_month_needs_eight_trails_and_says_how_many_have_a_season(self):
+ def test_a_month_needs_eight_trails(self):
july = browse.by_key("hike-in-july")
self.assertEqual(july.min_size, 8)
self.assertFalse(browse.is_shown(7, 100, july.min_size))
@@ -126,8 +127,35 @@ class MonthListTest(unittest.TestCase):
shown = {lst.key for lst, _ in browse.shown(recs)}
self.assertIn("hike-in-july", shown)
self.assertNotIn("hike-in-august", shown)
+
+ def est(self, i, months=(7,)):
+ return fake(i, hike={"months": list(months), "season": "July", "season_basis": "estimate",
+ "season_method": "Judged. Confidence: low."})
+
+ def test_a_month_note_counts_stated_and_estimated_exactly(self):
+ july = browse.by_key("hike-in-july")
+ recs = [fake(i, hike={"months": [7], "season": "July", "season_basis": "primary"}) for i in range(10)] \
+ + [self.est(20 + i) for i in range(5)]
note = july.note(browse.members(july, recs), recs)
- self.assertIn("Only 10 of the 20 trails have a season on file", note)
+ self.assertEqual(note, "A source states the season for 10 of these. For the other 5 it is estimated "
+ "from climate, and marked.")
+
+ def test_a_month_list_with_no_estimates_says_so(self):
+ july = browse.by_key("hike-in-july")
+ recs = [fake(i, hike={"months": [7], "season": "July", "season_basis": "primary"}) for i in range(10)]
+ self.assertEqual(july.note(browse.members(july, recs), recs), "A source states the season for all 10.")
+ recs = [self.est(i) for i in range(3)]
+ self.assertEqual(july.note(browse.members(july, recs), recs),
+ "No source states the season for these, so each is estimated from climate.")
+
+ def test_the_month_blurb_no_longer_says_only_some_trails(self):
+ group = {key: blurb for key, _title, blurb in browse.GROUPS}["month"]
+ self.assertEqual(group, "Trails normally hiked in the month. Estimated seasons are marked.")
+ self.assertEqual(browse.by_key("hike-in-july").blurb,
+ "Trails normally hiked in July. Estimated seasons are marked.")
+ for lst in browse.LISTS:
+ self.assertNotIn("Only some trails", lst.blurb)
+ self.assertNotIn("season on file", lst.blurb)
def test_every_list_has_a_group_and_every_group_a_heading(self):
headings = {k for k, _, _ in browse.GROUPS}
@@ -628,6 +656,34 @@ class RealDataTest(unittest.TestCase):
n_ver = len(reference.verified(self.records))
self.assertIn(f"{n_ver} of the {len(self.records)} trails have a track", str(body))
+ def method_text(self):
+ title, desc, body = reference.method_page(self.records, SITE, ROOT)
+ return re.sub(r"\s+", " ", html_unescape(re.sub(r"<[^>]+>", " ", str(body))))
+
+ def test_the_reference_page_counts_stated_and_estimated_seasons(self):
+ text = self.method_text()
+ kinds = {k: sum(1 for r in self.records if facets.season_kind(r) == k) for k in ("stated", "judged", "estimated")}
+ self.assertEqual(sum(kinds.values()), len(self.records))
+ self.assertIn(f"A season a page states Records with it {kinds['stated']} Records without {len(self.records) - kinds['stated']}", text)
+ self.assertIn(f"A season estimated from climate Records with it {kinds['estimated']} Records without {len(self.records) - kinds['estimated']}", text)
+ self.assertIn(f"A season set from pages that differ Records with it {kinds['judged']} Records without {len(self.records) - kinds['judged']}", text)
+ self.assertIn(f"All trails Trails {len(self.records)}", text)
+
+ def test_the_reference_page_gives_the_blind_test_from_its_file(self):
+ blind = datafiles.blind_test(ROOT)
+ text = self.method_text()
+ self.assertIn(f"the method was run blind on {blind['tested']} trails whose seasons a page does state", text)
+ self.assertIn(f"It matched {blind['matched']} of them ({round(blind['share'] * 100)} percent) within one month at "
+ "each end", text)
+ for name, v in blind["by_confidence"].items():
+ self.assertIn(f"{name} {v['matched']} of {v['tested']} ({round(v['share'] * 100)} percent)", text)
+ self.assertIn("not a promise for any one trail", text)
+
+ def test_the_glossary_no_longer_says_only_some_records_state_a_season(self):
+ season = next(t for t in reference.terms(ROOT) if t["id"] == "season")
+ self.assertNotIn("Only some", season["definition"])
+ self.assertIn("estimated", season["definition"])
+
def test_every_place_page_has_a_summary_paragraph(self):
by_slug, _ = regions.collect_regions(self.records)
for slug in by_slug:
From 33ca4c218f7cf12519a995b701605853857e8ae7 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:26:51 -0700
Subject: [PATCH 14/30] Check estimated seasons monthly, and write the season
steps into the audit
---
.github/workflows/season-check.yml | 26 ++++++++++
docs/audit.md | 12 +++++
tools/tests/test_season_audit.py | 80 ++++++++++++++++++++++++++++++
3 files changed, 118 insertions(+)
create mode 100644 .github/workflows/season-check.yml
create mode 100644 docs/audit.md
create mode 100644 tools/tests/test_season_audit.py
diff --git a/.github/workflows/season-check.yml b/.github/workflows/season-check.yml
new file mode 100644
index 0000000..35c32fc
--- /dev/null
+++ b/.github/workflows/season-check.yml
@@ -0,0 +1,26 @@
+name: Season check
+
+# Once a month, rerun the machine estimate for every estimated season and the fit against the
+# sourced seasons. A failure lists the estimates whose inputs have changed; see docs/audit.md.
+on:
+ schedule:
+ - cron: "17 6 1 * *"
+ workflow_dispatch:
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - id: month
+ run: echo "month=$(date +%Y-%m)" >> "$GITHUB_OUTPUT"
+ - uses: actions/cache@v4
+ with:
+ path: ~/.cache/longhikes-climate
+ key: climate-${{ steps.month.outputs.month }}
+ restore-keys: climate-
+ - run: python3 tools/estimate_season.py check
diff --git a/docs/audit.md b/docs/audit.md
new file mode 100644
index 0000000..4c363f8
--- /dev/null
+++ b/docs/audit.md
@@ -0,0 +1,12 @@
+# The monthly audit
+
+The checklist for the roughly monthly audit of everything. `/refresh-trails` (`.claude/skills/refresh-trails/SKILL.md`) is the step for pages and records. Each section below is one topic, with its own numbered steps. A section is self-contained: it says what to run, what to act on, and when the step is done.
+
+## Seasons
+
+Every trail has a season. Where a page states one, the season is that page's. Where none does, the season is an estimate: set by a reviewer from the trail's climate and the seasons of similar trails, with its confidence on the record (`docs/season-judging.md`). The aim of this audit is that estimates shrink over time, and that none goes stale unnoticed.
+
+1. Search afresh for a page that states the season of every trail still marked `estimate`. List them with `python3 tools/estimate_season.py estimates`. For each, follow `docs/season-research.md`: the trail's holder or a government page first, then an established hiking reference, a guidebook publisher's page or an association list. When a page states a season, replace the estimate through `tools/refresh.py` (propose, collect, apply): give the page's season and months, the basis (`primary`, `sources` or `source`), the page as a `[[hike.source]]` naming `season` and `months`, and remove the climate source and `season_method`. A change to the season gets a `[[history]]` entry like any other fact. Then run `python3 tools/season_judge.py inputs` so that the record of estimate inputs drops the trail. A trail with no page found stays an estimate, and nothing else about it changes.
+2. Re-run the machine estimate and flag any estimate whose inputs have changed: `python3 tools/estimate_season.py check`. It reruns the machine estimate for every estimate, compares it, the climate at the trail and the sourced trails it is compared with against what was recorded in `tools/season_inputs.json` when the season was set, and lists each trail whose inputs differ. The listing is a flag, not a rewrite. For each trail listed, build its packet (`python3 tools/season_judge.py packets`), look at what changed, and either keep the season or set it again by judgement. Then run `python3 tools/season_judge.py inputs` to record the inputs as they now are. The check also fails when the blind test of the method (`tools/season_blind_test.json`) is below its bar, or when the fit of the machine estimate against the sourced seasons has got worse.
+
+The same check runs on its own on the first of each month (`.github/workflows/season-check.yml`), so a changed estimate is noticed even when the audit is late. The audit is still the step that acts on it.
diff --git a/tools/tests/test_season_audit.py b/tools/tests/test_season_audit.py
new file mode 100644
index 0000000..5cb1ccb
--- /dev/null
+++ b/tools/tests/test_season_audit.py
@@ -0,0 +1,80 @@
+"""Tests for the written audit checklist and the monthly season check.
+
+Run from the repository root:
+ python3 -m unittest discover tools/tests
+"""
+import os
+import re
+import sys
+import unittest
+
+sys.dont_write_bytecode = True
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import estimate_season as E # noqa: E402
+
+ROOT = E.ROOT
+
+
+def read(*parts):
+ with open(os.path.join(ROOT, *parts), encoding="utf-8") as f:
+ return f.read()
+
+
+def section(text, heading):
+ start = text.index(f"## {heading}")
+ nxt = text.find("\n## ", start + 1)
+ return text[start:nxt if nxt != -1 else len(text)]
+
+
+class AuditChecklistTest(unittest.TestCase):
+ def test_the_audit_checklist_has_a_seasons_section_naming_both_steps(self):
+ doc = read("docs", "audit.md")
+ seasons = section(doc, "Seasons")
+ self.assertIn("estimate_season.py check", seasons)
+ self.assertIn("estimate_season.py estimates", seasons)
+ self.assertIn("docs/season-research.md", seasons)
+ self.assertIn("search afresh for a page that states the season", seasons.lower().replace("\n", " "))
+ self.assertIn("re-run the machine estimate", seasons.lower())
+ self.assertIn("1. ", seasons)
+ self.assertIn("2. ", seasons)
+
+ def test_the_commands_it_names_exist(self):
+ import contextlib
+ import io
+ import season_judge
+ for module, subs in ((E, ("check", "estimates")), (season_judge, ("inputs", "packets", "score", "proposals"))):
+ for sub in subs:
+ out = io.StringIO()
+ with contextlib.redirect_stdout(out), self.assertRaises(SystemExit) as stop:
+ module.main([sub, "--help"])
+ self.assertEqual(stop.exception.code, 0, sub)
+ self.assertIn(f" {sub}", out.getvalue())
+
+ def test_the_estimates_command_prints_one_id_a_line(self):
+ ids = E.estimates(ROOT)
+ self.assertEqual(len(ids), 69)
+ self.assertEqual(ids, sorted(ids))
+
+ def test_house_wording_in_the_audit_doc_and_workflow(self):
+ dash = re.compile("[\u2013\u2014]")
+ for rel in (("docs", "audit.md"), ("docs", "season-judging.md")):
+ text = re.sub(r"`[^`]*`", "", read(*rel))
+ self.assertIsNone(dash.search(text), rel)
+ self.assertNotIn(" - ", text, rel)
+ # in the workflow a dash is YAML's own, so only its comments are read
+ comments = " ".join(l for l in read(".github", "workflows", "season-check.yml").splitlines()
+ if l.lstrip().startswith("#"))
+ self.assertIsNone(dash.search(comments))
+ self.assertNotIn(" - ", comments)
+
+
+class MonthlyWorkflowTest(unittest.TestCase):
+ def test_the_monthly_workflow_runs_the_check_on_a_schedule(self):
+ text = read(".github", "workflows", "season-check.yml")
+ for want in ("schedule", "workflow_dispatch", "estimate_season.py check", "cron:", "longhikes-climate"):
+ self.assertIn(want, text)
+
+
+if __name__ == "__main__":
+ unittest.main()
From 5a4fce26f004ed44d7e3ab3694f5b3cfdbdb9299 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:26:51 -0700
Subject: [PATCH 15/30] Every trail now has a season
---
CHANGELOG.md | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7fbdc5..756ba31 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## 2026-11-20 - Every trail now has a season
+
+- All 223 trails now have a season. 148 come from a page that states one. 6 were set by judgement from pages that disagree, none of them the trail's own, its association's or its route author's. The other 69 are estimates, because no page states a season for them.
+- An estimate never reads as a fact. A trail's page shows it as "About April to October", with a short note: no page states a season, it was estimated from the climate at the trail's elevation and from similar trails, what sets the season there, how confident the estimate is, and that people do walk the trail outside those months. Lists and tables mark an estimate, and it is left out of the data that search engines read. The 6 set from pages that disagree read the same way, and their note says the pages differ.
+- How an estimate is made: a reviewer is given the trail's location and elevation, its monthly climate (CHELSA, public domain, with NOAA elevation), a climate model's own estimate, and the ten most similar trails whose season a page states, and sets the months. The climate model alone matched 67.6 percent of the known seasons within a month at each end, under the 75 percent the owner asked for, so it is one input and not the answer.
+- How it was tested: the same reviewers estimated the 148 trails whose season a page does state, from packets with that season hidden. They matched 114 of them (77.0 percent) within a month at each end: 48 of 52 where they were highly confident, 55 of 76 at medium confidence, and 11 of 20 at low. The reference page and the glossary give these figures, read from a data file.
+- The "By month" lists now include every trail and mark the estimated seasons, and the note that only some trails have a season is gone. The month filter has a box to leave estimated seasons out.
+- An estimate is replaced when a page that states a season is found. The monthly audit searches again for every one, and a monthly check reruns the climate model for each estimate and flags any whose inputs have changed.
+- For contributors: `hike.season_basis` may now be `estimate`, with a `hike.season_method` that ends "Confidence: high.", "Confidence: medium." or "Confidence: low." and one source that cites the climate data; a season is required on every trail, and the validator refuses an estimate that cites an ordinary page. The packet builder and the blind scorer are `tools/season_judge.py`, the reviewers' instruction is `docs/season-judging.md`, and the audit steps are in `docs/audit.md`.
+
## 2026-11-20 - Seasons for 39 more trails
- 39 trails that had no season now have one, each read from a page and marked with where it came from. 10 of them are from the body that manages the trail, the trail's own association, or for a route its author; the other 29 are from other pages, and 2 of those rest on two pages from different publishers. Where a page gives only a start date, one segment or a word like "spring", the season says only that.
From b498cf25eb7747352e1bc9320f9b32a28b7d26ff Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:27:05 -0700
Subject: [PATCH 16/30] Update the season design to the judged method and its
blind test
---
.../2026-11-20-season-on-every-trail-design.md | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md b/docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md
index 5b53580..573a44d 100644
--- a/docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md
+++ b/docs/superpowers/specs/2026-11-20-season-on-every-trail-design.md
@@ -1,6 +1,6 @@
# A season on every trail
-Design, 2026-11-20. Status: awaiting approval.
+Design, 2026-11-20. Status: built; the method changed after the climate model was tried (see "What changed in the method").
## Intent
@@ -194,6 +194,17 @@ What the tool does:
- Tests: every record has season, months and basis; basis fits the sources;
estimates have a method; no page says a season is missing.
+## What changed in the method
+
+The plan above chose a rule over climate normals for Step 3. It was built and tested (`tools/estimate_season.py`, `tools/season_model.py`; CHELSA V2.1 1981 to 2010 normals, CC0, with NOAA ETOPO 2022 elevation), and it matched only 67.6 percent of the sourced seasons within one month at each end, under the owner's bar of 75 percent. Its output is therefore not written to a record. What was decided instead:
+
+- **A reviewer judges each estimate.** For each of the 75 trails with no season, a reviewer set the months from a packet: the trail's location, elevation, monthly climate normals, the machine estimate, and the ten most similar sourced trails (`tools/season_judge.py packets`; the reviewer's instruction is `docs/season-judging.md`). The machine estimate stays in the repository as an input to the packets and as the monthly check.
+- **The method is tested blind.** The same reviewers estimated the 148 trails whose season a page states, from identical packets with the season hidden, and a trail's comparable trails never came from its own part of the split. They matched 114 of 148 (77.0 percent), by the reviewer's confidence 48 of 52 (high), 55 of 76 (medium) and 11 of 20 (low). The figures are in `tools/season_blind_test.json`, written by `season_judge.py score`, and the site reads them.
+- **An estimate is stricter.** `season_basis = "estimate"` means no page states a season. `season` is built from `months`; `season_method` is one or two plain sentences saying how it was set and what sets the season there, ending "Confidence: high.", "medium." or "low."; and its one `[[hike.source]]` names `season` and `months` and cites the climate data. The validator refuses an estimate with any ordinary page naming the season, or with no method, and requires a season on every trail.
+- **Pages that disagree.** Six trails have pages that disagree where none is the managing body, association or route author. Their season is set by judgement from all the pages and the estimate: basis `sources`, the pages cited as sources naming the season, and a `season_method` saying the pages differ and how it was settled. A season with a method is shown as an estimate (it reads "About" with a note), left out of structured data, and not counted among the seasons a page states.
+- **The monthly check** (`estimate_season.py check`) reruns the machine estimate for every estimate and flags any whose inputs have changed since `tools/season_inputs.json` recorded them. It does not rewrite anything. The audit (`docs/audit.md`) also searches afresh for a page for every estimate.
+- **On the site**, a trail's page reads "About April to October" with a note (no page states a season; estimated from the climate at the trail's elevation and from similar trails; what sets it there; the confidence; that people walk it outside these months). Rows, tables and month lists mark estimates, the month filter can leave them out, and the reference page and glossary give the counts and the blind-test result.
+
## Open risks
- Climate normals are coarse in steep terrain. The fit against sourced
From 3305c23ee5e88e4efaf870044e8950b80dc76799 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:33:21 -0700
Subject: [PATCH 17/30] Say season once where a source names season and months
---
web/olt/trail.py | 2 +-
web/tests/test_hike.py | 6 ++++++
2 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/web/olt/trail.py b/web/olt/trail.py
index 5a5f11f..c61a515 100644
--- a/web/olt/trail.py
+++ b/web/olt/trail.py
@@ -1567,7 +1567,7 @@ def hike_sources_block(rec):
for src in hike.sources(rec):
url = src.get("url", "")
who = src.get("publisher") or (host(url) if url else "Source")
- facts_ = [words.HIKE_FACTS.get(f, f) for f in src.get("facts", [])]
+ facts_ = list(dict.fromkeys(words.HIKE_FACTS.get(f, f) for f in src.get("facts", []))) # season and months read alike
what = ("For " + words.join_names(facts_)) if facts_ else ""
link = ext_link(url, who) if url else esc(who)
detail = " · ".join(x for x in (host(url) if url else "", what) if x)
diff --git a/web/tests/test_hike.py b/web/tests/test_hike.py
index 81916f8..10d5d10 100644
--- a/web/tests/test_hike.py
+++ b/web/tests/test_hike.py
@@ -153,6 +153,12 @@ class TrailPageTest(unittest.TestCase):
block = html.unescape(trail.hike_sources_block(rec))
self.assertIn("Snow and mud last into March. Confidence: high. No page states a season.", block)
+ def test_a_source_naming_season_and_months_says_season_once(self):
+ rec = sample_record("X Trail")
+ rec["hike"] = dict(FULL_HIKE, season_basis="primary")
+ block = html.unescape(trail.hike_sources_block(rec))
+ self.assertNotIn("season and season", block)
+
def test_a_stated_season_row_has_no_note(self):
rec = sample_record("X Trail")
rec["hike"] = dict(FULL_HIKE, season_basis="primary")
From a806522ee18b80bb6be2490b819c998d23683331 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:48:07 -0700
Subject: [PATCH 18/30] Give every page that lists trails the search box and
the filters that have something to offer, however few trails it holds
The cutoff of ten trails is gone, so 48 of the 60 state and province pages, the small lists and each route author's page now have the bar. A set that nothing can narrow gets the search box alone, and an option no trail has is not written. In the state-pages golden file only the hashes of the ten pages that differ changed, each by the added bar and nothing else.
---
web/olt/authors.py | 2 +-
web/olt/home.py | 22 ++++++---------
web/olt/placepages.py | 2 +-
web/olt/regions.py | 3 +--
web/tests/golden/state-pages.json | 20 +++++++-------
web/tests/test_filter_bar.py | 45 ++++++++++++++++++++++---------
6 files changed, 53 insertions(+), 41 deletions(-)
diff --git a/web/olt/authors.py b/web/olt/authors.py
index 0cd2807..b4ec238 100644
--- a/web/olt/authors.py
+++ b/web/olt/authors.py
@@ -312,7 +312,7 @@ def author_page(g, records, site, all_pages):
+ " · ".join(f'{esc(x["name"])} ({len(x["routes"])})' for x in nav_items) + "") if nav_items else ""
more = str(summary.facts(routes, records, by_authors=False)) if n >= 3 else ""
briefs = "".join(f'
\n{trail.brief(r)}\n' for r in routes)
- listing = home.results(groups=[(None, routes, regions.route_guides)], routes_list=True, top=2,
+ listing = home.listing(groups=[(None, routes, regions.route_guides)], routes_list=True, top=2,
by=lambda r: with_html(g, r, by_name))
route_title = "About the route" if n == 1 else "About each route"
bio = about_html(g)
diff --git a/web/olt/home.py b/web/olt/home.py
index 6994820..37235f4 100644
--- a/web/olt/home.py
+++ b/web/olt/home.py
@@ -239,17 +239,13 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
# The filters ------------------------------------------------------------------
-# One bar and one set of panels, on the home page and on every other page that shows a set of at
-# least FILTER_MIN trails (listing()), and on every park, range and wilderness page whatever its
-# size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
+# One bar and one set of panels, on the home page and on every other page that shows a set of
+# trails (listing()), whatever its size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
# cannot narrow them is left out, and an option none of them has is not written. The numbers written
# here are for the whole set; app.js counts again from the rows on the page every time anything
# changes, and hides an option that would show nothing (its counting is facetCounts(), which
# web/tests/test_filter_counts.py runs under node against counts made here from the records).
-FILTER_MIN = 10
-
-
def _length_options(steps, selected_any_last, unit="mi"):
opts = [f'' for n in steps]
if selected_any_last:
@@ -443,15 +439,13 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
"""
-def listing(recs=None, *, where="all", groups=None, always=False, **kw):
- """The rows of a page that shows a set of trails, with the filter bar over them when the set
- has at least FILTER_MIN trails (else results() alone); with always, whatever its size (the
- bar then holds only the filters that have something to offer). where: the Where filter's
- scope (finder_form). The other arguments are results()'s."""
+def listing(recs=None, *, where="all", groups=None, **kw):
+ """The rows of a page that shows a set of trails, with the filter bar over them whatever the size
+ of the set (the bar holds only the filters that have something to offer, and the search box
+ alone where nothing can narrow the set). where: the Where filter's scope (finder_form). The
+ other arguments are results()'s."""
trails = [r for g in groups for r in g[1]] if groups is not None else list(recs)
- if len(trails) < FILTER_MIN and not always:
- return results(recs, groups=groups, **kw)
- return Markup(f"""
- {home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly, always=kind.always_filters), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
+ {home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
about=f"{summary.facts(recs, records, place=place)}{summary.details(recs)}",
about_title=f"About the trails {phrase}")}
{nav}{place_links}
diff --git a/web/tests/golden/state-pages.json b/web/tests/golden/state-pages.json
index 1863e2c..6d57e57 100644
--- a/web/tests/golden/state-pages.json
+++ b/web/tests/golden/state-pages.json
@@ -1,14 +1,14 @@
{
"/regions/": "e70a9608ef0ee6a97d0591ad582abff1b165371dee5111e3277df06a53a554e1",
- "/regions/atlantic-canada/": "6af5c4a79cac82eb0a4342297fd4f6755890e98597a98f219087c56432f06243",
- "/regions/ca-on/": "12b5726d800090233f082a572cf1472f152552cef8fa5019f49b83e32e337eef",
- "/regions/central-canada/": "fa6f8bbe466b5978f1edda22371b6aab8546efa567eee0d0405c717e278b8a3e",
- "/regions/mountain-west/": "c079eb93a55c2279f24083983230057940eb032cb034057c822c52230ce22e05",
- "/regions/north/": "fdfd201ae1e42b8fd17dd055815d4b06392a8ddb6ac3e72a06f15ec2b333fb56",
- "/regions/us-co/": "45cb1b92fd22ffc35f82a26fe2c71b66836b0624bf0e195f9c4926dfab6a8900",
- "/regions/us-co/loops/": "8883c9aac63f100196f9e853d6738a42b8199f1250c10ec34d1d0cfe8c998e7d",
- "/regions/us-co/with-gpx/": "abc3f7e44cbcbf8d6cce3b5d5065e6e7c085ec5a4033842af8909077f87e1e18",
+ "/regions/atlantic-canada/": "5146b4b9d1940a268cfd2345f1eee2263fd6c7e2dfd28adfdffc3fff0e698c93",
+ "/regions/ca-on/": "d4e543c6f163ba188a34444b42c494a3dbbd26c02f2b141339bbc230cd91f84e",
+ "/regions/central-canada/": "d7478ad682d715705770d35cc902c80c40d27719e7f9f5a1d99ec702d3f7a43e",
+ "/regions/mountain-west/": "6151f5a28d366fb48aab7027f08cea6da425201d0e7327780a01dd77cedc7bc7",
+ "/regions/north/": "85ba3ea850c2df690e311cf09257f2548ed888c07c319a01fd30d5e19cdf1fd4",
+ "/regions/us-co/": "97daaf3511578896b222570cba630da2d8ca0571504ce43b3685dbe532e40f56",
+ "/regions/us-co/loops/": "03896834b5369655f7b5f26634b6d23c834b17f1a25b0ec328d44934e20e2dfa",
+ "/regions/us-co/with-gpx/": "d82eace3d70eb9b1ef1346f5a3470199bd6a00e6e104fe661bfeb80199af96b8",
"/regions/us-hi/": "1e5681ffbd50e382db7d69528fde602069006bf0cddad494d817369224bd96ad",
- "/regions/us-ut/": "065bcc01e14eb588dc1b118c466f44474fca0172c30037fb193d83a044624100",
- "/regions/western-canada/": "91b40d35dd3d1a093d38d01bbfcf1ef536221a69631fc58e46732da81d0582c3"
+ "/regions/us-ut/": "906db4153def35fa5418d0b86dba908fd27396bbc2098978ee169516e1b39785",
+ "/regions/western-canada/": "1b102ed9d47283869fdf8c8d54229d245f2113fd53c7e8ec2ecc118fd4da3b64"
}
diff --git a/web/tests/test_filter_bar.py b/web/tests/test_filter_bar.py
index 84e9fb1..1911f9a 100644
--- a/web/tests/test_filter_bar.py
+++ b/web/tests/test_filter_bar.py
@@ -1,7 +1,7 @@
"""The filter bar on every page that shows a set of trails, and the numbers beside its choices.
The bar (olt/home.py listing(), finder_form()) is the home page's, on each list, place and the Routes
-page whose set has at least home.FILTER_MIN trails, built from that page's own trails. app.js counts
+page, whatever the number of trails, built from that page's own trails. app.js counts
the choices again from the rows on the page every time anything changes (FacetCount, between the
facet-counts markers); this file runs that counting under node, on the rows the home page writes,
and checks it against counts made here straight from the records. Pages are rendered one at a time;
@@ -68,22 +68,36 @@ class WhichPagesHaveTheBarTest(unittest.TestCase):
lst = browse.by_key(key)
return regions.list_page(lst, self.shown[key], len(self.records), SITE, records=self.records)[2]
- def test_a_list_page_a_place_page_a_part_of_the_country_and_routes_have_it(self):
- self.assertGreaterEqual(len(self.shown["loops"]), home.FILTER_MIN)
- self.assertTrue(form_of(self.list_body("loops")))
+ def test_a_list_page_a_place_page_a_part_of_the_country_and_routes_have_it(self):
+ self.assertTrue(form_of(self.list_body("loops")))
by_slug, _ = regions.collect_regions(self.records)
- self.assertGreaterEqual(len(by_slug["ca-on"]["records"]), home.FILTER_MIN)
self.assertTrue(form_of(regions.region_page("ca-on", self.records, SITE)[2]))
self.assertTrue(form_of(regions.group_page("central-canada", self.records, SITE)[2]))
self.assertTrue(form_of(regions.routes_page(self.records, SITE)[2]))
- def test_a_set_under_the_threshold_has_the_plain_rows(self):
- small = [k for k, recs in self.shown.items() if len(recs) < home.FILTER_MIN and k != "routes"]
- self.assertTrue(small)
+ def test_every_state_province_and_list_page_has_the_bar_however_few_trails(self):
+ by_slug, _ = regions.collect_regions(self.records)
+ small = [k for k, v in by_slug.items() if len(v["records"]) < 10]
+ self.assertGreater(len(small), 40)
for key in small:
- body = self.list_body(key)
- self.assertFalse(form_of(body), key)
- self.assertNotIn("data-finder", str(body), key)
+ body = regions.region_page(key, self.records, SITE)[2]
+ self.assertIn('id="finder-form"', str(body), key)
+ self.assertIn("data-finder", str(body), key)
+ small_lists = [k for k, recs in self.shown.items() if len(recs) < 10 and k != "routes"]
+ self.assertTrue(small_lists)
+ for key in small_lists:
+ self.assertTrue(form_of(self.list_body(key)), key)
+
+ def test_a_two_trail_page_offers_only_filters_that_narrow_it(self):
+ by_slug, _ = regions.collect_regions(self.records)
+ two = [k for k, v in by_slug.items() if len(v["records"]) == 2]
+ self.assertTrue(two)
+ for key in two:
+ form = form_of(regions.region_page(key, self.records, SITE)[2])
+ self.assertIn('name="q"', form, key)
+ for sel in re.findall(r"", form, re.S):
+ self.assertNotIn("", sel)
+ self.assertGreater(len(re.findall(r"
', body, re.S).group(1)
+ self.assertEqual(
+ re.sub(r"<[^>]+>", "", line),
+ "Browse by park, by mountain range or by wilderness area.")
+ for frag in ('href="/regions/#parks">park', 'href="/regions/#ranges">mountain range',
+ 'href="/regions/#wilderness">wilderness area'):
+ self.assertIn(frag, line)
+ # after the rows and the map, in the notes at the foot, never in the intro
+ self.assertGreater(body.index("finder__places"), body.rindex('
"), body.index("finder__places"))
+
+ def test_only_the_kinds_with_pages_and_none_when_there_are_none(self):
+ line = re.search(r'finder__places">(.*?)
', str(home.render(self.records, S, ROOT, place_kinds=["range"])), re.S).group(1)
+ self.assertEqual(re.sub(r"<[^>]+>", "", line), "Browse by mountain range.")
+ self.assertNotIn("finder__places", str(home.render(self.records, S, ROOT)))
+
+
class HubTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
From 742f5da4f11d20a39e3817d9e3e613ac2cf88722 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:51:50 -0700
Subject: [PATCH 21/30] Say in the changelog what the filter bar and the new
ways in to the place pages change for a visitor
---
CHANGELOG.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2adc7fe..122cb64 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## 2026-11-20 - The search box and filters on every page, and ways in to the places
+
+- Every page that lists trails now has the search box and the filters, however few trails it holds. Until now the 48 state and province pages with fewer than ten trails, the small lists and each route author's page showed the rows alone. The filters shown are the ones that have something to offer: a page with two trails offers the choices those two trails differ on, with the number that each choice leaves, and a page with one trail has the search box alone. Nothing is offered that would show no trails.
+- The Places page now begins with one row of links, visible at every screen size: States and provinces, Parks, Mountain ranges and Wilderness areas, each with its number of pages. They go to the parts of the page that were at the bottom, below sixty states and provinces.
+- The home page ends with a line under the rows and the map: Browse by park, by mountain range or by wilderness area, each going to its part of the Places page. The first screen is as it was.
+
## 2026-11-20 - Pages for national parks, mountain ranges and wilderness areas
- There are now 81 pages for named places: 21 national parks and other Park Service units (such as the Blue Ridge Parkway and Glen Canyon National Recreation Area), 36 mountain ranges and other named landforms (the Colorado Plateau and the Mogollon Rim are labelled and worded as what they are, "on the Colorado Plateau") and 24 wilderness areas, each with 3 or more trails. Every page has the search box and the filters that have something to offer, however few trails it holds, and every title keeps its count of trails. They answer searches such as "Wind River Range hikes" or "backpacking in Glacier National Park", and each has the same filter bar, trail rows and map as a state page. A place with fewer than 3 trails has no page: the Uinta Mountains have one. A range or wilderness area that holds exactly the trails of the park of the same name (Great Smoky Mountains, Olympic Mountains) has no page of its own either, and six places that were only another name for trails already on a neighbour's page are left out: the Longfellow Mountains, Finger Lakes, Gore Range, Mosquito Range, Great Western Divide and Russian Wilderness.
From f669a6695a41ff2b6c9dcf0f092d40abbe6f9455 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 13:54:27 -0700
Subject: [PATCH 22/30] Mark the places checklist's sub-steps with asterisks so
the audit document keeps the house wording the seasons check reads
---
docs/audit.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/docs/audit.md b/docs/audit.md
index e027715..aac36f3 100644
--- a/docs/audit.md
+++ b/docs/audit.md
@@ -17,11 +17,11 @@ down the list in order and stop at the first step that fails.
`python3 -m unittest discover -s web/tests` must both pass.
6. **Check the places.** `python3 tools/place_trails.py --check --refresh` downloads every outline again (without `--refresh` it reuses the files already in the cache, which are the ones first downloaded),
measures every track again and prints each difference from the records, one per line:
- - a place gained or lost by a trail: re-run `place_trails.py propose`, read the line, and
+ * a place gained or lost by a trail: re-run `place_trails.py propose`, read the line, and
apply it only when the new outline is right;
- - a boundary that moved (a new source version): the owner rules whether the new outline
+ * a boundary that moved (a new source version): the owner rules whether the new outline
replaces the old one;
- - a place that crossed the 3-trail line: its page appears or goes, so check its links and the
+ * a place that crossed the 3-trail line: its page appears or goes, so check its links and the
counts that name it.
The monthly workflow `.github/workflows/places.yml` runs this step by itself and fails with
the list; this step is the one you run when it has failed, and before a release.
From fc66f541a30943762863cb27a618eaa7a3627391 Mon Sep 17 00:00:00 2001
From: Stephen Waits
Date: Fri, 20 Nov 2026 14:08:34 -0700
Subject: [PATCH 23/30] Let a set with no trails build its filter bar, and pin
the Places page's new jump-link anchor in the state-pages golden file
In the golden file only the hash of /regions/ changed, by the anchor the jump row's first link goes to.
---
web/olt/home.py | 2 +-
web/tests/golden/state-pages.json | 2 +-
web/tests/test_filter_bar.py | 3 +++
3 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/web/olt/home.py b/web/olt/home.py
index 876a298..9b6ff48 100644
--- a/web/olt/home.py
+++ b/web/olt/home.py
@@ -336,7 +336,7 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
""")
- kms = [r["length_km"] for r in records]
+ kms = [r["length_km"] for r in records] or [0]
if any(min(kms) < n * words.KM_PER_MI <= max(kms) for n in steps):
first.append(f"""