diff --git a/docs/schema.md b/docs/schema.md index b749a92..b900bcf 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -126,7 +126,7 @@ The field and file names keep the word "line" (`line.geojson`, `line_file`, `lin ## `[hike]`: what a hiker asks first -Optional: a record without `[hike]` is valid. The table holds the facts a hiker wants before anything else: where the trail goes, what the country is like, how long it takes, when to go, where its own site is. Every fact is read on a page, and that page is named in `[[hike.source]]`. The first choice is a page of the trail's holder (the agency, the association, or for a route its author) or a government page. Where those say nothing, a fact may be read on an established hiking reference that covers the trail, such as a guide site, a hiking association's list of trails or a guidebook publisher's page; the source entry names that site as the publisher, so a reader can see where the fact came from and weigh it. Apps and pages that anyone can edit (AllTrails, forums, social media, wikis) are not sources. A fact found on no acceptable page is left out, never guessed, except season, which may be estimated and must then say so. Typical time is estimated at page-build time and never stored, while an estimated season is stored on the record. Where sources disagree, the managing body's figure is used. Wording is ours: nothing is copied from a source. +Optional: a record without `[hike]` is valid. The table holds the facts a hiker wants before anything else: where the trail goes, what the country is like, how long it takes, when to go, where its own site is. Every fact is read on a page, and that page is named in `[[hike.source]]`. The first choice is a page of the trail's holder (the agency, the association, or for a route its author) or a government page. Where those say nothing, a fact may be read on an established hiking reference that covers the trail, such as a guide site, a hiking association's list of trails or a guidebook publisher's page; the source entry names that site as the publisher, so a reader can see where the fact came from and weigh it. Apps and pages that anyone can edit (AllTrails, forums, social media, wikis) are not sources. A fact found on no acceptable page is left out, never guessed, except season, which may be estimated and must then say so. Typical time is estimated at page-build time and never stored, while an estimated season is stored on the record. Where sources disagree, the managing body's figure is used; where none of them manages the trail, is its association or is its route author, the season is set by judgement from all the pages and the climate estimate, and `season_method` says so. Wording is ours: nothing is copied from a source. | Field | Type | Meaning | Example | | --- | --- | --- | --- | @@ -138,8 +138,8 @@ Optional: a record without `[hike]` is valid. The table holds the facts a hiker | `days` | array of two integers | The usual time to walk the whole trail in one go, `[fewest, most]`, in days, as a source states it. Weeks count 7 days, months 30. | `[150, 210]` | | `season` | string | The months in which the whole trail is usually walked, as a short phrase. Not the dates a park or hut is open, unless those set the walking season. `season` and `months` come together: one is never given without the other. For an estimated season (`season_basis = "estimate"`) the phrase is built from the months. | `"July to September"` | | `months` | array of integers | The same season as month numbers, 1 to 12, for filtering: every month in which the whole trail, or a usual start, is normally walked. A month counts when about half of it or more is in season. Given whenever `season` is, and never without it. | `[7, 8, 9]` | -| `season_basis` | string | Required whenever `season` is present, and refused without it. Where the season came from, one of: `primary` (the page is published by the body that manages the trail, the trail's own association, or, for a route worked out by a hiker, that route's author); `sources` (no primary page, but two or more pages from different publishers agree on the season); `source` (one page that is not a primary one); `estimate` (no page states a season, so it is worked out from climate). A route author's stated season counts as `primary`. | `"primary"` | -| `season_method` | string | Required with `season_basis = "estimate"`, where it is one sentence naming the method and its inputs: the dataset, the period, the points used and the rule version. Allowed with `sources`, where it says in one sentence how the season was settled when the pages differ. Refused with `primary` and `source`. | `"Estimated from 1991-2020 climate normals at 5 track points (rule version 1)."` | +| `season_basis` | string | Required whenever `season` is present, and refused without it. Where the season came from, one of: `primary` (the page is published by the body that manages the trail, the trail's own association, or, for a route worked out by a hiker, that route's author); `sources` (no primary page, but two or more pages from different publishers agree on the season); `source` (one page that is not a primary one); `estimate` (no page states a season, so it is worked out from climate). A route author's stated season counts as `primary`. An `estimate` has no page that states a season: its one `[[hike.source]]` names both `season` and `months` and cites the climate data (CHELSA, with ETOPO), and any ordinary page naming the season makes the basis wrong. An estimate is worked out by a reviewer from the trail's location, elevation, monthly climate normals, a machine estimate and the most similar sourced trails (`tools/season_judge.py`); the method was tested blind against the seasons that pages state, and the result is in `tools/season_blind_test.json`. | `"primary"` | +| `season_method` | string | Required with `season_basis = "estimate"`, where it is one or two plain sentences saying how the season was set and what sets it there, ending "Confidence: high.", "Confidence: medium." or "Confidence: low.". Allowed with `sources`, where it says how the season was settled when the pages differ; a season with a method was set by judgement and is shown as an estimate, not as a page's statement. Refused with `primary` and `source`. | `"Snow keeps the high passes closed until late June and returns in October. Confidence: high."` | | `high_point` | string | Name of the highest point on the trail. | `"Mount Mansfield"` | | `high_point_m` | integer | The elevation of the highest point in metres, rounded to the nearest metre (converted from feet where the source gives feet). May be given without `high_point` where a source states the elevation but not a name. | `1340` | | `terrain` | array of strings | One to three of `alpine`, `forest`, `desert`, `coast`, `prairie`, `canyon`, `tundra`, `lakes`, `farmland`: the main kinds of country only. | `["forest"]` | diff --git a/tools/estimate_season.py b/tools/estimate_season.py index a3d8fa9..cddd3ef 100644 --- a/tools/estimate_season.py +++ b/tools/estimate_season.py @@ -412,7 +412,7 @@ def sourced_trails(root, fetch, log=None): out = [] for tid, rec in _records(root): hike = rec.get("hike") or {} - if not hike.get("season") or hike.get("season_basis") == "estimate": + if not season.read_from_a_page(hike): continue points, kind = sample_points(root, rec) med = season_model.medians(normals_at(points, fetch)) @@ -622,7 +622,7 @@ def _phrases(root): out = {} for tid, rec in _records(root): hike = rec.get("hike") or {} - if hike.get("season") and hike.get("season_basis") != "estimate": + if season.read_from_a_page(hike): out[tid] = str(hike.get("season")) _PHRASES[root] = out return _PHRASES[root] diff --git a/tools/season.py b/tools/season.py index 7abd502..7c9a351 100644 --- a/tools/season.py +++ b/tools/season.py @@ -4,9 +4,41 @@ Python 3 standard library only. tools/validate.py imports this module; it must not import validate.py. The fields are documented in docs/schema.md. """ +import re +import urllib.parse + BASES = ("primary", "sources", "source", "estimate") PROVENANCE_KEYS = frozenset({"season_basis", "season_method"}) -SEASON_REQUIRED = False +SEASON_REQUIRED = True +# The host of the climate data an estimate cites (tools/season_climate.SOURCE). +CLIMATE_HOSTS = frozenset({"www.chelsa-climate.org"}) +CONFIDENCES = ("high", "medium", "low") +_CONFIDENCE_END = re.compile(r"Confidence: (high|medium|low)\.\s*$") + + +def _is_climate(source): + host = urllib.parse.urlparse(str(source.get("url", ""))).hostname + return host in CLIMATE_HOSTS + + +def confidence_of(method): + """"high", "medium" or "low" from the end of a season_method, else "".""" + found = _CONFIDENCE_END.search(str(method or "")) + return found.group(1) if found else "" + + +def read_from_a_page(hike): + """True when a page states the season: one is present, its basis is not + "estimate", and no method records that it was worked out by judgement + (the seasons set from pages that disagree carry one).""" + return bool(hike.get("season")) and hike.get("season_basis") in ( + "primary", "sources", "source") and not hike.get("season_method") + + +def check_present(tid, rec, errors): + """Every record has a hike table (check_season then requires its season).""" + if not isinstance(rec.get("hike"), dict): + errors.append(f"{tid}: hike.season is required") def _naming(sources, fact): @@ -51,10 +83,18 @@ def check_season(tid, hike, errors): errors.append(f"{tid}: hike.season_method must not be empty") elif len(method) >= 400: errors.append(f"{tid}: hike.season_method must be under 400 characters") + elif basis == "estimate" and not _CONFIDENCE_END.search(method): + errors.append( + f"{tid}: hike.season_method of an estimate must end with " + "\"Confidence: high.\", \"Confidence: medium.\" or \"Confidence: low.\"") elif basis == "estimate": errors.append(f"{tid}: hike.season_method is required with season_basis \"estimate\"") naming_season = _naming(sources, "season") + if basis != "estimate" and any(_is_climate(x) for x in naming_season): + errors.append( + f"{tid}: a source naming season may not cite climate data unless " + "hike.season_basis is \"estimate\"") if basis in ("primary", "source"): if not naming_season: errors.append( @@ -69,16 +109,32 @@ def check_season(tid, hike, errors): elif basis == "sources": publishers = {str(s.get("publisher", "")).strip().casefold() for s in naming_season if str(s.get("publisher", "")).strip()} - if len(publishers) < 2: + if not naming_season: + errors.append( + f"{tid}: hike.season_basis \"sources\" needs a [[hike.source]] naming season") + elif has_method: + pass # set by judgement from pages that differ; they may share a publisher + elif len(publishers) < 2: errors.append( f"{tid}: hike.season_basis \"sources\" needs two sources from different " "publishers naming season") elif basis == "estimate": - naming = {id(s) for s in _naming(sources, "season") + _naming(sources, "months")} + naming = {id(x): x for x in _naming(sources, "season") + _naming(sources, "months")} if len(naming) != 1: errors.append( f"{tid}: hike.season_basis \"estimate\" needs exactly one source naming " - "season or months") + "season or months, and it must cite the climate data (no page states a season)") + else: + only = next(iter(naming.values())) + facts = only.get("facts") or [] + if not _is_climate(only): + errors.append( + f"{tid}: hike.season_basis \"estimate\" needs its source to cite the " + "climate data (CHELSA, with ETOPO); an ordinary page naming the season " + "makes the basis wrong") + if "season" not in facts or "months" not in facts: + errors.append( + f"{tid}: the climate source of an estimate must name both season and months") # --------------------------------------------------------------------------- diff --git a/tools/tests/test_season_basis.py b/tools/tests/test_season_basis.py index db35fd9..7b9da90 100644 --- a/tools/tests/test_season_basis.py +++ b/tools/tests/test_season_basis.py @@ -20,6 +20,22 @@ def src(publisher, facts=("season", "months"), url="https://example.org/trail"): return {"url": url, "publisher": publisher, "facts": list(facts)} +CLIMATE_URL = "https://www.chelsa-climate.org/datasets/chelsa_climatologies" +CLIMATE = "WSL (CHELSA) and NOAA NCEI (ETOPO)" +METHOD = "Snow clears from the high ground in June. Confidence: medium." + + +def climate_src(**kw): + return src(CLIMATE, url=CLIMATE_URL, **kw) + + +def estimate(**fields): + fields.setdefault("season_basis", "estimate") + fields.setdefault("season_method", METHOD) + fields.setdefault("source", [climate_src()]) + return check(**fields) + + def check(**fields): hike = { "season": "June to September", @@ -98,42 +114,97 @@ class SeasonBasisTest(unittest.TestCase): errors = check(source=[src("Park Service", facts=("days",))]) self.assertTrue(errors) - def test_estimate_needs_a_method_and_refuses_one_otherwise(self): - self.assertTrue(check(season_basis="estimate")) + def test_an_estimate_with_a_method_and_a_climate_source_passes(self): + self.assertEqual(estimate(), []) + + def test_an_estimate_needs_a_method(self): + errors = estimate(season_method=None) + self.assertTrue(any("season_method" in e for e in errors), errors) + self.assertTrue(estimate(season_method="")) + self.assertTrue(estimate(season_method="x" * 401)) + + def test_an_estimate_method_ends_with_its_confidence(self): + for word in ("high", "medium", "low"): + self.assertEqual(estimate(season_method=f"Set by snow. Confidence: {word}."), []) + errors = estimate(season_method="Set by snow.") + self.assertTrue(any("Confidence" in e for e in errors), errors) + self.assertTrue(estimate(season_method="Set by snow. Confidence: certain.")) + + def test_a_method_without_an_estimate_is_still_an_error_on_a_primary(self): + self.assertTrue(check(season_method=METHOD)) + + def test_an_estimate_refuses_an_ordinary_page_naming_the_season(self): + two = [climate_src(), src("Park Service", url="https://example.org/p")] + errors = estimate(source=two) + self.assertTrue(errors) + only = [src("Park Service", url="https://example.org/p")] + errors = estimate(source=only) + self.assertTrue(any("climate" in e for e in errors), errors) + + def test_an_estimate_with_no_naming_source_is_an_error(self): + self.assertTrue(estimate(source=[climate_src(facts=("days",))])) + + def test_an_estimate_source_names_both_season_and_months(self): + errors = estimate(source=[climate_src(facts=("season",))]) + self.assertTrue(any("months" in e for e in errors), errors) + + def test_a_sourced_season_may_not_cite_the_climate_data(self): + errors = check(source=[climate_src()]) + self.assertTrue(any("climate" in e for e in errors), errors) + + def test_the_climate_host_is_the_one_the_estimator_reads(self): + import urllib.parse + import season_climate self.assertEqual( - check(season_basis="estimate", season_method="Estimated from climate normals."), []) - self.assertTrue(check(season_basis="estimate", season_method="")) - self.assertTrue(check(season_basis="estimate", season_method="x" * 401)) - self.assertTrue(check(season_method="Estimated from climate normals.")) + season.CLIMATE_HOSTS, + frozenset({urllib.parse.urlparse(season_climate.SOURCE["url"]).hostname})) - def test_estimate_with_two_naming_sources_is_an_error(self): - two = [src("Climate", url="https://c.example/1"), src("Other", url="https://o.example/1")] - errors = check(season_basis="estimate", season_method="Estimated from climate.", source=two) + def test_sources_judged_from_pages_that_differ_may_share_a_publisher(self): + two = [src("The Trek", url="https://t.example/1"), src("The Trek", url="https://t.example/2")] + errors = check(season_basis="sources", source=two) + self.assertTrue(errors) + self.assertEqual( + check(season_basis="sources", source=two, + season_method="The pages differ. Confidence: low."), []) + + def test_judged_from_pages_that_differ_needs_a_page(self): + errors = check(season_basis="sources", source=[src("The Trek", facts=("days",))], + season_method="The pages differ. Confidence: low.") self.assertTrue(errors) - def test_estimate_with_no_naming_source_is_an_error(self): - errors = check(season_basis="estimate", season_method="Estimated from climate.", - source=[src("Climate", facts=("days",))]) + def test_a_season_read_from_a_page_has_no_method_and_no_estimate_basis(self): + self.assertTrue(season.read_from_a_page({"season": "x", "season_basis": "primary"})) + self.assertFalse(season.read_from_a_page({"season": "x", "season_basis": "estimate"})) + self.assertFalse(season.read_from_a_page( + {"season": "x", "season_basis": "sources", "season_method": "Judged."})) + self.assertFalse(season.read_from_a_page({"season_basis": "primary"})) + + def test_the_confidence_is_read_from_the_method(self): + self.assertEqual(season.confidence_of("Set by snow. Confidence: low."), "low") + self.assertEqual(season.confidence_of("Set by snow."), "") + + def test_a_hike_without_season_is_an_error(self): + errors = check(season=None, months=None, season_basis=None, source=None) + self.assertTrue(any("season" in e for e in errors), errors) + + def test_a_record_with_no_hike_is_an_error(self): + errors = [] + season.check_present("t", {}, errors) self.assertTrue(errors) - - def test_a_hike_without_season_passes_until_required(self): - self.assertEqual(check(season=None, months=None, season_basis=None, source=None), []) - - def test_required_flag_makes_it_an_error(self): - with mock.patch.object(season, "SEASON_REQUIRED", True): - errors = check(season=None, months=None, season_basis=None, source=None) - self.assertTrue(any("season" in e for e in errors), errors) + errors = [] + season.check_present("t", {"hike": {"season": "x"}}, errors) + self.assertEqual(errors, []) def test_method_without_season_is_an_error(self): errors = check(season=None, months=None, season_basis=None, season_method="Some method.") self.assertTrue(errors) - def test_every_record_with_a_season_passes_the_validator(self): + def test_every_record_passes_the_validator(self): errors = [] for tid in refresh.trail_ids(V.ROOT): rec = refresh.load_toml(os.path.join(V.ROOT, tid, "trail.toml")) - if (rec.get("hike") or {}).get("season"): - V.check_hike(tid, rec, errors) + V.check_hike(tid, rec, errors) + season.check_present(tid, rec, errors) self.assertEqual(errors, []) def test_provenance_keys_need_no_source_fact(self): diff --git a/tools/validate.py b/tools/validate.py index 281c587..c337e1d 100644 --- a/tools/validate.py +++ b/tools/validate.py @@ -934,6 +934,7 @@ def main(): check_guides(tid, guides, errors) check_links(tid, rec, errors) check_hike(tid, rec, errors) + season.check_present(tid, rec, errors) check_elevation(tid, tdir, rec, errors) trail_history.check_entries(tid, rec, errors)