Site: show precomputed statistics; drop the upload and the click-to-select route map (#12)

Step 4a of the Python-first core.

- analysis/stats/measures.yaml (declarative): outcomes and denominators, route targets and
  comparison groups, encounter contexts, the route map's stages, six filter presets and the
  route thresholds (5, 10, 20, 30).
- analysis/stats/site_stats.py computes every number the page shows, for every preset, and
  writes data/public/stats.json: factor tables, models, chance events, encounters, the route map
  for every outcome, route rankings with q-values at every threshold, the valley map's place and
  step counts, and The Odds' summary cards.
- The page now only displays: app.js, ui.js and explorer.js read stats.json; engine.js is no
  longer loaded. The three filter controls become one "Runs" menu; minimum runs become fixed
  thresholds. Removed: "Load a newer route export", click-to-select and "Follow" on the Deep
  Dive route map, and the unused old valley renderer. The coded runs are a CSV download.
- tests/parity/compare_stats.py: every number matches what engine.js computed, for all six
  presets (factor tables, models, encounters, route rankings at every threshold, route map).


Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ekcSchiano
2026-11-03 21:37:10 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 963b08c522
commit d04b88e7b4
14 changed files with 866 additions and 424 deletions
+78 -155
View File
@@ -1,17 +1,26 @@
/* app.js — renders the Threshing Route Atlas from engine.js results. All numbers come from ThreshEngine. */
/* app.js — renders the Threshing Route Atlas. Every number comes precomputed from data/stats.json
(analysis/stats/site_stats.py); this file only displays them. */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const NS = "http://www.w3.org/2000/svg";
const state = {
raw: null, bundled: null, allRuns: [], runs: [], res: null, missing: [],
filters: { source: "all", goal: "all", excludeFlagged: false },
target: "bond_any", widthMode: "traffic", minN: 10, conds: {},
stats: null, preset: "all", P: null, res: null,
target: "bond_any", widthMode: "traffic", minN: 10,
fxOutcome: "blue_meadow", fxFactor: "resolution", rtTarget: "see_Blue", rtMin: 10,
};
const META = () => state.stats.meta;
const TARGET = (t) => META().targets[t];
const MISSING = () => new Set(META().missing_values);
const isMissing = (v) => v === null || v === undefined || v === "" || MISSING().has(v);
/** A precomputed route ranking at one of the fixed thresholds: rows with at least minN runs, their q-values. */
function routesAt(target, minN) {
const R = state.P.routes[target], b = R.by_threshold[String(minN)];
const rows = R.rows.map((r, i) => ({ ...r, q: b.q[i], mh_q: b.mh_q[i] })).filter((r) => r.n >= minN);
return { target, overall: R.overall, minN, n_routes_tested: b.n_routes_tested, rows };
}
// ------------------------------------------------------------ formatting
const pct = (p, d = 1) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(p > 0 && p < 0.001 ? 2 : d) + "%");
@@ -38,7 +47,7 @@
}
const DRAGON_VAR = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const dragonColor = (c) => cssVar(DRAGON_VAR[c] || "--dr-any");
const targetColor = (t) => dragonColor(E.TARGETS[t].color);
const targetColor = (t) => dragonColor(TARGET(t).color);
function svgEl(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
@@ -73,42 +82,22 @@
const hideTip = () => (tip.hidden = true);
// ------------------------------------------------------------ data loading
async function loadBundled() {
const resp = await fetch("data/form_responses.json");
const raw = await resp.json();
state.bundled = raw;
useRaw(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`);
}
function useRaw(raw, label) {
const { runs, missing } = E.codeRows(raw.rows, raw.headers);
state.raw = raw; state.allRuns = runs; state.missing = missing; state.dataLabel = label;
state.conds = {};
async function loadStats() {
state.stats = await (await fetch("data/stats.json")).json();
const sel = $("#f-preset");
sel.innerHTML = Object.entries(META().presets).map(([k, l]) => `<option value="${k}">${esc(l)}</option>`).join("");
sel.value = state.preset;
const th = META().route_thresholds;
for (const id of ["#minn", "#rt-min"]) {
$(id).innerHTML = th.map((m) => `<option value="${m}">${m}</option>`).join("");
$(id).value = String(state.minN);
}
recompute();
}
$("#upload").addEventListener("change", async (e) => {
const f = e.target.files[0];
if (!f) return;
try {
const buf = await f.arrayBuffer();
const wb = XLSX.read(buf, { type: "array", cellDates: true });
const name = wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0];
const ws = wb.Sheets[name];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
useRaw({ rows, headers, source_file: f.name, exported: new Date().toISOString().slice(0, 10) }, `uploaded file ${f.name} (sheet "${name}")`);
$("#btn-reset-data").hidden = false;
toast(`Loaded ${rows.length} rows from ${f.name}`);
} catch (err) {
toast("That file could not be read. Export the responses sheet as .xlsx or .csv and try again.");
console.error(err);
}
e.target.value = "";
});
$("#btn-reset-data").addEventListener("click", () => { useRaw(state.bundled, `bundled snapshot (${state.bundled.source_file}, exported ${state.bundled.exported})`); $("#btn-reset-data").hidden = true; });
function recompute() {
state.runs = E.applyFilters(state.allRuns, state.filters);
state.res = E.analyse(state.allRuns, state.filters);
state.P = state.stats.presets[state.preset];
state.res = state.P.analyse;
renderAll();
}
@@ -116,17 +105,13 @@
function renderStatus() {
const m = state.res.meta;
const src = Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v.toLocaleString()}`).join(" · ");
const filt = [];
if (state.filters.source !== "all") filt.push(state.filters.source === "form" ? "form submissions only" : "bulk logs only");
if (state.filters.goal !== "all") filt.push(state.filters.goal === "exclude_rare" ? "not chasing Blue/Black" : "chasing Blue/Black");
if (state.filters.excludeFlagged) filt.push("flagged rows dropped");
const total = state.stats.data.runs;
$("#data-status").innerHTML = `
<span><b>${state.res.n.toLocaleString()}</b> runs${state.res.n !== state.allRuns.length ? ` of ${state.allRuns.length.toLocaleString()}` : ""}</span>
<span><b>${state.res.n.toLocaleString()}</b> runs${state.res.n !== total ? ` of ${total.toLocaleString()}` : ""}</span>
<span>${esc(src)}</span>
<span>Form dates ${m.date_min || "?"} → ${m.date_max || "?"}</span>
<span class="pill">${esc(state.dataLabel)}</span>
${filt.length ? `<span class="pill warn">Filtered: ${esc(filt.join(", "))}</span>` : ""}
${state.missing.length ? `<span class="pill warn">Questions not found in this file: ${esc(state.missing.join(", "))}</span>` : ""}`;
<span class="pill">Snapshot of the community form${state.stats.data.exported ? `, exported ${esc(state.stats.data.exported)}` : ""}</span>
${state.preset !== "all" ? `<span class="pill warn">Showing: ${esc(state.P.label)}</span>` : ""}`;
}
// ------------------------------------------------------------ findings
@@ -158,7 +143,7 @@
const mb = r.models.blue_meadow;
if (mb) {
const sig = mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level));
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const rk = routesAt("see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q !== undefined && x.mh_q < 0.05);
let t = sig.length
? `<p><b>After adjusting for reporting bias, ${sig.length === 1 ? "one recorded choice was" : sig.length + " recorded choices were"} linked to the Blue appearing:</b> ${sig.map((s) => `${esc(labelFactor(s.factor))}: ${esc(s.level)} (OR ${fmtOR(s.or)}, 95% CI ${fmtOR(s.lo)}–${fmtOR(s.hi)}, p = ${fmtP(s.p)})`).join("; ")}.</p>`
@@ -171,8 +156,7 @@
}
if (cs.overall.n) {
const bulkS = stratumRate(cs, "Bulk"), formS = Object.entries(cs.by_stratum).filter(([k]) => k.startsWith("Form"));
const fk = formS.reduce((a, [, w]) => a + w.k, 0), fn = formS.reduce((a, [, w]) => a + w.n, 0);
const fw = E.wilson(fk, fn);
const fw = cs.form_overall, fn = fw.n;
let t = `<p><b>The tree shadow showed up in ${rateTxt(cs.overall)} of logged tree climbs.</b>${fn ? ` Form submissions: ${rateTxt(fw)}.` : ""}`;
if (bulkS && bulkS.n >= 30 && fn >= 30 && fw.lo > bulkS.hi) t += ` Bulk logs: ${rateTxt(bulkS)}. Those two cannot both be the true rate for the same game. The form figure is the one exposed to selective reporting, so the true rate is probably nearer the bulk logs, whose 95% upper bound is ${pct(bulkS.hi)} per climb.`;
t += `</p>`;
@@ -213,8 +197,8 @@
const OTHER_T = ["see_Blue", "see_shadow"];
function renderTargets() {
const chip = (t, featured) => {
const c = E.TARGETS[t].color ? DRAGON_VAR[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${featured ? " featured" : ""}" data-t="${t}" aria-pressed="${state.target === t}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
const c = TARGET(t).color ? DRAGON_VAR[TARGET(t).color] : "--dr-any";
return `<button type="button" class="tchip${featured ? " featured" : ""}" data-t="${t}" aria-pressed="${state.target === t}" style="--c: var(${c})"><span class="sw"></span>${esc(TARGET(t).label)}</button>`;
};
$("#targets-rare").innerHTML = RARE_T.map((t) => chip(t, false)).join("");
$("#targets-other").innerHTML = OTHER_T.map((t) => chip(t, false)).join("");
@@ -237,25 +221,24 @@
"Tree: shadow → Blue/Black": "Tree: shadow (Blue→Black)", "Meadow (no attempt recorded)": "Meadow: none recorded", "Unknown → Unknown": "Unknown",
};
const short = (v) => SHORT[v] || v;
const condSets = () => Object.fromEntries(Object.entries(state.conds).map(([k, v]) => [k, new Set(v)]));
function renderMap() {
const svg = $("#map");
svg.innerHTML = "";
const runs = state.runs;
const base = E.buildGraph(runs, state.target, {});
const sel = E.buildGraph(runs, state.target, condSets());
const hasSel = Object.values(state.conds).some((v) => v.length);
const selNode = new Map(sel.nodes.map((n) => [n.id, n]));
// the precomputed route map, with the chosen outcome's counts and intervals on every box and band
const G = state.P.map, BT = G.by_target[state.target];
const sel = { nodes: G.nodes.map((n, i) => ({ ...n, ...BT.nodes[i] })), links: G.links.map((l, i) => ({ ...l, ...BT.links[i] })) };
const base = sel;
const STAGES = META().stages;
const minN = state.minN;
const tcol = targetColor(state.target), low = cssVar("--link-low"), surface = cssVar("--raised");
const shell = $(".map-scroll");
const W = Math.max(1440, shell.clientWidth || 1440), H = 660, top = 40, bottom = 16, left = 10, right = 168, nodeW = 12;
svg.setAttribute("width", W); svg.setAttribute("height", H); svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const S = E.STAGES.length;
const S = STAGES.length;
const colX = (i) => left + (i * (W - left - right - nodeW)) / (S - 1);
const cols = E.STAGES.map((s, i) => {
const cols = STAGES.map((s, i) => {
const ns = base.nodes.filter((n) => n.stage === i);
const ord = ORDER[s.key];
ns.sort((a, b) => {
@@ -284,8 +267,8 @@
const colorFor = (o) => (o.n < minN ? low : mix(low, tcol, Math.pow(Math.min(1, o.p / pmax), 0.75)));
// stage headers
E.STAGES.forEach((s, i) => {
const chance = s.key === "first_sighting" || s.key === "encounter";
STAGES.forEach((s, i) => {
const chance = s.chance;
const t = svgEl("text", { x: colX(i), y: 18, class: "stage-label" + (chance ? " stage-chance" : "") }, svg);
t.textContent = s.label;
if (chance) { const r = svgEl("text", { x: colX(i), y: 31, class: "stage-label stage-chance" }, svg); r.textContent = "game roll"; }
@@ -322,7 +305,7 @@
el = svgEl("path", { d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}`, fill: "none", stroke: colorFor(l), "stroke-width": w, "stroke-opacity": l.n >= minN ? 0.8 : 0.3, "stroke-linecap": "round", class: "link" }, gLinks);
}
const sv = pos.get(l.source).n.value, tv = pos.get(l.target).n.value;
el.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${esc(sv)} → ${esc(tv)}</div>${l.n} runs${hasSel ? " (in your selection)" : ""}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(l.p)}</b> (${kn(l)})<br>95% CI ${ci(l)}${l.n < minN ? "<br><i>Too few runs to read</i>" : ""}`));
el.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${esc(sv)} → ${esc(tv)}</div>${l.n} runs<br>${esc(TARGET(state.target).label)}: <b>${pct(l.p)}</b> (${kn(l)})<br>95% CI ${ci(l)}${l.n < minN ? "<br><i>Too few runs to read</i>" : ""}`));
el.addEventListener("mouseleave", hideTip);
});
@@ -331,66 +314,26 @@
cols.forEach((ns, i) => {
let lastLabelBottom = -1e9;
ns.forEach((bn) => {
const p = pos.get(bn.id), sn = selNode.get(bn.id);
const isSel = (state.conds[E.STAGES[i].key] || []).includes(bn.value);
const g = svgEl("g", { class: "node" + (isSel ? " sel" : "") + (hasSel && !sn ? " dim" : ""), tabindex: 0, role: "button", "aria-label": `${E.STAGES[i].label}: ${bn.value}, ${bn.n} runs` }, gNodes);
const shown = sn || { n: 0, k: 0, p: null };
svgEl("rect", { x: p.x, y: p.y, width: nodeW, height: p.h, rx: 2, fill: sn ? colorFor(sn) : low }, g);
const p = pos.get(bn.id), sn = bn;
const g = svgEl("g", { class: "node", tabindex: 0, "aria-label": `${STAGES[i].label}: ${bn.value}, ${bn.n} runs` }, gNodes);
svgEl("rect", { x: p.x, y: p.y, width: nodeW, height: p.h, rx: 2, fill: colorFor(sn) }, g);
const lx = p.x + nodeW + 5, ly = p.y + p.h / 2 + 4;
if (ly - 11 > lastLabelBottom || isSel) {
if (ly - 11 > lastLabelBottom) {
const t = svgEl("text", { x: lx, y: ly, "paint-order": "stroke", stroke: surface, "stroke-width": 3, "stroke-linejoin": "round" }, g);
const lab = short(bn.value), maxC = i === S - 1 ? 30 : Math.floor((colX(1) - colX(0) - nodeW - 36) / 5.8);
t.textContent = lab.length > maxC ? lab.slice(0, maxC - 1) + "…" : lab;
const t2 = svgEl("tspan", { fill: cssVar("--muted"), dx: 4 }, t);
t2.textContent = sn && sn.n >= minN ? pct(sn.p, 0) : sn ? `n=${sn.n}` : "";
t2.textContent = sn.n >= minN ? pct(sn.p, 0) : `n=${sn.n}`;
lastLabelBottom = ly;
}
const html = () => `<div class="t">${esc(E.STAGES[i].label)}: ${esc(bn.value)}</div>${hasSel ? `${shown.n} of ${bn.n} runs in your selection` : `${bn.n} runs`}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(shown.p)}</b> (${shown.k}/${shown.n})<br>95% CI ${ci(sn)}<br><span class="muted">Click to ${isSel ? "remove from" : "add to"} the selection</span>`;
const html = () => `<div class="t">${esc(STAGES[i].label)}: ${esc(bn.value)}</div>${bn.n} runs<br>${esc(TARGET(state.target).label)}: <b>${pct(sn.p)}</b> (${sn.k}/${sn.n})<br>95% CI ${ci(sn)}`;
g.addEventListener("mousemove", (e) => showTip(e, html()));
g.addEventListener("focus", (e) => { const r = e.target.getBoundingClientRect(); showTip({ clientX: r.right, clientY: r.top }, html()); });
g.addEventListener("mouseleave", hideTip);
const toggle = () => {
const k = E.STAGES[i].key, cur = new Set(state.conds[k] || []);
cur.has(bn.value) ? cur.delete(bn.value) : cur.add(bn.value);
state.conds[k] = [...cur];
if (!state.conds[k].length) delete state.conds[k];
hideTip(); renderMap();
};
g.addEventListener("click", toggle);
g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggle(); } });
g.addEventListener("blur", hideTip);
});
});
renderCondChips(); renderSelSummary(sel); renderLegend(pmax, tcol, low);
}
function renderCondChips() {
const entries = Object.entries(state.conds).filter(([, v]) => v.length);
$("#cond-chips").innerHTML = entries.length
? entries.map(([k, vals]) => vals.map((v) => `<span class="cchip">${esc(E.STAGES.find((s) => s.key === k).label)}: ${esc(v)}<button type="button" aria-label="Remove ${esc(v)}" data-k="${esc(k)}" data-v="${esc(v)}">×</button></span>`).join("")).join("")
: `<span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span>`;
$$("#cond-chips button").forEach((b) => b.addEventListener("click", () => {
state.conds[b.dataset.k] = (state.conds[b.dataset.k] || []).filter((v) => v !== b.dataset.v);
if (!state.conds[b.dataset.k].length) delete state.conds[b.dataset.k];
renderMap();
}));
}
function renderSelSummary(sel) {
const T = E.TARGETS[state.target];
const cs = condSets();
const inSel = (r) => Object.entries(cs).every(([k, set]) => !set.size || set.has(E.stageValue(r, k)));
const pool = state.runs.filter(T.pool);
const A = pool.filter(inSel), B = pool.filter((r) => !inSel(r));
const wa = E.wilson(A.filter(T.fn).length, A.length), wb = E.wilson(B.filter(T.fn).length, B.length);
const hasSel = Object.keys(state.conds).length > 0;
let cmp = "";
if (hasSel && A.length && B.length) {
const o = E.oddsRatio(wa.k, wa.n - wa.k, wb.k, wb.n - wb.k);
cmp = `<div>Everyone else: ${pct(wb.p)} (${kn(wb)}). Odds ratio ${fmtOR(o.or)} (95% CI ${fmtOR(o.or_lo)}–${fmtOR(o.or_hi)}), Fisher p = ${fmtP(o.fisher_p)}. This is unadjusted: if your selection mixes in a lot of Blue-chasers, expect it to look better than it is.</div>`;
}
$("#sel-summary").innerHTML = `
<span class="eyebrow">${hasSel ? "Your selection" : "All runs"} · ${esc(T.label)}</span>
<div><span class="big">${pct(wa.p)}</span> <span class="muted">${kn(wa)} runs that could reach it · 95% CI ${ci(wa)}</span></div>
${cmp}`;
renderLegend(pmax, tcol, low);
}
function renderLegend(pmax, tcol, low) {
@@ -402,22 +345,15 @@
}
function renderBestRoutes() {
const rk = E.rankRoutes(state.runs, state.target, state.minN);
const rk = routesAt(state.target, state.minN);
const rows = rk.rows.slice(0, 8);
const sigN = rk.rows.filter((r) => r.mh_q !== undefined && r.mh_q < 0.05 && r.mh_or > 1).length;
$("#best-routes").innerHTML = `<div class="panel">
<h3>Top routes for "${esc(E.TARGETS[state.target].label)}" <span class="small muted">routes with ≥ ${state.minN} runs, ranked by the lower end of the 95% interval</span></h3>
<h3>Top routes for "${esc(TARGET(state.target).label)}" <span class="small muted">routes with ≥ ${state.minN} runs, ranked by the lower end of the 95% interval</span></h3>
<p class="small">${rows.length ? `Overall rate in the comparison group: ${rateTxt(rk.overall)}. <b>${sigN} of ${rk.n_routes_tested} routes are better than the rest after adjusting for reporting bias and multiple testing.</b> ${sigN === 0 ? "Treat the ordering below as noise unless a newer export changes this." : ""}` : "No route has enough runs at this threshold. Lower the minimum."}</p>
${rows.length ? `<div class="tbl-wrap"><table><thead><tr><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">Adj. OR</th><th class="num">Adj. q</th><th></th></tr></thead><tbody>
${rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}"><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td><td><button type="button" data-i="${i}">Follow</button></td></tr>`).join("")}
${rows.length ? `<div class="tbl-wrap"><table><thead><tr><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">Adj. OR</th><th class="num">Adj. q</th></tr></thead><tbody>
${rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}"><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td></tr>`).join("")}
</tbody></table></div>` : ""}</div>`;
$$("#best-routes button[data-i]").forEach((b) => b.addEventListener("click", () => {
const r = rows[+b.dataset.i];
state.conds = {};
E.STAGES.slice(0, 6).forEach((s, i) => { if (r.values[i]) state.conds[s.key] = [r.values[i]]; });
renderMap();
$("#map-sec").scrollIntoView({ behavior: "smooth" });
}));
}
// ------------------------------------------------------------ small charts
@@ -488,10 +424,10 @@
const blueCol = dragonColor("Blue"), blackCol = dragonColor("Black");
const strataRows = (c, col) => [{ label: "All rows", ...c.overall, color: cssVar("--ink") }].concat(
STRATUM_ORDER.filter((s) => c.by_stratum[s]).map((s) => ({ label: s, ...c.by_stratum[s], color: col })),
Object.entries(c.by_attempt).filter(([k]) => !E.isMissing(k)).map(([k, w]) => ({ label: k, ...w, color: cssVar("--accent") })));
Object.entries(c.by_attempt).filter(([k]) => !isMissing(k)).map(([k, w]) => ({ label: k, ...w, color: cssVar("--accent") })));
ciBars($("#ch-blue-strata"), strataRows(r.chance.blue_meadow, blueCol), { labelW: 180 });
ciBars($("#ch-shadow-strata"), strataRows(r.chance.shadow, blackCol), { labelW: 180 });
const termsOf = (m, skip = []) => (m ? m.terms.filter((t) => t.n >= 5 && !skip.includes(t.factor) && !E.isMissing(t.level)) /* the "goal not asked" stratum stays in the model as an adjustment, but is not a finding */.map((t) => ({ label: `${labelFactor(t.factor)}: ${t.level}`, or: t.or, lo: t.lo, hi: t.hi, p: t.p, n: t.n })) : []);
const termsOf = (m, skip = []) => (m ? m.terms.filter((t) => t.n >= 5 && !skip.includes(t.factor) && !isMissing(t.level)) /* the "goal not asked" stratum stays in the model as an adjustment, but is not a finding */.map((t) => ({ label: `${labelFactor(t.factor)}: ${t.level}`, or: t.or, lo: t.lo, hi: t.hi, p: t.p, n: t.n })) : []);
const mb = r.models.blue_meadow, ms = r.models.shadow;
forest($("#ch-model-blue"), termsOf(mb));
forest($("#ch-model-shadow"), termsOf(ms));
@@ -513,11 +449,11 @@
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const x = (i) => l + (d.length === 1 ? (W - l - rgt) / 2 : (i * (W - l - rgt)) / (d.length - 1));
const panels = [
{ y0: top, y1: mid - 14, k: "blue_k", n: "meadow_n", col: dragonColor("Blue"), name: "Blue in meadow" },
{ y0: mid + 6, y1: H - bottom, k: "shadow_k", n: "tree_n", col: dragonColor("Black"), name: "Shadow at tree" },
{ y0: top, y1: mid - 14, w: "blue", col: dragonColor("Blue"), name: "Blue in meadow" },
{ y0: mid + 6, y1: H - bottom, w: "shadow", col: dragonColor("Black"), name: "Shadow at tree" },
];
panels.forEach((P) => {
const vals = d.map((r) => E.wilson(r[P.k], r[P.n]));
const vals = d.map((r) => r[P.w]);
const ymax = Math.min(1, Math.max(0.05, ...vals.filter((v) => v.n >= 5).map((v) => v.hi)));
const y = (v) => P.y1 - (v / ymax) * (P.y1 - P.y0);
const ga = svgEl("g", { class: "axis" }, svg);
@@ -559,11 +495,11 @@
box.innerHTML = `<h3>Bond rate once the encounter starts</h3><div class="chart" id="ch-enc-inner"></div>`;
ciBars($("#ch-enc-inner"), rows, { labelW: 220, max: 1, rowH: 22 });
const g = r.green_rescue;
const parts = [["Bonded a Green", g.bonded_green, dragonColor("Green")], ["Rescued, bonded the Orange", g.rescued_orange, dragonColor("Orange")], ["Rescued, bonded the Brown", g.rescued_brown, dragonColor("Brown")], ["Incinerated", g.incinerated, cssVar("--faint")], ["No outcome recorded", g.green_encounters - g.bonded_green - g.rescued_orange - g.rescued_brown - g.incinerated, cssVar("--line")]];
const parts = [["Bonded a Green", g.bonded_green, dragonColor("Green"), "bonded_green"], ["Rescued, bonded the Orange", g.rescued_orange, dragonColor("Orange"), "rescued_orange"], ["Rescued, bonded the Brown", g.rescued_brown, dragonColor("Brown"), "rescued_brown"], ["Incinerated", g.incinerated, cssVar("--faint"), "incinerated"], ["No outcome recorded", g.no_outcome, cssVar("--line"), "no_outcome"]];
const tot = g.green_encounters || 1;
$("#green-rescue").innerHTML = `<p class="small muted">${g.green_encounters} tree runs that descended slowly to the two Greens. A wrong answer sometimes brings an Orange or Brown swooping in to bond you instead.</p>
$("#green-rescue").innerHTML = `<p class="small muted">${g.green_encounters} tree runs that met the two Greens (climbing down slowly, or quickly and letting the Red pass). A wrong answer sometimes brings an Orange or Brown swooping in to bond you instead.</p>
<div style="display:flex;height:16px;border-radius:3px;overflow:hidden;border:1px solid var(--line)">${parts.map(([, n, c]) => `<span style="width:${(100 * n) / tot}%;background:${c}"></span>`).join("")}</div>
<div class="tbl-wrap"><table><tbody>${parts.map(([l, n, c]) => { const w = E.wilson(n, g.green_encounters); return `<tr><td><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:${c};margin-right:6px"></span>${l}</td><td class="num">${n}</td><td class="num">${pct(w.p)}</td><td class="num">${ci(w)}</td></tr>`; }).join("")}</tbody></table></div>`;
<div class="tbl-wrap"><table><tbody>${parts.map(([l, n, c, key]) => { const w = g.rates[key]; return `<tr><td><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:${c};margin-right:6px"></span>${l}</td><td class="num">${n}</td><td class="num">${pct(w.p)}</td><td class="num">${ci(w)}</td></tr>`; }).join("")}</tbody></table></div>`;
// "Unsure" / blank first sightings are missing information, not a colour: left out of the table and its totals
const cols = ["Red", "Orange", "Brown", "Green"];
const POOL = { "Alone|East": ["Red", "Orange"], "Alone|West": ["Red", "Brown", "Green"], "Alone|Center": ["Red", "Brown"], "1 Squadmate|East": ["Green", "Orange", "Red"], "1 Squadmate|West": ["Red", "Brown", "Green"], "1 Squadmate|Center": ["Red", "Brown"], "2 Squadmates|East": ["Red", "Orange"], "2 Squadmates|West": ["Green", "Brown", "Red"], "2 Squadmates|Center": ["Red", "Brown"] };
@@ -574,12 +510,12 @@
function renderRouteTable() {
const sel = $("#rt-target");
if (!sel.options.length) {
sel.innerHTML = Object.entries(E.TARGETS).map(([k, t]) => `<option value="${k}">${esc(t.label)}</option>`).join("");
sel.innerHTML = Object.entries(META().targets).map(([k, t]) => `<option value="${k}">${esc(t.label)}</option>`).join("");
sel.value = state.rtTarget;
sel.addEventListener("change", () => { state.rtTarget = sel.value; renderRouteTable(); });
$("#rt-min").addEventListener("change", (e) => { state.rtMin = Math.max(1, +e.target.value || 10); renderRouteTable(); renderFindings(); });
$("#rt-min").addEventListener("change", (e) => { state.rtMin = +e.target.value; renderRouteTable(); renderFindings(); });
}
const rk = E.rankRoutes(state.runs, state.rtTarget, state.rtMin);
const rk = routesAt(state.rtTarget, state.rtMin);
const sig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
$("#rt-note").innerHTML = `${rk.n_routes_tested} routes tested · comparison group ${rateTxt(rk.overall)} · <b>${sig}</b> clearly better after adjustment`;
const bar = (w) => `<span class="cibar" aria-hidden="true"><i style="left:${w.lo * 90}px;width:${Math.max(1, (w.hi - w.lo) * 90)}px"></i><b style="left:${w.p * 90 - 1}px"></b></span>`;
@@ -592,8 +528,8 @@
function renderFactors() {
const so = $("#fx-outcome"), sf = $("#fx-factor");
if (!so.options.length) {
so.innerHTML = Object.entries(E.OUTCOMES).map(([k, o]) => `<option value="${k}">${esc(o.label)}</option>`).join("");
sf.innerHTML = E.FACTORS.map((f) => `<option value="${f}">${esc(labelFactor(f))}</option>`).join("");
so.innerHTML = Object.entries(META().outcomes).map(([k, o]) => `<option value="${k}">${esc(o.label)}</option>`).join("");
sf.innerHTML = META().factors.map((f) => `<option value="${f}">${esc(labelFactor(f))}</option>`).join("");
so.value = state.fxOutcome; sf.value = state.fxFactor;
so.addEventListener("change", () => { state.fxOutcome = so.value; renderFactors(); });
sf.addEventListener("change", () => { state.fxFactor = sf.value; renderFactors(); });
@@ -616,16 +552,12 @@
<div class="panel"><h3>Who logged the runs</h3><div class="tbl-wrap"><table><thead><tr><th>Source</th><th class="num">Runs</th><th class="num">Blue in meadow</th><th class="num">Shadow at tree</th></tr></thead><tbody>
${Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([s, n]) => { const b = sourceRate("blue_meadow", s), t = sourceRate("shadow", s); return `<tr><td>${esc(s)}</td><td class="num">${n}</td><td class="num">${pct(b.p)} <span class="muted">${kn(b)}</span></td><td class="num">${pct(t.p)} <span class="muted">${kn(t)}</span></td></tr>`; }).join("")}
</tbody></table></div><p class="small">Bulk logs come from players who recorded every run, so they are the least selective rows. Their rare-dragon rates are several times lower than the form's, which is the strongest sign of reporting bias in this data.</p></div>
<div class="panel"><h3>Rows flagged for contradictions</h3><p class="small muted">${m.n_flagged} of ${r.n} rows (${pct(m.n_flagged / r.n)}). Flagged rows stay in unless you drop them above.</p><div class="tbl-wrap"><table><tbody>${flags.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td></tr>`).join("") || `<tr><td>None</td></tr>`}</tbody></table></div></div>
<div class="panel"><h3>Rows flagged for contradictions</h3><p class="small muted">${m.n_flagged} of ${r.n} rows (${pct(m.n_flagged / r.n)}). Flagged rows stay in unless you pick "Rows without data-quality flags" above.</p><div class="tbl-wrap"><table><tbody>${flags.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td></tr>`).join("") || `<tr><td>None</td></tr>`}</tbody></table></div></div>
<div class="panel"><h3>How runs ended</h3><div class="tbl-wrap"><table><tbody>${outs.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td><td class="num">${pct(n / r.n)}</td></tr>`).join("")}</tbody></table></div><p class="small muted">"No outcome recorded" rows reached the hour but the form shows no Bonded or Incinerated. They count toward reaching a branch but not toward bond rates.</p></div>
<div class="panel"><h3>Independence</h3><p class="small">The form has no player ID. One player's 50 runs count as 50 independent runs, so intervals are somewhat narrower than they should be. ${pct((r.n - (m.sources["Form"] || 0)) / r.n, 0)} of rows arrived as bulk imports, each probably one player's or one group's log.</p></div>
<div class="panel"><h3>What the form does not ask</h3><p class="small">The redesigned form asks how you reacted to the first dragon (answered in ${r.factors.reach_hour.rows.filter((x) => x.factor === "sighting_action" && !["Unknown", "(not asked)"].includes(x.level)).reduce((a, x) => a + x.n, 0)} rows; most riders answer "Unsure") and how the bully fight went (${r.factors.reach_hour.rows.filter((x) => x.factor === "combat_first" && x.level !== "(not recorded)").reduce((a, x) => a + x.n, 0)} rows). It still does not record most choices inside the bonding encounters. Theories that rely on those choices cannot be confirmed or refuted here.</p></div>`;
}
function sourceRate(outKey, source) {
const O = E.OUTCOMES[outKey];
const D = state.runs.filter((r) => r.source === source).filter(O.denom);
return E.wilson(D.filter(O.event).length, D.length);
}
const sourceRate = (outKey, source) => state.res.source_rates[outKey][source];
// ------------------------------------------------------------ share
function redditPost() {
@@ -634,7 +566,7 @@
const encB = r.encounters.find((e) => e.context === "Blue (meadow)"), encK = r.encounters.find((e) => e.context === "Black (shadow)");
const mb = r.models.blue_meadow;
const sigRoute = mb ? mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level)) : [];
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const rk = routesAt("see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
const leads = r.factors.shadow.rows.filter((x) => ["post_path", "attempt_group"].includes(x.factor) && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
const L = [];
@@ -659,13 +591,7 @@
L.push(`*Caveats: self-reported data, no player IDs (so runs from one person aren't independent), and the form doesn't record every in-game choice. The author has said there's a ~10% chaos roll, so nothing is guaranteed.*`);
return L.join("\n");
}
function runsCSV() {
const cols = Object.keys(state.runs[0] || {});
const q = (v) => { if (v === null || v === undefined) return ""; const s = String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...state.runs.map((r) => cols.map((c) => q(r[c])).join(","))].join("\n");
}
$("#cp-reddit").addEventListener("click", () => copyText(redditPost(), "Reddit post"));
$("#cp-csv").addEventListener("click", () => copyText(runsCSV(), `${state.runs.length} coded runs`));
$("#cp-json").addEventListener("click", () => copyText(JSON.stringify(state.res, null, 1), "results JSON"));
$$("button[data-src]").forEach((b) => b.addEventListener("click", async () => {
const pre = $("#srcview");
@@ -679,11 +605,8 @@
$$("#width-mode button").forEach((x) => x.setAttribute("aria-pressed", x === b));
renderMap();
}));
$("#minn").addEventListener("change", (e) => { state.minN = Math.max(1, +e.target.value || 10); renderMap(); });
$("#f-source").addEventListener("change", (e) => { state.filters.source = e.target.value; recompute(); });
$("#f-goal").addEventListener("change", (e) => { state.filters.goal = e.target.value; recompute(); });
$("#f-flag").addEventListener("change", (e) => { state.filters.excludeFlagged = e.target.checked; recompute(); });
$("#btn-clear").addEventListener("click", () => { state.conds = {}; renderMap(); $("#best-routes").innerHTML = ""; });
$("#minn").addEventListener("change", (e) => { state.minN = +e.target.value; renderMap(); if ($("#best-routes").innerHTML) renderBestRoutes(); });
$("#f-preset").addEventListener("change", (e) => { state.preset = e.target.value; recompute(); });
$("#btn-best").addEventListener("click", renderBestRoutes);
function renderAll() {
@@ -698,7 +621,7 @@
new MutationObserver(rerender).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
let rz; window.addEventListener("resize", () => { clearTimeout(rz); rz = setTimeout(() => state.res && renderMap(), 200); });
window.ThreshAtlas = { state, redditPost, runsCSV };
window.ThreshAtlas = { state, redditPost };
if (window.DragonRegister) window.DragonRegister.mount({ copy: copyText, toast });
loadBundled().catch((e) => { $("#data-status").innerHTML = `<span class="pill warn">The bundled data could not load (${esc(e.message)}). Use "Load a newer export" to load the responses file.</span>`; console.error(e); });
loadStats().catch((e) => { $("#data-status").innerHTML = `<span class="pill warn">The statistics (data/stats.json) could not load: ${esc(e.message)}.</span>`; console.error(e); });
})();