From 2f4bc6862ec144376987a4b081465601c5dbaf7e Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 10:25:39 -0700 Subject: [PATCH] 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()