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 <noreply@anthropic.com>
This commit is contained in:
1 parent
a2423e0ba5
commit
b2cdfc37cf
4 files changed
+1299
-29
No files matched your search
+703
-29
@@ -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
|
||||
<staging>/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())
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user