Merge seasons-ship-3 into nav-and-filters: the seasons ship and the places ship touched the same trail files; both sides kept
This commit is contained in:
commit
fd2e6fc6c7
122 files changed
+7437
-211
No files matched your search
@@ -0,0 +1,512 @@
|
||||
"""Tests for tools/estimate_season.py. The rule tests use hand-made
|
||||
normals, so they run with no network.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import 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(cold_c_min=5.0, heat_c_max=32.0)
|
||||
|
||||
|
||||
def normals(elev, tmax, snow=None):
|
||||
return C.PointNormals(lat=45.0, lon=-110.0, elev_m=float(elev),
|
||||
tmax_c=tuple(float(v) for v in tmax),
|
||||
snow_cm=None if snow is None
|
||||
else tuple(float(v) for v in snow))
|
||||
|
||||
|
||||
class RuleTest(unittest.TestCase):
|
||||
"""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])
|
||||
self.assertEqual(E.months_in_season([point], PARAMS),
|
||||
[4, 5, 6, 7, 8, 9, 10])
|
||||
|
||||
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])
|
||||
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) 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 is cold in June
|
||||
self.assertEqual(len(got), 11)
|
||||
|
||||
def test_a_wrapped_season_is_returned_sorted(self):
|
||||
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_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)
|
||||
self.assertEqual(E.months_in_season([coast], PARAMS), list(range(1, 13)))
|
||||
|
||||
def test_a_point_with_missing_data_makes_the_trail_unestimable(self):
|
||||
point = normals(20, [15] * 12)
|
||||
self.assertIsNone(E.months_in_season([point, None], PARAMS))
|
||||
self.assertIsNone(E.months_in_season([], PARAMS))
|
||||
|
||||
|
||||
class SamplePointsTest(unittest.TestCase):
|
||||
def make_root(self, td, parts=None, profile=None, multi=False):
|
||||
import json
|
||||
import tempfile # noqa: F401 (td is made by the caller)
|
||||
d = os.path.join(td, "trail-x")
|
||||
os.makedirs(os.path.join(td, "web"))
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(td, "web", "place-bounds.toml"), "w") as f:
|
||||
f.write('[box]\n"US-VT" = [-73.5, 42.7, -71.5, 45.0]\n')
|
||||
if parts is not None:
|
||||
if multi:
|
||||
geom = {"type": "MultiLineString", "coordinates": parts}
|
||||
else:
|
||||
geom = {"type": "LineString", "coordinates": parts[0]}
|
||||
doc = {"type": "FeatureCollection",
|
||||
"features": [{"type": "Feature", "geometry": geom}]}
|
||||
with open(os.path.join(d, "line.geojson"), "w") as f:
|
||||
json.dump(doc, f)
|
||||
if profile is not None:
|
||||
with open(os.path.join(d, "elevation.json"), "w") as f:
|
||||
json.dump({"profile": profile}, f)
|
||||
return td
|
||||
|
||||
@staticmethod
|
||||
def meridian(lat0, lat1, step=0.1, lon=-110.0):
|
||||
n = int(round((lat1 - lat0) / step))
|
||||
return [[lon, lat0 + i * step] for i in range(n + 1)]
|
||||
|
||||
def rec(self, **hike):
|
||||
base = {"summary": "x", "checked": "2026-01-01", "source": []}
|
||||
base.update(hike)
|
||||
return {"id": "trail-x", "country": "US", "regions": ["VT"],
|
||||
"source": {"line_file": "line.geojson"}, "hike": base}
|
||||
|
||||
def test_a_track_gives_points_spaced_along_it(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td, parts=[self.meridian(43.0, 44.8)],
|
||||
profile=[[0, 1000], [200, 1000]])
|
||||
points, kind = E.sample_points(root, self.rec())
|
||||
self.assertEqual(kind, "track")
|
||||
self.assertEqual(len(points), 5) # about 200 km, one per 50 km
|
||||
self.assertEqual(points[0].km, 0.0)
|
||||
self.assertAlmostEqual(points[0].lat, 43.0, places=3)
|
||||
self.assertLess(abs(points[-1].km - 200.15), 50)
|
||||
self.assertAlmostEqual(points[-1].lat, 44.8, places=3)
|
||||
|
||||
def test_a_short_track_still_gets_three_points(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td, parts=[self.meridian(43.0, 43.09, 0.03)],
|
||||
profile=[[0, 500], [10, 500]])
|
||||
points, kind = E.sample_points(root, self.rec())
|
||||
self.assertEqual(len(points), 3)
|
||||
|
||||
def test_a_very_long_track_is_capped_at_twelve(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td, parts=[self.meridian(35.0, 45.0, 0.5)],
|
||||
profile=[[0, 500], [1112, 500]])
|
||||
points, kind = E.sample_points(root, self.rec())
|
||||
self.assertEqual(len(points), 12)
|
||||
|
||||
def test_a_multipart_track_is_sampled_along_all_parts(self):
|
||||
import tempfile
|
||||
parts = [self.meridian(43.0, 43.9), self.meridian(44.1, 45.0)]
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td, parts=parts, multi=True,
|
||||
profile=[[0, 500], [200, 500]])
|
||||
points, kind = E.sample_points(root, self.rec())
|
||||
self.assertEqual(kind, "track")
|
||||
self.assertTrue(any(p.lat > 44.1 for p in points))
|
||||
self.assertTrue(any(p.lat < 43.9 for p in points))
|
||||
|
||||
def test_elevation_comes_from_the_profile_by_distance(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td, parts=[self.meridian(43.0, 44.8)],
|
||||
profile=[[0, 1000], [100, 2000], [200, 1500]])
|
||||
points, kind = E.sample_points(root, self.rec())
|
||||
middle = points[len(points) // 2]
|
||||
self.assertLess(abs(middle.elev_m - 2000), 30)
|
||||
self.assertLess(abs(points[0].elev_m - 1000), 30)
|
||||
|
||||
def test_a_track_without_a_profile_uses_the_high_point_for_the_top_only(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td, parts=[self.meridian(43.0, 44.8)])
|
||||
points, kind = E.sample_points(root, self.rec(high_point_m=3000))
|
||||
elevs = [p.elev_m for p in points]
|
||||
self.assertEqual(elevs.count(3000), 1)
|
||||
self.assertEqual(elevs.count(None), len(elevs) - 1)
|
||||
|
||||
def test_no_track_uses_the_two_ends(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td)
|
||||
points, kind = E.sample_points(
|
||||
root, self.rec(start_lonlat=[-110.0, 43.0],
|
||||
end_lonlat=[-109.0, 44.0]))
|
||||
self.assertEqual(kind, "ends")
|
||||
self.assertEqual(len(points), 2)
|
||||
self.assertEqual((points[0].lat, points[0].lon), (43.0, -110.0))
|
||||
self.assertEqual((points[1].lat, points[1].lon), (44.0, -109.0))
|
||||
|
||||
def test_no_track_and_no_ends_uses_the_place_centre(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = self.make_root(td)
|
||||
points, kind = E.sample_points(root, self.rec())
|
||||
self.assertEqual(kind, "place")
|
||||
self.assertEqual(len(points), 1)
|
||||
self.assertTrue(-73.5 <= points[0].lon <= -71.5)
|
||||
self.assertTrue(42.7 <= points[0].lat <= 45.0)
|
||||
self.assertAlmostEqual(points[0].lon, -72.5)
|
||||
self.assertAlmostEqual(points[0].lat, 43.85)
|
||||
|
||||
|
||||
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 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.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, "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_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))
|
||||
|
||||
|
||||
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):
|
||||
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_trails_are_listed_nearest_first(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=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, 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": 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)
|
||||
|
||||
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"])
|
||||
# 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, [
|
||||
("aaa", "Aaa", {"extra_hike": months_extra + self.ENDS}),
|
||||
])
|
||||
|
||||
EST = ('season = "All year"\n'
|
||||
'months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n'
|
||||
'season_basis = "estimate"\n'
|
||||
'season_method = "Judged from climate. Confidence: low."\n')
|
||||
|
||||
def blind_doc(self, root, share=0.77, tested=100):
|
||||
matched = int(round(share * tested))
|
||||
doc = {"date": "2026-11-20", "tested": tested, "matched": matched,
|
||||
"share": round(matched / tested, 2),
|
||||
"by_confidence": {
|
||||
"high": {"tested": tested, "matched": matched,
|
||||
"share": round(matched / tested, 2)},
|
||||
"medium": {"tested": 0, "matched": 0, "share": 0.0},
|
||||
"low": {"tested": 0, "matched": 0, "share": 0.0}}}
|
||||
with open(os.path.join(root, "tools", "season_blind_test.json"), "w") as f:
|
||||
json.dump(doc, f)
|
||||
|
||||
def record_inputs(self, root, tid="aaa", **change):
|
||||
params = E.load_params(root)
|
||||
rec = E.refresh.load_toml(os.path.join(root, tid, "trail.toml"))
|
||||
sig = E.inputs_signature(E.estimate(root, dict(rec, id=tid), params, mild_fetch,
|
||||
E.references(root, mild_fetch)))
|
||||
sig.update(change)
|
||||
with open(os.path.join(root, "tools", "season_inputs.json"), "w") as f:
|
||||
json.dump({tid: sig}, f)
|
||||
|
||||
def checked_repo(self, tmp, **kw):
|
||||
root = self.est_repo(tmp, self.EST)
|
||||
self.fit_doc(root)
|
||||
self.blind_doc(root, **kw)
|
||||
return root
|
||||
|
||||
def test_check_passes_when_nothing_changed(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.checked_repo(tmp)
|
||||
E._REFS.clear()
|
||||
self.record_inputs(root)
|
||||
ok, lines = E.check(root, mild_fetch)
|
||||
self.assertTrue(ok, lines)
|
||||
|
||||
def test_check_flags_an_estimate_whose_machine_estimate_changed(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.checked_repo(tmp)
|
||||
E._REFS.clear()
|
||||
self.record_inputs(root, machine=[6, 7])
|
||||
ok, lines = E.check(root, mild_fetch)
|
||||
self.assertFalse(ok)
|
||||
self.assertTrue(any("aaa" in line and "inputs changed" in line and "[6, 7]" in line
|
||||
for line in lines), lines)
|
||||
|
||||
def test_check_flags_an_estimate_whose_climate_digest_changed(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.checked_repo(tmp)
|
||||
E._REFS.clear()
|
||||
self.record_inputs(root, digest="0" * 16)
|
||||
ok, lines = E.check(root, mild_fetch)
|
||||
self.assertFalse(ok)
|
||||
self.assertTrue(any("aaa" in line and "inputs changed" in line for line in lines), lines)
|
||||
|
||||
def test_check_flags_an_estimate_with_no_recorded_inputs(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.checked_repo(tmp)
|
||||
E._REFS.clear()
|
||||
ok, lines = E.check(root, mild_fetch)
|
||||
self.assertFalse(ok)
|
||||
self.assertTrue(any("aaa" in line and "no inputs are recorded" in line for line in lines), lines)
|
||||
|
||||
def test_check_fails_when_the_blind_test_is_under_the_bar(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.checked_repo(tmp, share=0.6)
|
||||
E._REFS.clear()
|
||||
self.record_inputs(root)
|
||||
ok, lines = E.check(root, mild_fetch)
|
||||
self.assertFalse(ok)
|
||||
self.assertTrue(any("blind test" in line for line in lines), lines)
|
||||
|
||||
def test_check_fails_when_the_fit_got_worse(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
# 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, [("only", "Only", {"extra_hike": extra})])
|
||||
self.fit_doc(root, within1=4, n=4)
|
||||
self.blind_doc(root)
|
||||
E._REFS.clear()
|
||||
ok, lines = E.check(root, mild_fetch)
|
||||
self.assertFalse(ok)
|
||||
self.assertTrue(any("fit got worse" in line for line in lines), lines)
|
||||
|
||||
def test_the_estimates_command_lists_only_estimates(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.repo_with(tmp, [
|
||||
("aaa", "Aaa", {"extra_hike": self.EST + self.ENDS}),
|
||||
("bbb", "Bbb", {"extra_hike": 'season = "June"\nmonths = [6]\n'
|
||||
'season_basis = "source"\n' + self.ENDS}),
|
||||
])
|
||||
self.assertEqual(E.estimates(root), ["aaa"])
|
||||
|
||||
def test_a_season_with_a_method_is_not_a_sourced_season(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp, True)
|
||||
root = self.repo_with(tmp, [
|
||||
("aaa", "Aaa", {"extra_hike": 'season = "June"\nmonths = [6]\nseason_basis = "sources"\n'
|
||||
'season_method = "The pages differ. Confidence: low."\n' + self.ENDS}),
|
||||
])
|
||||
E._PHRASES.clear()
|
||||
self.assertEqual(E._phrases(root), {})
|
||||
|
||||
|
||||
class SeasonKindTest(unittest.TestCase):
|
||||
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")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Tests for the written audit checklist and the monthly season check.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import estimate_season as E # noqa: E402
|
||||
|
||||
ROOT = E.ROOT
|
||||
|
||||
|
||||
def read(*parts):
|
||||
with open(os.path.join(ROOT, *parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def section(text, heading):
|
||||
start = text.index(f"## {heading}")
|
||||
nxt = text.find("\n## ", start + 1)
|
||||
return text[start:nxt if nxt != -1 else len(text)]
|
||||
|
||||
|
||||
class AuditChecklistTest(unittest.TestCase):
|
||||
def test_the_audit_checklist_has_a_seasons_section_naming_both_steps(self):
|
||||
doc = read("docs", "audit.md")
|
||||
seasons = section(doc, "Seasons")
|
||||
self.assertIn("estimate_season.py check", seasons)
|
||||
self.assertIn("estimate_season.py estimates", seasons)
|
||||
self.assertIn("docs/season-research.md", seasons)
|
||||
self.assertIn("search afresh for a page that states the season", seasons.lower().replace("\n", " "))
|
||||
self.assertIn("re-run the machine estimate", seasons.lower())
|
||||
self.assertIn("1. ", seasons)
|
||||
self.assertIn("2. ", seasons)
|
||||
|
||||
def test_the_commands_it_names_exist(self):
|
||||
import contextlib
|
||||
import io
|
||||
import season_judge
|
||||
for module, subs in ((E, ("check", "estimates")), (season_judge, ("inputs", "packets", "score", "proposals"))):
|
||||
for sub in subs:
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), self.assertRaises(SystemExit) as stop:
|
||||
module.main([sub, "--help"])
|
||||
self.assertEqual(stop.exception.code, 0, sub)
|
||||
self.assertIn(f" {sub}", out.getvalue())
|
||||
|
||||
def test_the_estimates_command_prints_one_id_a_line(self):
|
||||
ids = E.estimates(ROOT)
|
||||
self.assertEqual(len(ids), 69)
|
||||
self.assertEqual(ids, sorted(ids))
|
||||
|
||||
def test_house_wording_in_the_audit_doc_and_workflow(self):
|
||||
dash = re.compile("[\u2013\u2014]")
|
||||
for rel in (("docs", "audit.md"), ("docs", "season-judging.md")):
|
||||
text = re.sub(r"`[^`]*`", "", read(*rel))
|
||||
self.assertIsNone(dash.search(text), rel)
|
||||
self.assertNotIn(" - ", text, rel)
|
||||
# in the workflow a dash is YAML's own, so only its comments are read
|
||||
comments = " ".join(l for l in read(".github", "workflows", "season-check.yml").splitlines()
|
||||
if l.lstrip().startswith("#"))
|
||||
self.assertIsNone(dash.search(comments))
|
||||
self.assertNotIn(" - ", comments)
|
||||
|
||||
|
||||
class MonthlyWorkflowTest(unittest.TestCase):
|
||||
def test_the_monthly_workflow_runs_the_check_on_a_schedule(self):
|
||||
text = read(".github", "workflows", "season-check.yml")
|
||||
for want in ("schedule", "workflow_dispatch", "estimate_season.py check", "cron:", "longhikes-climate"):
|
||||
self.assertIn(want, text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -20,6 +20,22 @@ def src(publisher, facts=("season", "months"), url="https://example.org/trail"):
|
||||
return {"url": url, "publisher": publisher, "facts": list(facts)}
|
||||
|
||||
|
||||
CLIMATE_URL = "https://www.chelsa-climate.org/datasets/chelsa_climatologies"
|
||||
CLIMATE = "WSL (CHELSA) and NOAA NCEI (ETOPO)"
|
||||
METHOD = "Snow clears from the high ground in June. Confidence: medium."
|
||||
|
||||
|
||||
def climate_src(**kw):
|
||||
return src(CLIMATE, url=CLIMATE_URL, **kw)
|
||||
|
||||
|
||||
def estimate(**fields):
|
||||
fields.setdefault("season_basis", "estimate")
|
||||
fields.setdefault("season_method", METHOD)
|
||||
fields.setdefault("source", [climate_src()])
|
||||
return check(**fields)
|
||||
|
||||
|
||||
def check(**fields):
|
||||
hike = {
|
||||
"season": "June to September",
|
||||
@@ -98,42 +114,102 @@ class SeasonBasisTest(unittest.TestCase):
|
||||
errors = check(source=[src("Park Service", facts=("days",))])
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_estimate_needs_a_method_and_refuses_one_otherwise(self):
|
||||
self.assertTrue(check(season_basis="estimate"))
|
||||
def test_an_estimate_with_a_method_and_a_climate_source_passes(self):
|
||||
self.assertEqual(estimate(), [])
|
||||
|
||||
def test_an_estimate_phrase_is_built_from_its_months(self):
|
||||
errors = estimate(season="Summer")
|
||||
self.assertTrue(any("built from" in e for e in errors), errors)
|
||||
self.assertEqual(check(season="Summer"), []) # a page's own words stand
|
||||
|
||||
def test_an_estimate_needs_a_method(self):
|
||||
errors = estimate(season_method=None)
|
||||
self.assertTrue(any("season_method" in e for e in errors), errors)
|
||||
self.assertTrue(estimate(season_method=""))
|
||||
self.assertTrue(estimate(season_method="x" * 401))
|
||||
|
||||
def test_an_estimate_method_ends_with_its_confidence(self):
|
||||
for word in ("high", "medium", "low"):
|
||||
self.assertEqual(estimate(season_method=f"Set by snow. Confidence: {word}."), [])
|
||||
errors = estimate(season_method="Set by snow.")
|
||||
self.assertTrue(any("Confidence" in e for e in errors), errors)
|
||||
self.assertTrue(estimate(season_method="Set by snow. Confidence: certain."))
|
||||
|
||||
def test_a_method_without_an_estimate_is_still_an_error_on_a_primary(self):
|
||||
self.assertTrue(check(season_method=METHOD))
|
||||
|
||||
def test_an_estimate_refuses_an_ordinary_page_naming_the_season(self):
|
||||
two = [climate_src(), src("Park Service", url="https://example.org/p")]
|
||||
errors = estimate(source=two)
|
||||
self.assertTrue(errors)
|
||||
only = [src("Park Service", url="https://example.org/p")]
|
||||
errors = estimate(source=only)
|
||||
self.assertTrue(any("climate" in e for e in errors), errors)
|
||||
|
||||
def test_an_estimate_with_no_naming_source_is_an_error(self):
|
||||
self.assertTrue(estimate(source=[climate_src(facts=("days",))]))
|
||||
|
||||
def test_an_estimate_source_names_both_season_and_months(self):
|
||||
errors = estimate(source=[climate_src(facts=("season",))])
|
||||
self.assertTrue(any("months" in e for e in errors), errors)
|
||||
|
||||
def test_a_sourced_season_may_not_cite_the_climate_data(self):
|
||||
errors = check(source=[climate_src()])
|
||||
self.assertTrue(any("climate" in e for e in errors), errors)
|
||||
|
||||
def test_the_climate_host_is_the_one_the_estimator_reads(self):
|
||||
import urllib.parse
|
||||
import season_climate
|
||||
self.assertEqual(
|
||||
check(season_basis="estimate", season_method="Estimated from climate normals."), [])
|
||||
self.assertTrue(check(season_basis="estimate", season_method=""))
|
||||
self.assertTrue(check(season_basis="estimate", season_method="x" * 401))
|
||||
self.assertTrue(check(season_method="Estimated from climate normals."))
|
||||
season.CLIMATE_HOSTS,
|
||||
frozenset({urllib.parse.urlparse(season_climate.SOURCE["url"]).hostname}))
|
||||
|
||||
def test_estimate_with_two_naming_sources_is_an_error(self):
|
||||
two = [src("Climate", url="https://c.example/1"), src("Other", url="https://o.example/1")]
|
||||
errors = check(season_basis="estimate", season_method="Estimated from climate.", source=two)
|
||||
def test_sources_judged_from_pages_that_differ_may_share_a_publisher(self):
|
||||
two = [src("The Trek", url="https://t.example/1"), src("The Trek", url="https://t.example/2")]
|
||||
errors = check(season_basis="sources", source=two)
|
||||
self.assertTrue(errors)
|
||||
self.assertEqual(
|
||||
check(season_basis="sources", source=two,
|
||||
season_method="The pages differ. Confidence: low."), [])
|
||||
|
||||
def test_judged_from_pages_that_differ_needs_a_page(self):
|
||||
errors = check(season_basis="sources", source=[src("The Trek", facts=("days",))],
|
||||
season_method="The pages differ. Confidence: low.")
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_estimate_with_no_naming_source_is_an_error(self):
|
||||
errors = check(season_basis="estimate", season_method="Estimated from climate.",
|
||||
source=[src("Climate", facts=("days",))])
|
||||
def test_a_season_read_from_a_page_has_no_method_and_no_estimate_basis(self):
|
||||
self.assertTrue(season.read_from_a_page({"season": "x", "season_basis": "primary"}))
|
||||
self.assertFalse(season.read_from_a_page({"season": "x", "season_basis": "estimate"}))
|
||||
self.assertFalse(season.read_from_a_page(
|
||||
{"season": "x", "season_basis": "sources", "season_method": "Judged."}))
|
||||
self.assertFalse(season.read_from_a_page({"season_basis": "primary"}))
|
||||
|
||||
def test_the_confidence_is_read_from_the_method(self):
|
||||
self.assertEqual(season.confidence_of("Set by snow. Confidence: low."), "low")
|
||||
self.assertEqual(season.confidence_of("Set by snow."), "")
|
||||
|
||||
def test_a_hike_without_season_is_an_error(self):
|
||||
errors = check(season=None, months=None, season_basis=None, source=None)
|
||||
self.assertTrue(any("season" in e for e in errors), errors)
|
||||
|
||||
def test_a_record_with_no_hike_is_an_error(self):
|
||||
errors = []
|
||||
season.check_present("t", {}, errors)
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_a_hike_without_season_passes_until_required(self):
|
||||
self.assertEqual(check(season=None, months=None, season_basis=None, source=None), [])
|
||||
|
||||
def test_required_flag_makes_it_an_error(self):
|
||||
with mock.patch.object(season, "SEASON_REQUIRED", True):
|
||||
errors = check(season=None, months=None, season_basis=None, source=None)
|
||||
self.assertTrue(any("season" in e for e in errors), errors)
|
||||
errors = []
|
||||
season.check_present("t", {"hike": {"season": "x"}}, errors)
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
def test_method_without_season_is_an_error(self):
|
||||
errors = check(season=None, months=None, season_basis=None, season_method="Some method.")
|
||||
self.assertTrue(errors)
|
||||
|
||||
def test_every_record_with_a_season_passes_the_validator(self):
|
||||
def test_every_record_passes_the_validator(self):
|
||||
errors = []
|
||||
for tid in refresh.trail_ids(V.ROOT):
|
||||
rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
|
||||
if (rec.get("hike") or {}).get("season"):
|
||||
V.check_hike(tid, rec, errors)
|
||||
V.check_hike(tid, rec, errors)
|
||||
season.check_present(tid, rec, errors)
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
def test_provenance_keys_need_no_source_fact(self):
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
"""Tests for tools/season_climate.py. All offline: an injected range
|
||||
getter serves small synthetic GeoTIFFs laid out like CHELSA's (LZW with
|
||||
a horizontal predictor, 16 bit) and ETOPO's (deflate with the floating
|
||||
point predictor).
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zlib
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import season_climate as C # noqa: E402
|
||||
import validate as V # noqa: E402
|
||||
|
||||
W = H = 8
|
||||
TW = TH = 4
|
||||
X0, Y0, RES = -120.0, 40.0, 0.5
|
||||
|
||||
|
||||
def lzw_encode(data):
|
||||
"""A plain TIFF LZW encoder for short inputs (9 bit codes only)."""
|
||||
table = {bytes([i]): i for i in range(256)}
|
||||
nxt = 258
|
||||
codes = [256]
|
||||
cur = b""
|
||||
for byte in data:
|
||||
nb = cur + bytes([byte])
|
||||
if nb in table:
|
||||
cur = nb
|
||||
else:
|
||||
codes.append(table[cur])
|
||||
table[nb] = nxt
|
||||
nxt += 1
|
||||
cur = bytes([byte])
|
||||
if cur:
|
||||
codes.append(table[cur])
|
||||
codes.append(257)
|
||||
assert nxt < 500
|
||||
bits = "".join(format(c, "09b") for c in codes)
|
||||
bits += "0" * (-len(bits) % 8)
|
||||
return bytes(int(bits[i:i + 8], 2) for i in range(0, len(bits), 8))
|
||||
|
||||
|
||||
def build_tiff(tiles, compression, predictor, bits, sampleformat, meta="", nodata=None):
|
||||
"""Classic little-endian TIFF, W x H in TW x TH tiles."""
|
||||
entries = []
|
||||
extra = bytearray()
|
||||
base = 8 + 2 + 20 * 12 + 4 # room for up to 20 entries
|
||||
|
||||
def short(tag, v):
|
||||
entries.append((tag, 3, 1, struct.pack("<HH", v, 0)))
|
||||
|
||||
def blob(tag, typ, count, payload):
|
||||
off = base + len(extra)
|
||||
extra.extend(payload)
|
||||
entries.append((tag, typ, count, struct.pack("<I", off)))
|
||||
|
||||
short(256, W)
|
||||
short(257, H)
|
||||
short(258, bits)
|
||||
short(259, compression)
|
||||
short(277, 1)
|
||||
if predictor != 1:
|
||||
short(317, predictor)
|
||||
short(322, TW)
|
||||
short(323, TH)
|
||||
short(339, sampleformat)
|
||||
blob(33550, 12, 3, struct.pack("<3d", RES, RES, 0.0))
|
||||
blob(33922, 12, 6, struct.pack("<6d", 0, 0, 0, X0, Y0, 0))
|
||||
if meta:
|
||||
text = meta.encode() + b"\x00"
|
||||
blob(42112, 2, len(text), text)
|
||||
if nodata is not None:
|
||||
text = str(nodata).encode() + b"\x00"
|
||||
blob(42113, 2, len(text), text)
|
||||
# tile offsets and byte counts come after everything else
|
||||
n = len(tiles)
|
||||
tile_base = base + len(extra) + 8 * n
|
||||
offs, pos = [], tile_base
|
||||
for t in tiles:
|
||||
offs.append(pos)
|
||||
pos += len(t)
|
||||
blob(324, 4, n, struct.pack("<%dI" % n, *offs))
|
||||
blob(325, 4, n, struct.pack("<%dI" % n, *[len(t) for t in tiles]))
|
||||
entries.sort()
|
||||
ifd = struct.pack("<H", len(entries))
|
||||
for tag, typ, count, val in entries:
|
||||
ifd += struct.pack("<HHI", tag, typ, count) + val
|
||||
ifd += struct.pack("<I", 0)
|
||||
head = b"II*\x00" + struct.pack("<I", 8) + ifd
|
||||
head += b"\x00" * (base - len(head))
|
||||
return head + bytes(extra) + b"".join(tiles)
|
||||
|
||||
|
||||
def tiles_of(values, encode):
|
||||
"""Cut a W x H grid into tiles (row-major tile order) and encode."""
|
||||
out = []
|
||||
for ty in range(H // TH):
|
||||
for tx in range(W // TW):
|
||||
rows = [values[(ty * TH + r) * W + tx * TW: (ty * TH + r) * W + tx * TW + TW]
|
||||
for r in range(TH)]
|
||||
out.append(encode(rows))
|
||||
return out
|
||||
|
||||
|
||||
def encode_u16(rows):
|
||||
"""Horizontal predictor, then LZW."""
|
||||
raw = b""
|
||||
for row in rows:
|
||||
prev = 0
|
||||
for v in row:
|
||||
raw += struct.pack("<H", (v - prev) & 0xFFFF)
|
||||
prev = v
|
||||
return lzw_encode(raw)
|
||||
|
||||
|
||||
def encode_float(rows):
|
||||
"""Floating point predictor, then deflate."""
|
||||
raw = b""
|
||||
for row in rows:
|
||||
be = b"".join(struct.pack(">f", v) for v in row)
|
||||
planar = bytes(be[j * 4 + k] for k in range(4) for j in range(len(row)))
|
||||
diff = bytearray(len(planar))
|
||||
prev = 0
|
||||
for i, b in enumerate(planar):
|
||||
diff[i] = (b - prev) & 255
|
||||
prev = b
|
||||
raw += bytes(diff)
|
||||
return zlib.compress(raw)
|
||||
|
||||
|
||||
def month_file(month, nodata_at=None):
|
||||
"""Kelvin times ten, one value per cell: 280 K plus the month plus
|
||||
the column, so every cell and month is distinguishable."""
|
||||
vals = [int((280.0 + month + (i % W) * 0.1) * 10) for i in range(W * H)]
|
||||
if nodata_at is not None:
|
||||
vals[nodata_at] = 65535
|
||||
meta = ('<GDALMetadata><Item name="OFFSET" sample="0" role="offset">0</Item>'
|
||||
'<Item name="SCALE" sample="0" role="scale">0.1</Item></GDALMetadata>')
|
||||
return build_tiff(tiles_of(vals, encode_u16), 5, 2, 16, 1, meta,
|
||||
nodata=65535 if nodata_at is not None else None)
|
||||
|
||||
|
||||
def dem_file(elev=1000.0):
|
||||
vals = [elev] * (W * H)
|
||||
return build_tiff(tiles_of(vals, encode_float), 8, 3, 32, 3, nodata=-99999)
|
||||
|
||||
|
||||
class Getter:
|
||||
def __init__(self, nodata_at=None, elev=1000.0):
|
||||
self.calls = []
|
||||
self.files = {}
|
||||
for m in range(1, 13):
|
||||
self.files[C.CHELSA_URL.format(month=m)] = month_file(
|
||||
m, nodata_at if m == 1 else nodata_at)
|
||||
self.files[C.ETOPO_URL] = dem_file(elev)
|
||||
|
||||
def __call__(self, url, start, end):
|
||||
self.calls.append((url, start, end))
|
||||
return self.files[url][start:end + 1]
|
||||
|
||||
|
||||
class ReaderTest(unittest.TestCase):
|
||||
def test_lzw_round_trips_repeats(self):
|
||||
data = b"ABABABABCCCCCCDDDDABAB" * 5
|
||||
self.assertEqual(C.lzw_decode(lzw_encode(data)), data)
|
||||
|
||||
def test_a_chelsa_style_tile_is_read_with_its_predictor_and_scale(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
src = C.Source(C.CHELSA_URL.format(month=3), cache, Getter())
|
||||
raw = src.pixel(2, 2)
|
||||
self.assertEqual(raw, int((283.0 + 0.2) * 10))
|
||||
self.assertAlmostEqual(src.value_nearest(-119.0, 39.0), 283.2, places=1)
|
||||
|
||||
def test_an_etopo_style_float_tile_is_read(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
src = C.Source(C.ETOPO_URL, cache, Getter(elev=1234.5))
|
||||
self.assertAlmostEqual(src.value_bilinear(-119.1, 39.2), 1234.5, places=1)
|
||||
|
||||
|
||||
class NormalsTest(unittest.TestCase):
|
||||
def test_a_point_becomes_twelve_celsius_values_at_the_cell_elevation(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
n = C.fetch_normals(39.0, -119.0, None, cache=cache, getter=Getter())
|
||||
self.assertEqual(len(n.tmax_c), 12)
|
||||
self.assertEqual(n.elev_m, 1000.0)
|
||||
self.assertIsNone(n.snow_cm)
|
||||
self.assertAlmostEqual(n.tmax_c[0], 281.0 + 0.2 - 273.15, places=1)
|
||||
|
||||
def test_values_are_corrected_by_the_lapse_rate_to_the_asked_elevation(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
g = Getter()
|
||||
cell = C.fetch_normals(39.0, -119.0, None, cache=cache, getter=g)
|
||||
up = C.fetch_normals(39.0, -119.0, 2000, cache=cache, getter=g)
|
||||
self.assertEqual(up.elev_m, 2000.0)
|
||||
self.assertAlmostEqual(cell.tmax_c[6] - up.tmax_c[6], 6.5, places=1)
|
||||
|
||||
def test_a_second_call_reads_the_cache_not_the_network(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
g = Getter()
|
||||
C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=g)
|
||||
first = len(g.calls)
|
||||
self.assertGreater(first, 0)
|
||||
C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=g)
|
||||
self.assertEqual(len(g.calls), first)
|
||||
|
||||
def test_a_new_getter_still_reads_cached_tiles(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=Getter())
|
||||
g2 = Getter()
|
||||
C.fetch_normals(39.2, -119.0, 1500, cache=cache, getter=g2)
|
||||
# a different point in the same tiles: no tile range is asked again
|
||||
tile_asks = [c for c in g2.calls if c[1] != 0]
|
||||
self.assertEqual(tile_asks, [])
|
||||
|
||||
def test_a_point_with_no_data_returns_none_not_zeros(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
# every cell of every month file is nodata
|
||||
g = Getter()
|
||||
for m in range(1, 13):
|
||||
url = C.CHELSA_URL.format(month=m)
|
||||
vals = [65535] * (W * H)
|
||||
meta = ('<GDALMetadata><Item name="SCALE" role="scale">0.1</Item>'
|
||||
'</GDALMetadata>')
|
||||
g.files[url] = build_tiff(tiles_of(vals, encode_u16), 5, 2, 16, 1,
|
||||
meta, nodata=65535)
|
||||
self.assertIsNone(C.fetch_normals(39.0, -119.0, 1500, cache=cache, getter=g))
|
||||
|
||||
def test_a_sea_cell_borrows_the_nearest_land_cell(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
# cell (2, 2) is sea in every month; (3, 2) is land
|
||||
g = Getter(nodata_at=2 * W + 2)
|
||||
n = C.fetch_normals(39.0, -119.0, None, cache=cache, getter=g)
|
||||
self.assertIsNotNone(n)
|
||||
|
||||
def test_a_point_outside_the_grid_has_no_data(self):
|
||||
with tempfile.TemporaryDirectory() as cache:
|
||||
self.assertIsNone(C.fetch_normals(80.0, -119.0, 100, cache=cache, getter=Getter()))
|
||||
|
||||
|
||||
class SourceTest(unittest.TestCase):
|
||||
def test_the_cache_is_outside_the_repository(self):
|
||||
self.assertFalse(os.path.abspath(C.CACHE_DIR).startswith(os.path.abspath(V.ROOT)))
|
||||
|
||||
def test_the_source_says_its_licence_and_period(self):
|
||||
for key in ("name", "publisher", "url", "licence", "period"):
|
||||
self.assertIn(key, C.SOURCE)
|
||||
self.assertTrue(str(C.SOURCE[key]).strip())
|
||||
self.assertIn("CC0", C.SOURCE["licence"])
|
||||
self.assertEqual(C.SOURCE["period"], "1981-2010")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""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", "loo", "bar", "passes", "confidence"):
|
||||
self.assertIn(key, fit)
|
||||
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["loo"], fit["bar"]))
|
||||
|
||||
def test_estimates_only_over_the_bar_by_the_blind_test(self):
|
||||
"""The machine estimate on its own is under the bar and is never
|
||||
written to a record. Estimated seasons are judged, and the judged
|
||||
method must pass the bar in its blind test."""
|
||||
estimated = []
|
||||
for tid in refresh.trail_ids(V.ROOT):
|
||||
rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
|
||||
if (rec.get("hike") or {}).get("season_basis") == "estimate":
|
||||
estimated.append(tid)
|
||||
if not estimated:
|
||||
self.skipTest("no estimated seasons on file yet")
|
||||
import season_judge
|
||||
blind = season_judge.load_blind_test()
|
||||
self.assertEqual(season_judge.check_blind_test(blind), [])
|
||||
self.assertGreaterEqual(blind["share"], E.BAR["within1_min"])
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Tests for the shared season helpers in tools/season.py.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import season # noqa: E402
|
||||
|
||||
|
||||
class SpanTest(unittest.TestCase):
|
||||
def test_span_wraps_the_year(self):
|
||||
self.assertEqual(season.span([11, 12, 1, 2, 3]), (11, 3))
|
||||
|
||||
def test_span_of_two_windows_covers_both(self):
|
||||
self.assertEqual(season.span([4, 5, 9, 10]), (4, 10))
|
||||
|
||||
def test_span_of_one_month(self):
|
||||
self.assertEqual(season.span([7]), (7, 7))
|
||||
|
||||
def test_span_of_all_year(self):
|
||||
self.assertEqual(season.span(list(range(1, 13))), (1, 12))
|
||||
|
||||
def test_span_is_order_independent(self):
|
||||
self.assertEqual(season.span([3, 1, 12, 2, 11]), (11, 3))
|
||||
|
||||
|
||||
class GradeTest(unittest.TestCase):
|
||||
def test_grade_exact(self):
|
||||
self.assertEqual(season.grade([6, 7, 8, 9], [6, 7, 8, 9]), "exact")
|
||||
self.assertEqual(season.grade([11, 12, 1, 2], [11, 12, 1, 2]), "exact")
|
||||
|
||||
def test_grade_within_one_at_each_end(self):
|
||||
self.assertEqual(season.grade([5, 6, 7, 8, 9], [6, 7, 8]), "within1")
|
||||
|
||||
def test_grade_worse(self):
|
||||
self.assertEqual(season.grade([6, 7], [9, 10]), "worse")
|
||||
|
||||
def test_grade_across_the_year_end(self):
|
||||
self.assertEqual(season.grade([12, 1, 2], [1, 2, 3]), "within1")
|
||||
|
||||
def test_grade_two_months_off_at_one_end_is_worse(self):
|
||||
self.assertEqual(season.grade([4, 5, 6, 7, 8], [6, 7, 8]), "worse")
|
||||
|
||||
|
||||
class PhraseTest(unittest.TestCase):
|
||||
def test_phrase_runs(self):
|
||||
self.assertEqual(season.phrase_for([6, 7, 8, 9]), "June to September")
|
||||
self.assertEqual(season.phrase_for([11, 12, 1, 2, 3]), "November to March")
|
||||
self.assertEqual(season.phrase_for([4, 5, 9, 10]),
|
||||
"April to May and September to October")
|
||||
self.assertEqual(season.phrase_for([3, 4, 5, 10, 11]),
|
||||
"March to May and October to November")
|
||||
self.assertEqual(season.phrase_for([11, 12, 1, 2, 6, 7, 8]),
|
||||
"November to February and June to August")
|
||||
self.assertEqual(season.phrase_for([7]), "July")
|
||||
self.assertEqual(season.phrase_for(list(range(1, 13))), "All year")
|
||||
|
||||
def test_phrase_two_month_run(self):
|
||||
self.assertEqual(season.phrase_for([7, 8]), "July to August")
|
||||
self.assertEqual(season.phrase_for([12, 1]), "December to January")
|
||||
|
||||
|
||||
class MethodSentenceTest(unittest.TestCase):
|
||||
def test_method_sentence_names_dataset_period_and_points(self):
|
||||
text = season.method_sentence("ERA5-Land via Open-Meteo", "2011-2020", 5, "track", 1)
|
||||
self.assertIn("ERA5-Land via Open-Meteo", text)
|
||||
self.assertIn("2011-2020", text)
|
||||
self.assertIn("5", text)
|
||||
self.assertTrue(text.endswith("."))
|
||||
self.assertLess(len(text), 400)
|
||||
|
||||
def test_method_sentence_for_each_kind(self):
|
||||
for kind in ("track", "ends", "place"):
|
||||
text = season.method_sentence("Dataset", "2011-2020", 1, kind, 1)
|
||||
self.assertIn("Dataset", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,290 @@
|
||||
"""Tests for tools/season_judge.py: the packets reviewers judge a season from,
|
||||
the blind scoring, and the proposals that write the judged seasons.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import season_judge as J # noqa: E402
|
||||
import season_climate as C # noqa: E402
|
||||
import season_model as M # noqa: E402
|
||||
import estimate_season as E # noqa: E402
|
||||
import test_refresh as TR # noqa: E402
|
||||
import refresh as R # noqa: E402
|
||||
import trail_history # noqa: E402
|
||||
import validate as V # noqa: E402
|
||||
|
||||
|
||||
class CleanTest(unittest.TestCase):
|
||||
def test_a_sentence_that_bears_on_timing_is_removed_and_logged(self):
|
||||
kept, removed = J.clean("A pretty ridge walk. Best in July and August. It has huts.")
|
||||
self.assertEqual(kept, "A pretty ridge walk. It has huts.")
|
||||
self.assertEqual(removed, ["Best in July and August."])
|
||||
|
||||
def test_season_words_count_but_place_names_do_not(self):
|
||||
self.assertTrue(J.mentions_season("Snowmelt comes late."))
|
||||
self.assertTrue(J.mentions_season("Open year-round."))
|
||||
self.assertFalse(J.mentions_season("It crosses May Lake and Summer Lake."))
|
||||
self.assertFalse(J.mentions_season("It passes the Hot Springs."))
|
||||
|
||||
def test_nothing_left_is_said_so(self):
|
||||
kept, _ = J.clean("Best in summer.")
|
||||
self.assertEqual(kept, "")
|
||||
self.assertIn("none left", J.shown(kept, "x"))
|
||||
self.assertEqual(J.shown("", None), "(not on file)")
|
||||
|
||||
|
||||
class SplitTest(unittest.TestCase):
|
||||
def test_parts_are_disjoint_balanced_and_repeatable(self):
|
||||
src = [f"s{i}" for i in range(10)]
|
||||
oth = [f"o{i}" for i in range(7)]
|
||||
parts = J.split_parts(src, oth, 3, 1)
|
||||
flat = [t for p in parts for t in p]
|
||||
self.assertEqual(sorted(flat), sorted(src + oth))
|
||||
for part in parts:
|
||||
self.assertIn(sum(t in src for t in part), (3, 4))
|
||||
self.assertIn(sum(t in oth for t in part), (2, 3))
|
||||
self.assertEqual(parts, J.split_parts(src, oth, 3, 1))
|
||||
self.assertNotEqual(parts, J.split_parts(src, oth, 3, 2))
|
||||
|
||||
|
||||
def med(base):
|
||||
return ([base] * 12, [base] * 12)
|
||||
|
||||
|
||||
class ComparablesTest(unittest.TestCase):
|
||||
def test_a_trail_is_never_compared_with_its_own_part_or_itself(self):
|
||||
part_of = {"me": 0, "mate": 0, "a": 1, "b": 2}
|
||||
meds = {k: med(10.0) for k in part_of}
|
||||
centres = {k: (45.0, -110.0) for k in part_of}
|
||||
got = J.comparables("me", part_of, ["mate", "a", "b", "me"], meds, centres, k=10)
|
||||
self.assertEqual(sorted(got), ["a", "b"])
|
||||
|
||||
def test_the_nearest_in_climate_and_place_come_first(self):
|
||||
part_of = {"me": 0, "near": 1, "far": 1, "cold": 2}
|
||||
meds = {"me": med(10.0), "near": med(10.0), "far": med(10.0), "cold": med(-5.0)}
|
||||
centres = {"me": (45.0, -110.0), "near": (45.5, -110.0),
|
||||
"far": (30.0, -80.0), "cold": (45.1, -110.0)}
|
||||
got = J.comparables("me", part_of, ["near", "far", "cold"], meds, centres, k=2)
|
||||
self.assertEqual(got, ["near", "far"])
|
||||
|
||||
|
||||
def info(kind="track"):
|
||||
pts = [C.PointNormals(lat=44.0 + i, lon=-110.0, elev_m=1000.0 * (i + 1),
|
||||
tmax_c=tuple(float(v) for v in range(12)))
|
||||
for i in range(4)]
|
||||
return {"points": pts, "kind": kind, "profile": (3500.0, 800.0)}
|
||||
|
||||
|
||||
class PacketTest(unittest.TestCase):
|
||||
def rec(self):
|
||||
return {"id": "tt", "name": "Test Trail", "country": "US", "regions": ["WY"],
|
||||
"length_km": 160.9344, "kind": "trail",
|
||||
"hike": {"summary": "A ridge walk. Best in July. It has huts.",
|
||||
"start": "Trailhead.", "terrain": ["alpine"], "high_point_m": 3000,
|
||||
"days": [8, 10]}}
|
||||
|
||||
def text(self, **kw):
|
||||
args = dict(rec=self.rec(), info=info(), machine=[6, 7, 8],
|
||||
comparables=[], pages=None, precip=None)
|
||||
args.update(kw)
|
||||
return J.packet_text(**args)
|
||||
|
||||
def test_the_packet_states_the_trail_in_miles_and_feet_and_hides_timing(self):
|
||||
t = self.text()
|
||||
self.assertIn("length: 100 miles", t)
|
||||
self.assertIn("high point: 9843 ft", t)
|
||||
self.assertIn("A ridge walk. It has huts.", t)
|
||||
self.assertNotIn("Best in July", t)
|
||||
|
||||
def test_it_never_carries_the_trails_own_season(self):
|
||||
rec = self.rec()
|
||||
rec["hike"].update(season="July to September", months=[7, 8, 9], season_basis="primary")
|
||||
t = self.text(rec=rec)
|
||||
self.assertNotIn("July to September", t)
|
||||
|
||||
def test_it_gives_the_machine_estimate_and_the_climate(self):
|
||||
t = self.text()
|
||||
self.assertIn("Months: 6, 7, 8 (June, July, August)", t)
|
||||
self.assertIn("| Jan |", t)
|
||||
self.assertIn("Precipitation is not available", t)
|
||||
|
||||
def test_precipitation_is_given_when_supplied(self):
|
||||
t = self.text(precip=[[25.4] * 12] * 4)
|
||||
self.assertIn("precip in", t)
|
||||
self.assertNotIn("Precipitation is not available", t)
|
||||
|
||||
def test_what_pages_say_appears_only_when_given(self):
|
||||
self.assertNotIn("What pages say", self.text())
|
||||
self.assertIn("Months each gives: A 5-10", self.text(pages="Publisher(s): A\nMonths each gives: A 5-10"))
|
||||
|
||||
def test_a_trail_with_no_climate_says_so(self):
|
||||
t = self.text(info=dict(info(), points=[]), machine=[])
|
||||
self.assertIn("No climate data is available", t)
|
||||
self.assertIn("Months: none", t)
|
||||
|
||||
|
||||
class AnswersTest(unittest.TestCase):
|
||||
def write(self, text):
|
||||
d = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, d, True)
|
||||
path = os.path.join(d, "a.tsv")
|
||||
with open(path, "w") as f:
|
||||
f.write(text)
|
||||
return path
|
||||
|
||||
def test_good_rows_are_read_and_bad_rows_are_named(self):
|
||||
path = self.write(
|
||||
"aa\t7,8,9\tJuly to September\thigh\tSnow melts.\n"
|
||||
"bb\t\tNone\thigh\tEmpty.\n"
|
||||
"cc\t13\tX\thigh\tOut of range.\n"
|
||||
"dd\t6\tJune\tsure\tBad confidence.\n"
|
||||
"aa\t6\tJune\tlow\tDuplicate.\n"
|
||||
"zz\t6\tJune\tlow\tUnknown.\n"
|
||||
"ee\t5,6\tMay to June\tmedium\tFine.\n")
|
||||
ans, problems = J.read_answers(path, ["aa", "bb", "cc", "dd", "ee"])
|
||||
self.assertEqual(sorted(ans), ["aa", "ee"])
|
||||
self.assertEqual(ans["aa"], ([7, 8, 9], "July to September", "high", "Snow melts."))
|
||||
self.assertEqual(len(problems), 5)
|
||||
|
||||
|
||||
class ScoreTest(unittest.TestCase):
|
||||
def test_matches_are_counted_within_a_month_at_each_end_by_confidence(self):
|
||||
truth = {"a": [6, 7, 8, 9], "b": [6, 7, 8, 9], "c": [6, 7, 8, 9], "d": [1, 2, 3]}
|
||||
ans = {"a": ([6, 7, 8, 9], "", "high", ""), # exact
|
||||
"b": ([7, 8, 9, 10], "", "medium", ""), # one month at each end
|
||||
"c": ([1, 2, 3], "", "low", ""), # wrong
|
||||
"x": ([1], "", "high", "")} # not a sourced trail: ignored
|
||||
got = J.score(ans, truth)
|
||||
self.assertEqual(got["tested"], 4)
|
||||
self.assertEqual(got["matched"], 2)
|
||||
self.assertEqual(got["by_confidence"]["high"], {"tested": 1, "matched": 1})
|
||||
self.assertEqual(got["by_confidence"]["medium"], {"tested": 1, "matched": 1})
|
||||
self.assertEqual(got["by_confidence"]["low"], {"tested": 1, "matched": 0})
|
||||
# d was never answered: it counts as tested and missed
|
||||
self.assertEqual(got["unanswered"], 1)
|
||||
|
||||
def test_the_figure_file_round_trips_and_shares_are_computed(self):
|
||||
figures = {"tested": 148, "matched": 114, "unanswered": 0,
|
||||
"by_confidence": {"high": {"tested": 52, "matched": 48},
|
||||
"medium": {"tested": 76, "matched": 55},
|
||||
"low": {"tested": 20, "matched": 11}}}
|
||||
d = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, d, True)
|
||||
path = os.path.join(d, "t.json")
|
||||
J.write_blind_test(path, figures, "2026-11-20")
|
||||
got = J.load_blind_test(path)
|
||||
self.assertEqual(got["date"], "2026-11-20")
|
||||
self.assertEqual(got["tested"], 148)
|
||||
self.assertEqual(got["matched"], 114)
|
||||
self.assertEqual(got["share"], 0.77)
|
||||
self.assertEqual(got["by_confidence"]["high"]["share"], 0.92)
|
||||
self.assertEqual(got["by_confidence"]["low"]["share"], 0.55)
|
||||
|
||||
def test_a_loaded_file_must_add_up(self):
|
||||
bad = {"date": "2026-11-20", "tested": 10, "matched": 5, "share": 0.5,
|
||||
"by_confidence": {"high": {"tested": 4, "matched": 5, "share": 1.0},
|
||||
"medium": {"tested": 3, "matched": 1, "share": 0.33},
|
||||
"low": {"tested": 3, "matched": 1, "share": 0.33}}}
|
||||
self.assertTrue(J.check_blind_test(bad))
|
||||
|
||||
|
||||
class CommittedFilesTest(unittest.TestCase):
|
||||
def test_the_committed_blind_test_adds_up_and_passes_the_bar(self):
|
||||
got = J.load_blind_test(os.path.join(J.ROOT, "tools", "season_blind_test.json"))
|
||||
self.assertEqual(J.check_blind_test(got), [])
|
||||
self.assertGreaterEqual(got["share"], E.BAR["within1_min"])
|
||||
|
||||
def test_every_judged_row_is_well_formed_and_matches_its_record(self):
|
||||
ids = R.trail_ids(J.ROOT)
|
||||
ans, problems = J.read_answers(os.path.join(J.ROOT, "tools", "season_judged.tsv"), ids)
|
||||
self.assertEqual(problems, [])
|
||||
self.assertEqual(sorted(ans), sorted(ids))
|
||||
for tid in ids:
|
||||
hike = R.load_toml(os.path.join(J.ROOT, tid, "trail.toml")).get("hike") or {}
|
||||
if hike.get("season_basis") == "estimate" or hike.get("season_method"):
|
||||
months, _phrase, conf, _why = ans[tid]
|
||||
self.assertEqual(months, hike["months"], tid)
|
||||
self.assertEqual(J.season.confidence_of(hike["season_method"]), conf, tid)
|
||||
|
||||
|
||||
class ProposalsTest(unittest.TestCase):
|
||||
HIKE = 'start_lonlat = [-110.0, 43.0]\nend_lonlat = [-110.0, 43.2]\n'
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.root = TR.make_repo(self.tmp, trails=[
|
||||
("aaa", "Aaa", {"extra_hike": self.HIKE}),
|
||||
("bbb", "Bbb", {"extra_hike": self.HIKE}),
|
||||
("ccc", "Ccc", {"extra_hike": 'season = "June"\nmonths = [6]\nseason_basis = "source"\n' + self.HIKE}),
|
||||
])
|
||||
self.stage = os.path.join(self.tmp, "stage")
|
||||
os.makedirs(self.stage)
|
||||
self.answers = os.path.join(self.tmp, "judged.tsv")
|
||||
with open(self.answers, "w") as f:
|
||||
f.write("aaa\t7,8,9\tJuly to September\thigh\tSnow melts late.\n"
|
||||
"bbb\t5,6,7,8,9,10\tMay to October\tmedium\tThe pages differ.\n"
|
||||
"ccc\t1,2\tJanuary to February\tlow\tNot used: it has a season.\n")
|
||||
self.pages = os.path.join(self.tmp, "pages.json")
|
||||
with open(self.pages, "w") as f:
|
||||
json.dump({"bbb": {
|
||||
"why": "The pages differ: one says May to September and one says June to October. "
|
||||
"It was set by judgement from both and from the climate.",
|
||||
"sources": [
|
||||
{"url": "https://a.example/bbb", "publisher": "Guide A", "quote": "Season: May to September"},
|
||||
{"url": "https://b.example/bbb", "publisher": "Guide B", "quote": "Season: June to October"}]}}, f)
|
||||
|
||||
def test_only_trails_with_no_season_are_staged(self):
|
||||
n = J.proposals(self.root, self.answers, self.pages, self.stage)
|
||||
self.assertEqual(n, 2)
|
||||
|
||||
def test_collect_and_apply_write_valid_records_with_history(self):
|
||||
J.proposals(self.root, self.answers, self.pages, self.stage)
|
||||
code, out = TR.main(self.root, "--dir", self.stage, "collect")
|
||||
self.assertEqual(code, 0, out)
|
||||
coll = R.load_toml(os.path.join(self.stage, "collected.toml"))
|
||||
self.assertEqual({p["status"] for p in coll["proposal"]}, {"proposed"}, out)
|
||||
with open(os.path.join(self.stage, "owner.csv"), "w") as f:
|
||||
f.write("pid,decision,digest\n")
|
||||
for p in coll["proposal"]:
|
||||
f.write(f"{p['pid']},accept,{p['digest']}\n")
|
||||
code, out = TR.main(self.root, "--dir", self.stage, "collect")
|
||||
self.assertEqual(code, 0, out)
|
||||
code, out = TR.main(self.root, "--dir", self.stage, "apply")
|
||||
self.assertEqual(code, 0, out)
|
||||
a = R.load_toml(os.path.join(self.root, "aaa", "trail.toml"))
|
||||
h = a["hike"]
|
||||
self.assertEqual((h["season"], h["months"], h["season_basis"]),
|
||||
("July to September", [7, 8, 9], "estimate"))
|
||||
self.assertTrue(h["season_method"].endswith("Confidence: high."))
|
||||
self.assertIn("Snow melts late.", h["season_method"])
|
||||
self.assertEqual(len(h["source"]), 3) # two the record had, and the climate data
|
||||
self.assertEqual(h["source"][-1]["facts"], ["season", "months"])
|
||||
self.assertIn("chelsa", h["source"][-1]["url"])
|
||||
errors = []
|
||||
V.check_hike("aaa", a, errors)
|
||||
trail_history.check_entries("aaa", a, errors)
|
||||
# (the fixture's own end-point fields are not what is under test)
|
||||
self.assertEqual([e for e in errors if "lonlat" not in e], [], errors)
|
||||
self.assertTrue(any("hike.season" in (e.get("fields") or []) for e in a["history"]))
|
||||
b = R.load_toml(os.path.join(self.root, "bbb", "trail.toml"))["hike"]
|
||||
self.assertEqual(b["season_basis"], "sources")
|
||||
self.assertIn("The pages differ", b["season_method"])
|
||||
self.assertEqual([s["publisher"] for s in b["source"]][-2:], ["Guide A", "Guide B"])
|
||||
errors = []
|
||||
V.check_hike("bbb", {"hike": b}, errors)
|
||||
self.assertEqual([e for e in errors if "lonlat" not in e], [], errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Tests over the real records: every trail has a season, with its provenance.
|
||||
|
||||
Run from the repository root:
|
||||
python3 -m unittest discover tools/tests
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import refresh # noqa: E402
|
||||
import season # noqa: E402
|
||||
import validate as V # noqa: E402
|
||||
|
||||
RECORDS = {tid: refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml"))
|
||||
for tid in refresh.trail_ids(V.ROOT)}
|
||||
|
||||
|
||||
def hikes():
|
||||
for tid, rec in RECORDS.items():
|
||||
yield tid, rec.get("hike") or {}
|
||||
|
||||
|
||||
class EveryTrailHasASeasonTest(unittest.TestCase):
|
||||
def test_every_record_has_season_months_and_a_basis(self):
|
||||
for tid, hike in hikes():
|
||||
self.assertTrue(hike.get("season"), tid)
|
||||
self.assertTrue(hike.get("months"), tid)
|
||||
self.assertIn(hike.get("season_basis"), season.BASES, tid)
|
||||
|
||||
def test_the_basis_fits_the_sources(self):
|
||||
for tid, hike in hikes():
|
||||
errors = []
|
||||
season.check_season(tid, hike, errors)
|
||||
self.assertEqual(errors, [], tid)
|
||||
|
||||
def test_every_estimate_has_a_method_with_its_confidence_and_a_climate_source(self):
|
||||
found = 0
|
||||
for tid, hike in hikes():
|
||||
if hike.get("season_basis") != "estimate":
|
||||
continue
|
||||
found += 1
|
||||
self.assertIn(season.confidence_of(hike.get("season_method")), season.CONFIDENCES, tid)
|
||||
naming = [s for s in hike["source"] if "season" in s["facts"]]
|
||||
self.assertEqual(len(naming), 1, tid)
|
||||
self.assertEqual(naming[0]["facts"], ["season", "months"], tid)
|
||||
self.assertIn("chelsa-climate.org", naming[0]["url"], tid)
|
||||
self.assertGreater(found, 0)
|
||||
|
||||
def test_no_season_from_a_page_cites_climate_data(self):
|
||||
for tid, hike in hikes():
|
||||
if hike.get("season_basis") == "estimate":
|
||||
continue
|
||||
for source in hike.get("source") or []:
|
||||
if "season" in source["facts"]:
|
||||
self.assertNotIn("chelsa", source["url"], tid)
|
||||
|
||||
def test_no_record_says_a_season_is_missing(self):
|
||||
for tid, hike in hikes():
|
||||
for field in ("summary", "caution"):
|
||||
text = str(hike.get(field) or "").lower()
|
||||
self.assertNotIn("no season", text, tid)
|
||||
self.assertNotIn("season on file", text, tid)
|
||||
|
||||
def test_the_estimated_phrase_is_built_from_its_months(self):
|
||||
for tid, hike in hikes():
|
||||
if hike.get("season_basis") == "estimate":
|
||||
self.assertEqual(hike["season"], season.phrase_for(hike["months"]), tid)
|
||||
|
||||
def test_a_season_with_a_method_has_its_confidence_in_the_method(self):
|
||||
judged = [t for t, h in hikes() if h.get("season_method")]
|
||||
self.assertEqual(len(judged), 75)
|
||||
for tid in judged:
|
||||
self.assertTrue(season.confidence_of(RECORDS[tid]["hike"]["season_method"]), tid)
|
||||
|
||||
def test_a_judged_season_changed_its_record_history(self):
|
||||
for tid, hike in hikes():
|
||||
if hike.get("season_method"):
|
||||
changed = [e for e in RECORDS[tid]["history"]
|
||||
if "hike.season_method" in (e.get("fields") or [])]
|
||||
self.assertEqual(len(changed), 1, tid)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user