Show an estimated season as an estimate on the trail page, in lists and tables, and in the month filter; say how seasons are sourced and tested on the reference page
This commit is contained in:
1 parent
713fff78df
commit
e95131833b
20 files changed
+481
-103
No files matched your search
+1
-1
@@ -116,7 +116,7 @@ see = ["/lists/weekend/", "/lists/one-to-two-weeks/", "/lists/a-month-or-more/",
|
||||
[[term]]
|
||||
id = "season"
|
||||
term = "Season"
|
||||
definition = "The months in which the whole trail is usually walked, as a source states them. It is not the dates a park or a hut is open. Only some records state one."
|
||||
definition = "The months in which the whole trail is usually walked. Where a page states them, that is shown. Otherwise they are estimated from the climate at the trail's elevation and from similar trails, and the page says so: an estimated season reads “About” with a note. It is not the dates a park or a hut is open."
|
||||
see = ["/lists/"]
|
||||
|
||||
[[term]]
|
||||
|
||||
+24
-23
@@ -1940,9 +1940,10 @@
|
||||
var OLD_POLICY = { open: 'free', sold: 'sold', withheld: 'unpublished', unclear: 'elsewhere' };
|
||||
|
||||
/* facet-counts:begin — pure, with no page: web/tests/test_filter_counts.py runs this under node.
|
||||
A row: {search: [name, author, places, summary], where: [], km, time, months: [], terrain: [], kind, walking, shape, gpx}.
|
||||
A state: {words: [], where, min, max (km; max may be Infinity), month, kind, and a list for
|
||||
each of time, terrain, walking, shape, gpx}. */
|
||||
A row: {search: [name, author, places, summary], where: [], km, time, months: [], estimate, terrain: [], kind, walking, shape, gpx}.
|
||||
A state: {words: [], where, min, max (km; max may be Infinity), month, stated, kind, and a list for
|
||||
each of time, terrain, walking, shape, gpx}. stated: with a month chosen, leave out the rows whose
|
||||
season is an estimate. */
|
||||
var FacetCount = (function () {
|
||||
var FACETS = ['where', 'length', 'time', 'month', 'terrain', 'kind', 'walking', 'shape', 'gpx'];
|
||||
function has(list, v) { return list.indexOf(v) !== -1; }
|
||||
@@ -1991,6 +1992,9 @@
|
||||
if (skip !== 'length' && (d.km < s.min || d.km > s.max)) return false;
|
||||
if (skip !== 'time' && s.time.length && !has(s.time, d.time)) return false;
|
||||
if (skip !== 'month' && s.month && !has(d.months, s.month)) return false;
|
||||
/* Leaving estimates out belongs to the month: it holds in counting each month too, so the
|
||||
number beside a month is what choosing it, with estimates left out, shows. */
|
||||
if (s.month && s.stated && d.estimate) return false;
|
||||
if (skip !== 'terrain' && s.terrain.length && !d.terrain.some(function (t) { return has(s.terrain, t); })) return false;
|
||||
if (skip !== 'kind' && s.kind && d.kind !== s.kind) return false;
|
||||
if (skip !== 'walking' && s.walking.length && !has(s.walking, d.walking)) return false;
|
||||
@@ -2052,15 +2056,14 @@
|
||||
var rows = Array.prototype.map.call(resultsRoot.querySelectorAll('.entry[data-id]'), function (li) {
|
||||
var d = li.dataset;
|
||||
return { li: li, id: d.id, search: FacetCount.textsOf(d.search), where: split(d.where), km: Number(d.km), time: d.time || '',
|
||||
months: split(d.months), terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
|
||||
months: split(d.months), estimate: d.estimate === 'yes', terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
|
||||
shape: d.shape || '', gpx: d.gpx || '' };
|
||||
});
|
||||
var lists = Array.prototype.slice.call(resultsRoot.querySelectorAll('ol.entries'));
|
||||
var count = resultsRoot.querySelector('.results-count');
|
||||
var noun = (count && count.dataset.noun) || 'trails';
|
||||
var empty = resultsRoot.querySelector('.empty-state');
|
||||
var unseasoned = resultsRoot.querySelector('[data-unseasoned]');
|
||||
var unseasonedText = resultsRoot.querySelector('[data-unseasoned-text]');
|
||||
var seasonAlways = resultsRoot.hasAttribute('data-season-shown');
|
||||
var active = form.querySelector('.filters__active');
|
||||
var lenHint = document.getElementById('len-hint');
|
||||
var listHead = resultsRoot.querySelector('.list-head');
|
||||
@@ -2160,6 +2163,7 @@
|
||||
maxRaw: maxRaw,
|
||||
swapped: swapped,
|
||||
month: value(el.month),
|
||||
stated: !!(el.stated && el.stated.checked && value(el.month)),
|
||||
kind: radio('kind')
|
||||
};
|
||||
MULTI.forEach(function (name) { s[name] = checked(name); });
|
||||
@@ -2287,6 +2291,7 @@
|
||||
if (s.min) p.set('min', s.minRaw);
|
||||
if (s.max !== Infinity) p.set('max', s.maxRaw);
|
||||
if (s.month) p.set('month', s.month);
|
||||
if (s.month && s.stated) p.set('stated', '1');
|
||||
if (s.kind) p.set('kind', s.kind);
|
||||
MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); });
|
||||
if (sort && sort.value !== defaultSort && sort.value !== 'nearest') p.set('sort', sort.value);
|
||||
@@ -2332,6 +2337,7 @@
|
||||
if (el.month) {
|
||||
var month = p.get('month') || '';
|
||||
el.month.value = hasOption(el.month, month) ? month : '';
|
||||
if (el.stated) el.stated.checked = !!el.month.value && p.get('stated') === '1';
|
||||
}
|
||||
var kind = p.get('kind') || '';
|
||||
if (kind === 'designated') kind = 'trail';
|
||||
@@ -2460,16 +2466,19 @@
|
||||
count.appendChild(document.createTextNode(' ' + words));
|
||||
}
|
||||
if (empty) empty.hidden = shown.length > 0;
|
||||
/* With a month chosen, say how many trails that pass everything else are left out for having no
|
||||
season on file, counted over the same rows as the list. */
|
||||
if (unseasoned && el.month) {
|
||||
var noSeason = 0;
|
||||
if (s.month) rows.forEach(function (d) { if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++; });
|
||||
unseasoned.hidden = noSeason === 0;
|
||||
if (noSeason) {
|
||||
unseasonedText.textContent = noSeason + (noSeason === 1 ? ' trail with no season on file is not shown.'
|
||||
: ' trails with no season on file are not shown.');
|
||||
/* A month's rows show their season, and the way to leave estimated seasons out is offered once a
|
||||
month is chosen and some of the trails that pass everything else have an estimated season. */
|
||||
if (!seasonAlways) resultsRoot.toggleAttribute('data-season-shown', !!s.month);
|
||||
if (el.stated) {
|
||||
var open = false;
|
||||
if (s.month) {
|
||||
var withEstimates = Object.assign({}, s, { stated: false });
|
||||
open = rows.some(function (d) { return d.estimate && FacetCount.passes(d, withEstimates, ''); });
|
||||
}
|
||||
el.stated.disabled = !s.month;
|
||||
if (!s.month) el.stated.checked = false;
|
||||
var box = el.stated.closest('label');
|
||||
if (box) box.hidden = !open && !el.stated.checked;
|
||||
}
|
||||
if (listHead) listHead.hidden = shown.length === 0;
|
||||
relabel(s, c);
|
||||
@@ -2499,14 +2508,6 @@
|
||||
form.addEventListener('change', function () { apply(true); });
|
||||
form.addEventListener('submit', function (e) { e.preventDefault(); });
|
||||
form.addEventListener('reset', function () { setTimeout(function () { apply(true); }, 0); });
|
||||
resultsRoot.querySelectorAll('[data-unseasoned-show]').forEach(function (b) {
|
||||
/* Showing them is clearing the month; the rest of the filters stay. */
|
||||
b.addEventListener('click', function () {
|
||||
if (!el.month) return;
|
||||
el.month.value = '';
|
||||
el.month.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
});
|
||||
});
|
||||
resultsRoot.querySelectorAll('[data-reset]').forEach(function (b) {
|
||||
b.addEventListener('click', function () { form.reset(); el.q.focus(); });
|
||||
});
|
||||
|
||||
@@ -1247,6 +1247,11 @@ html.js .filters__panels:not([data-open]) { display: none; }
|
||||
.results-note { margin-block: calc(-1 * var(--space-1)) var(--space-3); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
|
||||
.results-note[hidden] { display: none; }
|
||||
.results-note__show { padding: 0; border: 0; background: none; color: var(--link); font: inherit; text-decoration: underline; cursor: pointer; }
|
||||
/* A row's season: shown on a month's list, and while a month is chosen (app.js). */
|
||||
.entry__season { display: none; }
|
||||
[data-season-shown] .entry__season { display: block; }
|
||||
.field__check { display: block; margin-block-start: var(--space-1); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
|
||||
.field__check[hidden] { display: none; }
|
||||
.key {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
+10
-5
@@ -78,7 +78,7 @@ GROUPS = (
|
||||
("walking", "By kind of walking", "Loops, high routes, walking with no trail, and trails not yet finished."),
|
||||
("terrain", "By terrain", "The main kinds of country a trail crosses."),
|
||||
("holder", "By who looks after it", "Trails whose designation names the holder."),
|
||||
("month", "By month", "Trails whose season on file includes the month. Only some trails have a season."),
|
||||
("month", "By month", "Trails normally hiked in the month. Estimated seasons are marked."),
|
||||
("where", "By country and GPX", "Where a trail is, and whether its page has a track to download."),
|
||||
)
|
||||
|
||||
@@ -115,7 +115,7 @@ def time_note(recs, records):
|
||||
def _month_list(m):
|
||||
name = facets.MONTHS[m - 1]
|
||||
return List(f"hike-in-{name.lower()}", f"Hiking in {name}",
|
||||
f"Trails whose season on file includes {name}.",
|
||||
f"Trails normally hiked in {name}. Estimated seasons are marked.",
|
||||
lambda r, m=m: m in facets.months(r),
|
||||
page_title=f"Long Trails to Hike in {name}: {{n}} Trails", group="month", note=month_note(name),
|
||||
min_size=MONTH_MIN)
|
||||
@@ -123,9 +123,14 @@ def _month_list(m):
|
||||
|
||||
def month_note(name):
|
||||
def note(recs, records):
|
||||
have = sum(1 for r in records if facets.months(r))
|
||||
return (f"Only {have} of the {len(records)} trails have a season on file, so this page covers those "
|
||||
f"{have}. It is not every trail that can be walked in {name}.")
|
||||
est = sum(1 for r in recs if facets.season_estimated(r))
|
||||
stated = len(recs) - est
|
||||
if not est:
|
||||
return f"A source states the season for all {stated}."
|
||||
if not stated:
|
||||
return "No source states the season for these, so each is estimated from climate."
|
||||
return (f"A source states the season for {stated} of these. For the other {est} it is "
|
||||
f"estimated from climate, and marked.")
|
||||
return note
|
||||
|
||||
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
collections.toml [[collection]] named sets of trails set side by side (olt/standing.py)
|
||||
[[list]] which lists the home page shows, and in what order (olt/home.py)
|
||||
authors.toml [[author]] route authors, and the words about the people among them (olt/authors.py)
|
||||
tools/season_blind_test.json how the judged seasons did against the seasons pages state (olt/reference.py)
|
||||
|
||||
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
|
||||
is looked for in the repository being built and then in this one, so a test repository without
|
||||
one still builds.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
@@ -40,3 +42,14 @@ def authors(repo_root):
|
||||
def lists(repo_root):
|
||||
"""The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row."""
|
||||
return load(repo_root, "collections.toml", "list")
|
||||
|
||||
|
||||
def blind_test(repo_root):
|
||||
"""The blind test of the judged seasons (tools/season_blind_test.json, written by
|
||||
tools/season_judge.py score), or None when there is none."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
path = os.path.join(base or REAL_ROOT, "tools", "season_blind_test.json")
|
||||
if os.path.isfile(path):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
return None
|
||||
+83
-6
@@ -172,8 +172,15 @@ def months(rec):
|
||||
return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12})
|
||||
|
||||
|
||||
def season_text(rec):
|
||||
"""The phrase on the trail page: [hike].season, else built from the months."""
|
||||
def season_estimated(rec):
|
||||
"""True when no page states the season: it was estimated (season_basis "estimate"), or set by
|
||||
judgement from pages that differ (it carries a season_method). Such a season reads "About"."""
|
||||
h = hike.table(rec)
|
||||
return bool(h.get("season")) and (h.get("season_basis") == "estimate" or bool((h.get("season_method") or "").strip()))
|
||||
|
||||
|
||||
def season_phrase(rec):
|
||||
"""The phrase on the trail page as the record gives it: [hike].season, else built from the months."""
|
||||
phrase = (hike.table(rec).get("season") or "").strip()
|
||||
if phrase:
|
||||
return phrase[:1].upper() + phrase[1:]
|
||||
@@ -185,6 +192,74 @@ def season_text(rec):
|
||||
return words.join_names(MONTHS[m - 1] for m in ms)
|
||||
|
||||
|
||||
def season_text(rec):
|
||||
"""The season as a page shows it: the phrase, or "About ..." where it is estimated, so an
|
||||
estimate never reads as a stated fact ("About June to September", "About all year")."""
|
||||
phrase = season_phrase(rec)
|
||||
if not phrase or not season_estimated(rec):
|
||||
return phrase
|
||||
if phrase.lower().startswith("about"):
|
||||
return phrase
|
||||
if phrase.lower() == "all year":
|
||||
phrase = phrase.lower()
|
||||
return "About " + phrase
|
||||
|
||||
|
||||
def season_kind(rec):
|
||||
"""How the season is known: "stated" (a page states it), "judged" (set by judgement from pages
|
||||
that differ), "estimated" (no page states one), or "" when the trail has no season."""
|
||||
if not hike.table(rec).get("season"):
|
||||
return ""
|
||||
if not season_estimated(rec):
|
||||
return "stated"
|
||||
return "judged" if season_basis(rec) == "sources" else "estimated"
|
||||
|
||||
|
||||
SEASON_CONFIDENCE = re.compile(r"\s*Confidence: (high|medium|low)\.\s*$")
|
||||
JUDGED_LEAD = "Judged from the climate at the trail's elevation and from similar trails."
|
||||
|
||||
|
||||
def season_confidence(rec):
|
||||
""""high", "medium" or "low" from the end of the season's method; "" when it names none."""
|
||||
found = SEASON_CONFIDENCE.search(hike.table(rec).get("season_method") or "")
|
||||
return found.group(1) if found else ""
|
||||
|
||||
|
||||
def season_reason(rec):
|
||||
"""What the season's method says sets the season, without its standard first sentence and its
|
||||
closing confidence."""
|
||||
text = SEASON_CONFIDENCE.sub("", (hike.table(rec).get("season_method") or "").strip()).strip()
|
||||
if text.startswith(JUDGED_LEAD):
|
||||
text = text[len(JUDGED_LEAD):].strip()
|
||||
return text
|
||||
|
||||
|
||||
def season_pages_differ(rec):
|
||||
"""True for a season set by judgement from pages that state different seasons."""
|
||||
return season_estimated(rec) and season_basis(rec) == "sources"
|
||||
|
||||
|
||||
def season_note(rec):
|
||||
"""Says an estimated season is not a page's statement, how it was worked out, what sets it
|
||||
there and how far to trust it; "" when a page states the season."""
|
||||
if not season_estimated(rec):
|
||||
return ""
|
||||
reason = season_reason(rec)
|
||||
if season_pages_differ(rec):
|
||||
lead = "No one page states this season."
|
||||
else:
|
||||
lead = ("No page states a season. This is estimated from the climate at the trail's "
|
||||
"elevation and from similar trails.")
|
||||
parts = [lead]
|
||||
if reason:
|
||||
parts.append(reason)
|
||||
conf = season_confidence(rec)
|
||||
if conf:
|
||||
parts.append(f"Confidence: {conf}.")
|
||||
parts.append("People do walk it outside these months.")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
SEASON_BASIS_TEXT = {
|
||||
"primary": "The season comes from the page of the body that manages the trail or the trail's own association or, for a route, its author.",
|
||||
"sources": "Two or more pages from different publishers agree on the season.",
|
||||
@@ -203,10 +278,12 @@ def season_basis(rec):
|
||||
def season_basis_line(rec):
|
||||
"""One sentence for "About this data"; "" when the season has no recorded basis."""
|
||||
basis = season_basis(rec)
|
||||
if basis == "estimate":
|
||||
method = (hike.table(rec).get("season_method") or "").strip()
|
||||
return (method + " No page states a season.").strip()
|
||||
return SEASON_BASIS_TEXT.get(basis, "")
|
||||
if not season_estimated(rec):
|
||||
return SEASON_BASIS_TEXT.get(basis, "")
|
||||
method = (hike.table(rec).get("season_method") or "").strip()
|
||||
if season_pages_differ(rec):
|
||||
return (method + " It is a judgement, not any one page's statement.").strip()
|
||||
return (method + " No page states a season.").strip()
|
||||
|
||||
|
||||
# Terrain, Walking, Shape ----------------------------------------------------
|
||||
|
||||
+17
-10
@@ -193,6 +193,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
if search:
|
||||
data["search"] = searchtext.attribute(rec)
|
||||
attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items())
|
||||
estimated = facets.season_estimated(rec)
|
||||
if estimated:
|
||||
attrs += ' data-estimate="yes"'
|
||||
if common.line_differs(rec):
|
||||
attrs += ' data-partial="yes"'
|
||||
h = f"h{level}"
|
||||
@@ -203,6 +206,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
desc = entry_desc(rec)
|
||||
desc_html = f'\n <p class="entry__desc">{esc(desc)}</p>' if desc else ""
|
||||
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
|
||||
season_html = (f'\n <div class="entry__season"><dt>{facets.SEASON}</dt><dd>{esc(facets.season_text(rec))}'
|
||||
+ ('<small class="entry__est">estimate</small>' if estimated else "") + "</dd></div>"
|
||||
if facets.months(rec) else "")
|
||||
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(climb_m, "stack")}'
|
||||
f'<small class="entry__est">computed</small></dd></div>') if climb_m is not None else ""
|
||||
if hidden:
|
||||
@@ -227,7 +233,7 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
<dl class="entry__facts">{lead_html}
|
||||
<div class="entry__length"><dt>Length</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}<span class="loglen" style="--km: {rec["length_km"]}" aria-hidden="true"></span></dd></div>
|
||||
<div class="entry__time"><dt>Time</dt><dd>{time_html}</dd></div>
|
||||
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{climb_html}{more_html}
|
||||
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{season_html}{climb_html}{more_html}
|
||||
</dl>{extra}
|
||||
</li>"""
|
||||
|
||||
@@ -352,10 +358,14 @@ def finder_form(records, c=None, steps=None, where="all"):
|
||||
</fieldset>""")
|
||||
if facets.offered(records, "season") and _narrows(c, "month", range(1, 13)):
|
||||
month_opts = "".join(_opt(str(i), m, c[f"month:{i}"]) for i, m in enumerate(facets.MONTHS, 1) if c[f"month:{i}"])
|
||||
# A way to leave estimated seasons out, offered only where some of these trails have one.
|
||||
stated_box = ('\n <label class="field__check"><input type="checkbox" name="stated" value="1" disabled> '
|
||||
'Leave out estimated seasons</label>'
|
||||
if any(facets.season_estimated(r) for r in records) else "")
|
||||
first.append(f"""<div class="field" data-facet="month">
|
||||
<label class="field__label" for="month">{facets.SEASON}</label>
|
||||
<select class="select" id="month" name="month"><option value="">Any month</option>{month_opts}</select>
|
||||
<p class="field__hint">Trails usually walked in that month.</p>
|
||||
<p class="field__hint">Trails usually walked in that month. Estimated seasons are marked.</p>{stated_box}
|
||||
{_missing(records, "season")}
|
||||
</div>""")
|
||||
if _narrows(c, "kind", facets.KINDS):
|
||||
@@ -535,7 +545,7 @@ def key(official=True):
|
||||
|
||||
|
||||
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False, top=3,
|
||||
ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None):
|
||||
ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None, season=False):
|
||||
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
|
||||
|
||||
Every list carries the same "Sort by" control. The rows are written in
|
||||
@@ -544,6 +554,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
|
||||
|
||||
finder: a list driven by the filter bar over it (listing(): live count, empty state).
|
||||
every: the list holds every trail (the home page's).
|
||||
season: show each row's season (a month's list), as app.js does when a month is chosen.
|
||||
groups: [(heading, trails, extra_fn)] to list the trails under headings (level `top`);
|
||||
sorting is within each group and the groups keep their order. A heading may be a pair
|
||||
(heading HTML, intro HTML): the intro is a sentence under the heading (an author's summary).
|
||||
@@ -624,18 +635,14 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
|
||||
tools = sort_select(default_sort, saved=saved, ranked=ranked, wholly=wholly)
|
||||
dflt = SAVED_ORDER[0] if saved else "rank" if ranked else HERE_ORDER if wholly else default_sort
|
||||
finder_attr = " data-finder" if finder else ""
|
||||
# Under the count, while a month is chosen: how many trails are left out for having no season on
|
||||
# file, and a way to see them (app.js fills it in from the rows, the same ones the list is).
|
||||
unseasoned = ('\n <p class="results-note" data-unseasoned hidden><span data-unseasoned-text></span> '
|
||||
'<button class="results-note__show" type="button" data-unseasoned-show>Show them</button></p>'
|
||||
if finder else "")
|
||||
return Markup(f"""<div class="results"{finder_attr} data-sortable data-default-sort="{esc(dflt)}">
|
||||
season_attr = " data-season-shown" if season else ""
|
||||
return Markup(f"""<div class="results"{finder_attr}{season_attr} data-sortable data-default-sort="{esc(dflt)}">
|
||||
<div class="results-head">
|
||||
{count}
|
||||
<div class="results-tools">
|
||||
{tools}
|
||||
</div>
|
||||
</div>{unseasoned}
|
||||
</div>
|
||||
{key(official=not only_routes)}
|
||||
{list_head(default_sort)}{lists}{empty}
|
||||
</div>""")
|
||||
|
||||
@@ -105,7 +105,7 @@ def page(p, records, site, all_pages):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where=""), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where="", season=lst.group == "month"), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
|
||||
about=summary.facts(recs, records, place=(name, [info["key"]])), about_title=f"About these trails in {name}")}
|
||||
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
|
||||
{nav}
|
||||
|
||||
+32
-2
@@ -96,6 +96,32 @@ def verified(records):
|
||||
return out
|
||||
|
||||
|
||||
def _pct(share):
|
||||
return f"{share * 100:.0f} percent"
|
||||
|
||||
|
||||
def season_section(records, blind):
|
||||
"""The paragraphs and table saying where seasons come from, how many trails have each kind, and how
|
||||
the estimates did in the blind test (read from tools/season_blind_test.json, never typed)."""
|
||||
n = len(records)
|
||||
kinds = collections.Counter(facets.season_kind(r) for r in records)
|
||||
basis = collections.Counter(facets.season_basis(r) for r in records if facets.season_kind(r) == "stated")
|
||||
rows = [["The body that manages the trail, its association, or for a route its author", str(basis["primary"])],
|
||||
["Two or more pages from different publishers that agree", str(basis["sources"])],
|
||||
["One page", str(basis["source"])],
|
||||
["Pages that differ, so set by judgement from all of them", str(kinds["judged"])],
|
||||
["No page states one, so estimated from climate", str(kinds["estimated"])],
|
||||
["All trails", str(n)]]
|
||||
out = [f"""<p>Every trail has a season. Where a page states one, the season is that page’s. Where the pages that state one differ and none is the trail’s holder, its association or its route’s author, the season is set by judgement from all of them and the climate, and the page says so. Where no page states one, the season is estimated from the climate at the trail’s elevation and from similar trails: it reads “About” with a note, is marked in lists and is left out of the data search engines read. People do walk many trails outside their estimated months, and an estimate is replaced when a page that states a season is found.</p>
|
||||
{pagekit.table(["Where a trail's season comes from", "Trails"], rows, caption="Where the seasons come from", numeric=(1,))}"""]
|
||||
if blind:
|
||||
by = blind["by_confidence"]
|
||||
conf = ", ".join(f"{name} {by[name]['matched']} of {by[name]['tested']} ({_pct(by[name]['share'])})"
|
||||
for name in ("high", "medium", "low") if by[name]["tested"])
|
||||
out.append(f"""<p>How the estimates were tested. On {esc(blind["date"])} the method was run blind on {blind["tested"]} trails whose seasons a page does state, with those seasons hidden. It matched {blind["matched"]} of them ({_pct(blind["share"])}) within one month at each end of the season the page states. By the confidence it gave each estimate: {esc(conf)}. This measures how the method did where the answer is known, not a promise for any one trail.</p>""")
|
||||
return "\n ".join(out)
|
||||
|
||||
|
||||
def method_page(records, site, repo_root):
|
||||
"""(title, description, body) for /method/."""
|
||||
meaning = schema_meanings(repo_root)
|
||||
@@ -120,12 +146,15 @@ def method_page(records, site, repo_root):
|
||||
(a, b), (c, d_) = facets.PACE_KM, facets.PACE_KM_CROSS
|
||||
coverage = []
|
||||
for label, fn in (("A usual time stated by a source", lambda r: not facets.time_days(r)[2]),
|
||||
("A season", lambda r: bool(facets.months(r))), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
|
||||
("A season a page states", lambda r: facets.season_kind(r) == "stated"),
|
||||
("A season set from pages that differ", lambda r: facets.season_kind(r) == "judged"),
|
||||
("A season estimated from climate", lambda r: facets.season_kind(r) == "estimated"), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
|
||||
("Terrain", lambda r: bool(facets.terrain(r))), ("What the walking is", lambda r: bool(facets.walking(r))),
|
||||
("A computed climb that covers the whole trail", lambda r: facets.row_climb_m(r) is not None),
|
||||
("A track included here", common.has_line)):
|
||||
have = sum(1 for r in records if fn(r))
|
||||
coverage.append([label, str(have), str(n - have)])
|
||||
season_html = season_section(records, datafiles.blind_test(repo_root))
|
||||
rows = [[label, str(k), f"{k / len(ver) * 100:.0f}%" if ver else ""] for label, k in bands]
|
||||
body = (pagekit.head("How the figures are measured", (
|
||||
f"What each figure on this site means, and how far to trust it. {len(ver)} of the {n} trails have a track whose "
|
||||
@@ -145,7 +174,8 @@ def method_page(records, site, repo_root):
|
||||
<p>Climb is the total ascent along the track.{(" It uses " + esc(model) + ", sampled every " + words.fmt_int(spacing) + " metres, with " + esc(smoothing[:1].lower() + smoothing[1:]) + ".") if model and spacing else ""} {esc(limits_text)}</p>
|
||||
<p>A climb is ranked or shown in a list only where its track covers the whole trail: a track that covers part of the trail, or more than the trail, would mislead.</p>
|
||||
<h2>Season and high point</h2>
|
||||
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} Not every record has them, so a page built from them says how many records it covers.</p>
|
||||
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} </p>
|
||||
{season_html}
|
||||
<h2>What the records have</h2>
|
||||
{pagekit.table(["Figure", "Records with it", "Records without"], coverage, caption="How many records carry each figure", numeric=(1, 2))}
|
||||
<p>Every fact is read on a page that the record names. See the <a href="/sources/">sources</a>, the <a href="/data/schema/">record schema</a> and <a href="{GLOSSARY}">the glossary</a>.</p>
|
||||
|
||||
+1
-1
@@ -390,7 +390,7 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead),
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead, season=lst.group == "month"),
|
||||
home.overview_map(recs, f"Map of the trails in the list {lst.title}"),
|
||||
about=f"{about}{before}{f'<p>{esc(note.strip())}</p>' if note else ''}<p class=\"finder__foot\">{rule}</p>",
|
||||
about_title="About this list")}
|
||||
|
||||
+2
-1
@@ -284,7 +284,8 @@ def _properties(rec):
|
||||
props.append(_pv("Shape", facets.SHAPES[shape]))
|
||||
props.append(_pv("Start", h.get("start", "")) if h.get("start") else None)
|
||||
props.append(_pv("End", h.get("end", "")) if h.get("end") else None)
|
||||
props.append(_pv("Usual season", h["season"]) if h.get("season") else None)
|
||||
# Only a season a page states: an estimate is not a fact about the trail to hand to a search engine.
|
||||
props.append(_pv("Usual season", h["season"]) if h.get("season") and not facets.season_estimated(rec) else None)
|
||||
if common.is_route(rec):
|
||||
route = rec.get("route", {})
|
||||
props.append(_pv("Route author", route["creator"]) if route.get("creator") else None)
|
||||
|
||||
+3
-1
@@ -45,14 +45,16 @@ def time_cell(rec):
|
||||
|
||||
|
||||
def season_cell(rec):
|
||||
return facets.season_text(rec) or "Not on file"
|
||||
return facets.season_text(rec)
|
||||
|
||||
|
||||
def figures_note(recs):
|
||||
"""What the times and climbs of these trails mean, with the caveats the records state."""
|
||||
est = sum(1 for r in recs if facets.time_days(r)[2])
|
||||
unstated = sum(1 for r in recs if facets.season_estimated(r))
|
||||
parts = [f"Times that start with “About” are estimated from the length ({est} of these). "
|
||||
"Otherwise a source states the time.",
|
||||
f"Seasons that start with “About” are estimated from climate ({unstated} of these)." if unstated else "",
|
||||
climb_caveat(recs)]
|
||||
return " ".join(p for p in parts if p)
|
||||
|
||||
|
||||
+3
-1
@@ -148,7 +148,9 @@ def detail(rec):
|
||||
out.append(f"Its high point is {esc(name + ', ') if name else ''}{words.elevation(m)}.")
|
||||
season = facets.season_text(rec)
|
||||
if season:
|
||||
out.append(f"Season: {esc(season)}.")
|
||||
how = (", judged from pages that differ" if facets.season_pages_differ(rec)
|
||||
else ", estimated from climate" if facets.season_estimated(rec) else "")
|
||||
out.append(f"Season: {esc(season)}{how}.")
|
||||
rest = _rest_of_summary(rec)
|
||||
if rest:
|
||||
out.append(f'<span class="record-text">{esc(rest)}</span>')
|
||||
|
||||
+17
-5
@@ -282,6 +282,7 @@ def _name_html(rec):
|
||||
|
||||
|
||||
MAX_BRIEF = 4 # sentences in the "In brief" paragraph
|
||||
PINNED = -1 # the priority of a sentence that is kept besides those (an estimated season)
|
||||
MONTH_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||
SEASON_WORDS = ("spring", "summer", "fall", "autumn", "winter", "late", "early", "mid", "from", "about")
|
||||
SENTENCE_VERBS = re.compile(r"\b(is|are|can|start|starts|hikes?|hiked|travelled|traveled|bring|brings|closed|best)\b", re.I)
|
||||
@@ -292,6 +293,13 @@ def season_sentence(rec):
|
||||
seasons, ("sentence", "Northbound hikes start late February to early April") for one the record
|
||||
already words as a sentence, or None when the record has none or it is too long to say briefly.
|
||||
The caller adds the full stop. Only the record's own words are used."""
|
||||
if facets.season_estimated(rec):
|
||||
# Never worded as a fact, and never joined to the GPX clause with "and".
|
||||
phrase = facets.season_phrase(rec).rstrip(". ")
|
||||
phrase = phrase.lower() if phrase.lower() == "all year" else phrase
|
||||
if facets.season_pages_differ(rec):
|
||||
return ("estimate", f"The pages differ on the season; it is judged to be about {phrase}")
|
||||
return ("estimate", f"No source gives a season; the climate suggests about {phrase}")
|
||||
text = facets.season_text(rec).strip().rstrip(". ")
|
||||
if not text:
|
||||
return None
|
||||
@@ -431,19 +439,23 @@ def brief_sentences(rec):
|
||||
# When to walk it and whether this site has a GPX: one sentence where the season is a plain range.
|
||||
clause = gpx_clause(rec) or ("this site has no GPX for it" + _see_clause(rec))
|
||||
season = season_sentence(rec)
|
||||
if season and not re.search(r"[,;]", season[1]):
|
||||
if season and season[0] != "estimate" and not re.search(r"[,;]", season[1]):
|
||||
# "The usual season is May to July, and this page has a GPX of the track to download."
|
||||
items.append((3, 5, f"{esc(season[1])}, and {esc(clause)}."))
|
||||
else:
|
||||
if season:
|
||||
items.append((3.5, 5, esc(season[1]) + "."))
|
||||
# An estimated season is always said, so it is never left for a reader to take as a fact
|
||||
# by omission: it is the one sentence that may stand beyond MAX_BRIEF.
|
||||
items.append((PINNED if season[0] == "estimate" else 3.5, 5, esc(season[1]) + "."))
|
||||
items.append((3, 6, esc(clause[:1].upper() + clause[1:]) + "."))
|
||||
permit = permit_sentence(rec)
|
||||
if permit:
|
||||
items.append((6, 7, esc(permit)))
|
||||
|
||||
# At most MAX_BRIEF sentences: the lowest priorities are kept, shown in reading order.
|
||||
kept = sorted(sorted(items, key=lambda i: (i[0], i[1]))[:MAX_BRIEF], key=lambda i: i[1])
|
||||
pinned = [i for i in items if i[0] == PINNED]
|
||||
rest = sorted((i for i in items if i[0] != PINNED), key=lambda i: (i[0], i[1]))[:MAX_BRIEF]
|
||||
kept = sorted(rest + pinned, key=lambda i: i[1])
|
||||
return [text for _, _, text in kept]
|
||||
|
||||
|
||||
@@ -624,7 +636,7 @@ def glance(rec, records=None):
|
||||
rows.append(glance_row(facets.TIME, facets.time_text(rec), time_note(rec, records)))
|
||||
season = facets.season_text(rec)
|
||||
if season:
|
||||
rows.append(glance_row(facets.SEASON, season))
|
||||
rows.append(glance_row(facets.SEASON, season, facets.season_note(rec)))
|
||||
if facets.walking(rec):
|
||||
walking = facets.WALKING_VALUES[facets.walking(rec)]
|
||||
if facets.walking(rec) in facets.CROSS_COUNTRY:
|
||||
@@ -692,7 +704,7 @@ def glance(rec, records=None):
|
||||
unfinished = ""
|
||||
if h.get("unfinished"):
|
||||
unfinished = f'<p class="glance__warn"><strong>Not finished.</strong> {common.rich(common.sentence(h["unfinished"]))}</p>'
|
||||
missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain),
|
||||
missing = [name for name, have in ((facets.TERRAIN, terrain),
|
||||
(facets.WALKING, facets.walking(rec)),
|
||||
(PERMITS, h.get("permit"))) if not have]
|
||||
pending = ""
|
||||
|
||||
@@ -173,6 +173,59 @@ class PlaceTest(unittest.TestCase):
|
||||
self.assertIn('<a href="/regions/us-co/">Colorado</a>', crumbs)
|
||||
|
||||
|
||||
def est_hike(**kw):
|
||||
h = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate",
|
||||
"season_method": "Judged from the climate at the trail's elevation and from similar trails. "
|
||||
"Snow keeps the high passes closed until June. Confidence: medium."}
|
||||
h.update(kw)
|
||||
return h
|
||||
|
||||
|
||||
class SeasonTextTest(unittest.TestCase):
|
||||
def test_an_estimated_season_reads_about_and_has_a_note(self):
|
||||
rec = fake(1, hike=est_hike())
|
||||
self.assertTrue(facets.season_estimated(rec))
|
||||
self.assertEqual(facets.season_text(rec), "About June to September")
|
||||
note = facets.season_note(rec)
|
||||
for want in ("No page states a season", "estimated from the climate at the trail's elevation and from "
|
||||
"similar trails", "Snow keeps the high passes closed until June.", "Confidence: medium.",
|
||||
"People do walk it outside these months."):
|
||||
self.assertIn(want, note)
|
||||
self.assertNotIn("Judged from", note) # the standard lead is said once, in the note's own words
|
||||
|
||||
def test_a_stated_season_is_unchanged_and_has_no_note(self):
|
||||
rec = fake(1, hike={"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "primary"})
|
||||
self.assertFalse(facets.season_estimated(rec))
|
||||
self.assertEqual(facets.season_text(rec), "June to September")
|
||||
self.assertEqual(facets.season_note(rec), "")
|
||||
|
||||
def test_an_estimated_all_year_season_reads_about_all_year(self):
|
||||
rec = fake(1, hike=est_hike(season="All year", months=list(range(1, 13))))
|
||||
self.assertEqual(facets.season_text(rec), "About all year")
|
||||
|
||||
def test_it_is_not_estimated_without_a_basis_or_a_method(self):
|
||||
self.assertFalse(facets.season_estimated(fake(1, hike={"season": "May", "months": [5]})))
|
||||
self.assertFalse(facets.season_estimated(fake(1)))
|
||||
self.assertEqual(facets.season_kind(fake(1)), "")
|
||||
|
||||
def test_a_season_judged_from_pages_that_differ_says_so(self):
|
||||
rec = fake(1, hike=est_hike(season_basis="sources", season_method=(
|
||||
"The pages differ: one gives May to October and one gives June to November. It was set by "
|
||||
"judgement from both and from the climate. Confidence: medium.")))
|
||||
self.assertTrue(facets.season_estimated(rec))
|
||||
self.assertEqual(facets.season_kind(rec), "judged")
|
||||
self.assertEqual(facets.season_text(rec), "About June to September")
|
||||
note = facets.season_note(rec)
|
||||
self.assertIn("No one page states this season.", note)
|
||||
self.assertIn("The pages differ", note)
|
||||
self.assertNotIn("estimated from the climate at the trail's elevation", note)
|
||||
self.assertIn("It is a judgement", facets.season_basis_line(rec))
|
||||
|
||||
def test_the_basis_line_gives_the_method_for_an_estimate(self):
|
||||
line = facets.season_basis_line(fake(1, hike=est_hike()))
|
||||
self.assertTrue(line.endswith("Confidence: medium. No page states a season."), line)
|
||||
|
||||
|
||||
class MissingValuesTest(unittest.TestCase):
|
||||
def recs(self, n_with, n_without):
|
||||
return ([fake(i, hike={"months": [7, 8], "season": "July and August", "terrain": ["alpine"]})
|
||||
@@ -189,22 +242,24 @@ class MissingValuesTest(unittest.TestCase):
|
||||
self.assertIn('name="terrain"', form)
|
||||
|
||||
def test_missing_count_is_said(self):
|
||||
# the generic mechanism, shown with terrain: no real trail lacks a season any more
|
||||
form = home.finder_form(self.recs(10, 12))
|
||||
self.assertIn('data-missing="season" hidden>12 trails have no season on file.', form)
|
||||
self.assertIn('data-missing="terrain" hidden>12 trails have no terrain on file.', form)
|
||||
self.assertEqual(facets.missing_text(1, "season"), "1 trail has no season on file.")
|
||||
self.assertEqual(facets.missing_text(0, "season"), "")
|
||||
self.assertEqual(facets.missing_text(1, "terrain"), "1 trail has no terrain on file.")
|
||||
self.assertEqual(facets.missing_text(0, "terrain"), "")
|
||||
# full coverage: no note
|
||||
self.assertNotIn('data-missing="season"', home.finder_form(self.recs(5, 0)))
|
||||
self.assertNotIn('data-missing="terrain"', home.finder_form(self.recs(5, 0)))
|
||||
|
||||
def test_rows_without_a_value_carry_none(self):
|
||||
# the script leaves out a row whose data-months is empty while a month is chosen
|
||||
row = home.entry(fake(1))
|
||||
self.assertIn('data-months=""', row)
|
||||
self.assertIn('data-terrain=""', row)
|
||||
row = home.entry(fake(1, hike={"months": [7, 8, 9]}))
|
||||
self.assertIn('data-months="7 8 9"', row)
|
||||
|
||||
def test_every_real_trail_has_months(self):
|
||||
for rec in records.load_records(ROOT):
|
||||
self.assertTrue(facets.months(rec), rec["id"])
|
||||
|
||||
def test_script_leaves_out_missing_values(self):
|
||||
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
|
||||
js = f.read()
|
||||
@@ -287,6 +342,31 @@ class BuiltVocabularyTest(unittest.TestCase):
|
||||
self.maxDiff = None
|
||||
self.assertEqual(bad[:40], [])
|
||||
|
||||
def test_no_page_says_only_some_trails_have_a_season(self):
|
||||
found = []
|
||||
for dirpath, _dirs, files in os.walk(OUT):
|
||||
for name in files:
|
||||
if name.endswith(".html") and "changelog" not in dirpath: # its old entries say what was
|
||||
path = os.path.join(dirpath, name)
|
||||
with open(path, encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
for phrase in ("Only some trails have a season", "season on file", "Not on file</td>",
|
||||
"data-unseasoned", "Show them"):
|
||||
if phrase in doc:
|
||||
found.append((os.path.relpath(path, OUT), phrase))
|
||||
self.assertEqual(found[:10], [])
|
||||
|
||||
def test_an_estimated_season_reads_about_on_its_page_and_a_stated_one_does_not(self):
|
||||
est = [r for r in records.load_records(ROOT) if facets.season_estimated(r)]
|
||||
stated = [r for r in records.load_records(ROOT) if not facets.season_estimated(r)]
|
||||
self.assertEqual(len(est) + len(stated), 223)
|
||||
for rec in est[:10]:
|
||||
doc = self.read(f"trails/{rec['id']}/index.html")
|
||||
self.assertIn(facets.season_text(rec), html.unescape(doc), rec["id"])
|
||||
self.assertIn("People do walk it outside these months.", html.unescape(doc), rec["id"])
|
||||
for rec in stated[:10]:
|
||||
self.assertNotIn("People do walk it outside these months.", html.unescape(self.read(f"trails/{rec['id']}/index.html")))
|
||||
|
||||
def test_navigation_has_four_sections_and_saved(self):
|
||||
doc = self.read("index.html")
|
||||
nav = re.search(r'<nav class="site-nav" aria-label="Main"><ul class="nav">(.*?)</ul></nav>', doc).group(1)
|
||||
|
||||
@@ -235,13 +235,13 @@ def rows_of(body):
|
||||
d = {k: html.unescape(v) for k, v in re.findall(r' data-([a-z]+)="([^"]*)"', attrs)}
|
||||
split = lambda v: [x for x in v.split(" ") if x] # noqa: E731
|
||||
out.append({"id": d["id"], "search": [" " + t + " " for t in d["search"].split("|")], "where": split(d["where"]), "km": float(d["km"]),
|
||||
"time": d["time"], "months": split(d["months"]), "terrain": split(d["terrain"]),
|
||||
"time": d["time"], "months": split(d["months"]), "estimate": d.get("estimate") == "yes", "terrain": split(d["terrain"]),
|
||||
"kind": d["kind"], "walking": d["walking"], "shape": d["shape"], "gpx": d["gpx"]})
|
||||
return out
|
||||
|
||||
|
||||
def state(**kw):
|
||||
s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "kind": "",
|
||||
s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "stated": False, "kind": "",
|
||||
"time": [], "terrain": [], "walking": [], "shape": [], "gpx": []}
|
||||
s.update(kw)
|
||||
return s
|
||||
@@ -366,45 +366,75 @@ class PanelInTheFlowTest(unittest.TestCase):
|
||||
self.assertIn("if (window.location.hash === '#filters') showPanels(true);", js)
|
||||
|
||||
|
||||
class UnseasonedNoteTest(unittest.TestCase):
|
||||
"""A month filter says how many trails it leaves out for having no season on file."""
|
||||
class LeaveOutEstimatesTest(unittest.TestCase):
|
||||
"""The month filter can leave estimated seasons out, and says nothing about trails with no season."""
|
||||
|
||||
def test_a_finder_list_has_the_note_and_it_starts_hidden(self):
|
||||
def test_the_month_field_has_the_checkbox_and_it_starts_disabled(self):
|
||||
recs = recordsmod.load_records(ROOT)
|
||||
body = str(home.results(recs, finder=True))
|
||||
self.assertIn('<p class="results-note" data-unseasoned hidden>', body)
|
||||
self.assertIn('data-unseasoned-show>Show them</button>', body)
|
||||
self.assertNotIn("data-unseasoned", str(home.results(recs)))
|
||||
form = home.finder_form(recs)
|
||||
field = form[form.index('data-facet="month"'):]
|
||||
field = field[:field.index("</div>")]
|
||||
self.assertIn('<input type="checkbox" name="stated" value="1" disabled>', field)
|
||||
self.assertIn("Leave out estimated seasons", field)
|
||||
|
||||
def test_the_script_counts_it_over_the_rows_of_the_list_and_show_them_clears_the_month(self):
|
||||
def test_there_is_no_checkbox_where_no_trail_has_an_estimated_season(self):
|
||||
recs = [r for r in recordsmod.load_records(ROOT) if not facets.season_estimated(r)]
|
||||
self.assertNotIn('name="stated"', home.finder_form(recs))
|
||||
|
||||
def test_the_results_have_no_unseasoned_note(self):
|
||||
recs = recordsmod.load_records(ROOT)
|
||||
for body in (str(home.results(recs, finder=True)), str(home.results(recs))):
|
||||
self.assertNotIn("data-unseasoned", body)
|
||||
self.assertNotIn("Show them", body)
|
||||
self.assertNotIn("no season on file", body)
|
||||
js = read(WEB, "assets", "app.js")
|
||||
self.assertIn("if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++;", js)
|
||||
self.assertIn("' trails with no season on file are not shown.'", js)
|
||||
self.assertIn("el.month.value = '';", js)
|
||||
self.assertNotIn("unseasoned", js.lower())
|
||||
self.assertNotIn("no season on file", js)
|
||||
|
||||
def test_a_row_carries_whether_its_season_is_an_estimate(self):
|
||||
est = next(r for r in recordsmod.load_records(ROOT) if facets.season_estimated(r))
|
||||
stated = next(r for r in recordsmod.load_records(ROOT) if not facets.season_estimated(r))
|
||||
self.assertIn('data-estimate="yes"', str(home.entry(est)))
|
||||
self.assertNotIn("data-estimate", str(home.entry(stated)))
|
||||
|
||||
def test_the_script_reads_the_checkbox_and_writes_it_in_the_address(self):
|
||||
js = read(WEB, "assets", "app.js")
|
||||
self.assertIn("if (s.month && s.stated && d.estimate) return false;", js)
|
||||
self.assertIn("if (s.month && s.stated) p.set('stated', '1');", js)
|
||||
self.assertIn("estimate: d.estimate === 'yes'", js)
|
||||
|
||||
@unittest.skipUnless(NODE, "node is not installed")
|
||||
def test_the_number_is_the_trails_that_pass_everything_else_and_have_no_season(self):
|
||||
recs = recordsmod.load_records(ROOT)
|
||||
rows = rows_of(home.render(recs, SITE, ROOT))
|
||||
def test_with_stated_on_estimated_rows_leave_the_month_and_the_counts_follow(self):
|
||||
def row(i, months, estimate):
|
||||
return {"id": f"t{i}", "search": [" ", " ", " ", " "], "where": [], "km": 100.0, "time": "week",
|
||||
"months": [str(m) for m in months], "estimate": estimate, "terrain": [], "kind": "trail", "walking": "",
|
||||
"shape": "", "gpx": "none"}
|
||||
rows = [row(1, [7], True), row(2, [7], False), row(3, [7, 8], False), row(4, [8], True)]
|
||||
off = run_counts(rows, state(month="7"))
|
||||
on = run_counts(rows, state(month="7", stated=True))
|
||||
self.assertEqual((off["total"], off["month"]["7"], off["month"]["8"]), (3, 3, 2))
|
||||
self.assertEqual((on["total"], on["month"]["7"], on["month"]["8"]), (2, 2, 1))
|
||||
# with no month chosen it does nothing
|
||||
self.assertEqual(run_counts(rows, state(stated=True))["total"], 4)
|
||||
# and the shown number is the rows that pass
|
||||
prog = facet_count_source() + """
|
||||
var input = JSON.parse(require('fs').readFileSync(0, 'utf8'));
|
||||
input.s.max = Infinity;
|
||||
var n = 0, shown = 0;
|
||||
input.rows.forEach(function (d) {
|
||||
if (FacetCount.passes(d, input.s, '')) shown++;
|
||||
else if (!d.months.length && FacetCount.passes(d, input.s, 'month')) n++;
|
||||
});
|
||||
process.stdout.write(JSON.stringify([shown, n]));
|
||||
process.stdout.write(JSON.stringify(input.rows.filter(function (d) { return FacetCount.passes(d, input.s, ''); }).length));
|
||||
"""
|
||||
for s in (state(month="8"), state(month="8", kind="route"), state(month="8", where="US-CA")):
|
||||
out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": s}),
|
||||
capture_output=True, text=True, check=True)
|
||||
shown, n = json.loads(out.stdout)
|
||||
def base(r):
|
||||
return ((not s["kind"] or facets.kind(r) == s["kind"])
|
||||
and (not s["where"] or s["where"] in facets.where_tokens(r)))
|
||||
self.assertEqual(shown, sum(1 for r in recs if base(r) and 8 in facets.months(r)))
|
||||
self.assertEqual(n, sum(1 for r in recs if base(r) and not facets.months(r)))
|
||||
out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": state(month="7", stated=True)}),
|
||||
capture_output=True, text=True, check=True)
|
||||
self.assertEqual(json.loads(out.stdout), on["total"])
|
||||
|
||||
@unittest.skipUnless(NODE, "node is not installed")
|
||||
def test_on_the_real_trails_the_counts_leave_out_exactly_the_estimates(self):
|
||||
recs = recordsmod.load_records(ROOT)
|
||||
rows = rows_of(home.render(recs, SITE, ROOT))
|
||||
for month in (1, 7):
|
||||
c = run_counts(rows, state(month=str(month), stated=True))
|
||||
want = sum(1 for r in recs if month in facets.months(r) and not facets.season_estimated(r))
|
||||
self.assertEqual(c["total"], want)
|
||||
self.assertEqual(c["month"][str(month)], want)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+25
-2
@@ -137,6 +137,29 @@ class TrailPageTest(unittest.TestCase):
|
||||
self.assertNotIn("The season comes from", trail.hike_sources_block(rec))
|
||||
self.assertEqual(facets.season_basis(rec), "")
|
||||
|
||||
def test_an_estimated_season_row_carries_the_note(self):
|
||||
rec = sample_record("X Trail")
|
||||
rec["hike"] = dict(FULL_HIKE, season="April to October", months=[4, 5, 6, 7, 8, 9, 10],
|
||||
season_basis="estimate",
|
||||
season_method="Judged from the climate at the trail's elevation and from similar "
|
||||
"trails. Snow and mud last into March. Confidence: high.")
|
||||
t = text(top_part(render(rec)))
|
||||
self.assertIn("Season About April to October", t)
|
||||
self.assertIn("No page states a season.", t)
|
||||
self.assertIn("Confidence: high.", t)
|
||||
self.assertIn("People do walk it outside these months.", t)
|
||||
self.assertIn("No source gives a season; the climate suggests about April to October.", t)
|
||||
self.assertNotIn("The usual season is", t)
|
||||
block = html.unescape(trail.hike_sources_block(rec))
|
||||
self.assertIn("Snow and mud last into March. Confidence: high. No page states a season.", block)
|
||||
|
||||
def test_a_stated_season_row_has_no_note(self):
|
||||
rec = sample_record("X Trail")
|
||||
rec["hike"] = dict(FULL_HIKE, season_basis="primary")
|
||||
t = text(top_part(render(rec)))
|
||||
self.assertIn("Season March to October", t)
|
||||
self.assertNotIn("No page states a season", t)
|
||||
|
||||
def test_partial_hike_table(self):
|
||||
rec = sample_record("X Trail")
|
||||
rec["hike"] = {"shape": "loop", "start": "Lake Camp", "days": [4, 6], "checked": "2026-11-13"}
|
||||
@@ -144,7 +167,7 @@ class TrailPageTest(unittest.TestCase):
|
||||
t = text(top)
|
||||
self.assertIn("Shape Loop. Starts and ends at Lake Camp", t)
|
||||
self.assertIn("Time 4 to 6 days", t)
|
||||
self.assertIn("Season, terrain, walking and permits are not on file for this trail yet.", t)
|
||||
self.assertIn("Terrain, walking and permits are not on file for this trail yet.", t)
|
||||
for absent in ("Season March", "High point", "Terrain Alpine", "Permits", "Not finished", "Official site"):
|
||||
self.assertNotIn(absent, t, absent)
|
||||
# no summary: the lede is built from the record
|
||||
@@ -175,7 +198,7 @@ class TrailPageTest(unittest.TestCase):
|
||||
self.assertIn("Where Arizona , United States", t)
|
||||
# every trail has a time: here estimated from its 100 km, and labelled so
|
||||
self.assertIn("Time About 4 to 5 days Estimated from the length, at 12 to 19 mi 20 to 30 km a day.", t)
|
||||
self.assertIn("Season, terrain, walking and permits are not on file for this trail yet.", t)
|
||||
self.assertIn("Terrain, walking and permits are not on file for this trail yet.", t)
|
||||
self.assertNotIn("Where the hiking facts come from", body)
|
||||
# no track: the page says so plainly and points at the source
|
||||
self.assertIn("No GPX here", t)
|
||||
|
||||
@@ -201,6 +201,17 @@ class JsonLdTest(unittest.TestCase):
|
||||
count += 1
|
||||
self.assertEqual(count, len(self.records))
|
||||
|
||||
def test_no_estimated_season_appears_in_structured_data(self):
|
||||
seen = 0
|
||||
for rec in self.records:
|
||||
h = rec.get("hike", {})
|
||||
if not (h.get("season_basis") == "estimate" or h.get("season_method")):
|
||||
continue
|
||||
seen += 1
|
||||
page = self.pages[f"trails/{rec['id']}/index.html"]
|
||||
self.assertNotIn("Usual season", page, rec["id"])
|
||||
self.assertGreater(seen, 0)
|
||||
|
||||
def test_a_trail_states_only_what_its_record_holds(self):
|
||||
built_derived = {r["id"]: r["derived"] for r in json.loads(read("data/trails.json"))}
|
||||
for rec in self.records:
|
||||
@@ -211,7 +222,9 @@ class JsonLdTest(unittest.TestCase):
|
||||
self.assertEqual(props[("Published length", "KMT")]["value"], rec["length_km"], rec["id"])
|
||||
h = rec.get("hike", {})
|
||||
self.assertEqual(("Start", None) in props, bool(h.get("start")), rec["id"])
|
||||
self.assertEqual(("Usual season", None) in props, bool(h.get("season")), rec["id"])
|
||||
self.assertEqual(("Usual season", None) in props,
|
||||
bool(h.get("season") and h.get("season_basis") != "estimate" and not h.get("season_method")),
|
||||
rec["id"])
|
||||
self.assertEqual(any(k[0] == "Highest point" for k in props),
|
||||
bool(h.get("high_point_m") or h.get("high_point")), rec["id"])
|
||||
if h.get("official_url"):
|
||||
|
||||
+25
-4
@@ -16,7 +16,7 @@ WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import common, docs, hike, records, seo, site, trail # noqa: E402
|
||||
from olt import common, docs, facets, hike, records, seo, site, trail # noqa: E402
|
||||
|
||||
SITE = site.load()
|
||||
|
||||
@@ -160,6 +160,21 @@ class InBrief(unittest.TestCase):
|
||||
("range", "The usual season is spring and fall"))
|
||||
self.assertIsNone(season("Best travelled " + "in the later part of the summer " * 5))
|
||||
|
||||
def test_an_estimated_season_sentence_says_no_source_gives_one(self):
|
||||
rec = sparse_record()
|
||||
rec["hike"] = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate",
|
||||
"season_method": "Judged from the climate. Snow. Confidence: low."}
|
||||
self.assertEqual(trail.season_sentence(rec),
|
||||
("estimate", "No source gives a season; the climate suggests about June to September"))
|
||||
rec["hike"]["season_basis"] = "sources"
|
||||
self.assertEqual(trail.season_sentence(rec),
|
||||
("estimate", "The pages differ on the season; it is judged to be about June to September"))
|
||||
rec["hike"].update(season="All year", months=list(range(1, 13)), season_basis="estimate")
|
||||
self.assertEqual(trail.season_sentence(rec)[1], "No source gives a season; the climate suggests about all year")
|
||||
# the sentence stands alone: it is never joined to the GPX clause with "and"
|
||||
paragraph = " ".join(trail.brief_sentences(rec))
|
||||
self.assertIn("No source gives a season; the climate suggests about all year.", paragraph)
|
||||
|
||||
def test_a_permit_is_said_only_when_it_is_short(self):
|
||||
short = sparse_record()
|
||||
short["hike"] = {"permit": "No permit is needed to hike it."}
|
||||
@@ -217,7 +232,8 @@ class InBrief(unittest.TestCase):
|
||||
s = self.sentences(rec)
|
||||
paragraph = " ".join(s)
|
||||
self.assertGreaterEqual(len(s), 2, rec["id"])
|
||||
self.assertLessEqual(len(s), 4, rec["id"])
|
||||
# four sentences, and a fifth where the season is an estimate, which is always said
|
||||
self.assertLessEqual(len(s), 4 + facets.season_estimated(rec), rec["id"])
|
||||
self.assertIn("GPX", paragraph, rec["id"])
|
||||
self.assertNotRegex(paragraph, r"\b(Season|Permits are noted)\b", rec["id"])
|
||||
for bad in ("None", "{", "}", " ", " ,", " .", "unknown", "not known", "n/a"):
|
||||
@@ -232,8 +248,13 @@ class InBrief(unittest.TestCase):
|
||||
self.assertIn("usually takes", paragraph, rec["id"])
|
||||
else:
|
||||
self.assertNotIn("usually takes", paragraph, rec["id"])
|
||||
if not (h.get("season") or h.get("months")):
|
||||
self.assertNotRegex(paragraph, r"usual season|walked all year|Northbound|season", rec["id"])
|
||||
self.assertTrue(h.get("season"), rec["id"])
|
||||
if facets.season_estimated(rec):
|
||||
self.assertIn("No source gives a season" if not facets.season_pages_differ(rec)
|
||||
else "The pages differ on the season", paragraph, rec["id"])
|
||||
self.assertNotIn("The usual season is", paragraph, rec["id"])
|
||||
else:
|
||||
self.assertNotIn("No source gives a season", paragraph, rec["id"])
|
||||
if "No permit" in paragraph or "permit" in paragraph.lower():
|
||||
self.assertIn(common.sentence(h.get("permit", "")), paragraph, rec["id"])
|
||||
self.assertEqual("highest point" in paragraph,
|
||||
|
||||
+58
-2
@@ -8,6 +8,7 @@ These do not need the built site.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from html import unescape as html_unescape
|
||||
import shutil
|
||||
import tempfile
|
||||
import sys
|
||||
@@ -117,7 +118,7 @@ class MonthListTest(unittest.TestCase):
|
||||
self.assertEqual(keys(recs, "hike-in-july"), ["t1"])
|
||||
self.assertEqual(keys(recs, "hike-in-august"), ["t2"])
|
||||
|
||||
def test_a_month_needs_eight_trails_and_says_how_many_have_a_season(self):
|
||||
def test_a_month_needs_eight_trails(self):
|
||||
july = browse.by_key("hike-in-july")
|
||||
self.assertEqual(july.min_size, 8)
|
||||
self.assertFalse(browse.is_shown(7, 100, july.min_size))
|
||||
@@ -126,8 +127,35 @@ class MonthListTest(unittest.TestCase):
|
||||
shown = {lst.key for lst, _ in browse.shown(recs)}
|
||||
self.assertIn("hike-in-july", shown)
|
||||
self.assertNotIn("hike-in-august", shown)
|
||||
|
||||
def est(self, i, months=(7,)):
|
||||
return fake(i, hike={"months": list(months), "season": "July", "season_basis": "estimate",
|
||||
"season_method": "Judged. Confidence: low."})
|
||||
|
||||
def test_a_month_note_counts_stated_and_estimated_exactly(self):
|
||||
july = browse.by_key("hike-in-july")
|
||||
recs = [fake(i, hike={"months": [7], "season": "July", "season_basis": "primary"}) for i in range(10)] \
|
||||
+ [self.est(20 + i) for i in range(5)]
|
||||
note = july.note(browse.members(july, recs), recs)
|
||||
self.assertIn("Only 10 of the 20 trails have a season on file", note)
|
||||
self.assertEqual(note, "A source states the season for 10 of these. For the other 5 it is estimated "
|
||||
"from climate, and marked.")
|
||||
|
||||
def test_a_month_list_with_no_estimates_says_so(self):
|
||||
july = browse.by_key("hike-in-july")
|
||||
recs = [fake(i, hike={"months": [7], "season": "July", "season_basis": "primary"}) for i in range(10)]
|
||||
self.assertEqual(july.note(browse.members(july, recs), recs), "A source states the season for all 10.")
|
||||
recs = [self.est(i) for i in range(3)]
|
||||
self.assertEqual(july.note(browse.members(july, recs), recs),
|
||||
"No source states the season for these, so each is estimated from climate.")
|
||||
|
||||
def test_the_month_blurb_no_longer_says_only_some_trails(self):
|
||||
group = {key: blurb for key, _title, blurb in browse.GROUPS}["month"]
|
||||
self.assertEqual(group, "Trails normally hiked in the month. Estimated seasons are marked.")
|
||||
self.assertEqual(browse.by_key("hike-in-july").blurb,
|
||||
"Trails normally hiked in July. Estimated seasons are marked.")
|
||||
for lst in browse.LISTS:
|
||||
self.assertNotIn("Only some trails", lst.blurb)
|
||||
self.assertNotIn("season on file", lst.blurb)
|
||||
|
||||
def test_every_list_has_a_group_and_every_group_a_heading(self):
|
||||
headings = {k for k, _, _ in browse.GROUPS}
|
||||
@@ -628,6 +656,34 @@ class RealDataTest(unittest.TestCase):
|
||||
n_ver = len(reference.verified(self.records))
|
||||
self.assertIn(f"{n_ver} of the {len(self.records)} trails have a track", str(body))
|
||||
|
||||
def method_text(self):
|
||||
title, desc, body = reference.method_page(self.records, SITE, ROOT)
|
||||
return re.sub(r"\s+", " ", html_unescape(re.sub(r"<[^>]+>", " ", str(body))))
|
||||
|
||||
def test_the_reference_page_counts_stated_and_estimated_seasons(self):
|
||||
text = self.method_text()
|
||||
kinds = {k: sum(1 for r in self.records if facets.season_kind(r) == k) for k in ("stated", "judged", "estimated")}
|
||||
self.assertEqual(sum(kinds.values()), len(self.records))
|
||||
self.assertIn(f"A season a page states Records with it {kinds['stated']} Records without {len(self.records) - kinds['stated']}", text)
|
||||
self.assertIn(f"A season estimated from climate Records with it {kinds['estimated']} Records without {len(self.records) - kinds['estimated']}", text)
|
||||
self.assertIn(f"A season set from pages that differ Records with it {kinds['judged']} Records without {len(self.records) - kinds['judged']}", text)
|
||||
self.assertIn(f"All trails Trails {len(self.records)}", text)
|
||||
|
||||
def test_the_reference_page_gives_the_blind_test_from_its_file(self):
|
||||
blind = datafiles.blind_test(ROOT)
|
||||
text = self.method_text()
|
||||
self.assertIn(f"the method was run blind on {blind['tested']} trails whose seasons a page does state", text)
|
||||
self.assertIn(f"It matched {blind['matched']} of them ({round(blind['share'] * 100)} percent) within one month at "
|
||||
"each end", text)
|
||||
for name, v in blind["by_confidence"].items():
|
||||
self.assertIn(f"{name} {v['matched']} of {v['tested']} ({round(v['share'] * 100)} percent)", text)
|
||||
self.assertIn("not a promise for any one trail", text)
|
||||
|
||||
def test_the_glossary_no_longer_says_only_some_records_state_a_season(self):
|
||||
season = next(t for t in reference.terms(ROOT) if t["id"] == "season")
|
||||
self.assertNotIn("Only some", season["definition"])
|
||||
self.assertIn("estimated", season["definition"])
|
||||
|
||||
def test_every_place_page_has_a_summary_paragraph(self):
|
||||
by_slug, _ = regions.collect_regions(self.records)
|
||||
for slug in by_slug:
|
||||
|
||||
Reference in new issue
Block a user