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()