site built from fbf42508

This commit is contained in:
Atlas data bot
2026-11-19 20:23:28 +00:00
commit a6952c193e
28 changed files with 21965 additions and 0 deletions
+629
View File
@@ -0,0 +1,629 @@
/* 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 $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const NS = "http://www.w3.org/2000/svg";
const state = {
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) + "%");
const ci = (w, d = 1) => (w && w.n ? `${pct(w.lo, d)}–${pct(w.hi, d)}` : "–");
const fmtOR = (x) => (x === null || x === undefined || !isFinite(x) ? "–" : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2));
const fmtP = (p) => (p === null || p === undefined ? "–" : p < 0.0001 ? "<0.0001" : p < 0.001 ? p.toExponential(1) : p.toFixed(p < 0.01 ? 3 : 2));
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const kn = (w) => (w ? `${w.k}/${w.n}` : "–");
const rateTxt = (w, d = 1) => (w && w.n ? `${pct(w.p, d)} (${kn(w)}; 95% CI ${ci(w, d)})` : "no data");
function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
function rgb(c) {
c = c.trim();
if (c.startsWith("#")) {
const h = c.length === 4 ? c.slice(1).split("").map((x) => x + x).join("") : c.slice(1);
return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
}
const m = c.match(/\d+(\.\d+)?/g);
return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
function mix(a, b, t) {
const A = rgb(a), B = rgb(b);
return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`;
}
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(TARGET(t).color);
function svgEl(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function toast(msg) {
const t = document.createElement("div");
t.className = "toast"; t.textContent = msg; document.body.appendChild(t);
setTimeout(() => t.remove(), 2200);
}
async function copyText(text, label) {
try { await navigator.clipboard.writeText(text); toast(`Copied ${label}`); }
catch (e) {
const ta = document.createElement("textarea");
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select();
let ok = false; try { ok = document.execCommand("copy"); } catch (_) { /* ignore */ }
ta.remove(); toast(ok ? `Copied ${label}` : "Copy was blocked here. Select the text manually instead.");
}
}
// ------------------------------------------------------------ tooltip
const tip = $("#tip");
function showTip(evt, html) {
tip.innerHTML = html; tip.hidden = false;
const x = evt.clientX ?? (evt.touches && evt.touches[0].clientX) ?? 0, y = evt.clientY ?? 0;
const r = tip.getBoundingClientRect();
tip.style.left = Math.min(window.innerWidth - r.width - 8, x + 14) + "px";
tip.style.top = Math.min(window.innerHeight - r.height - 8, y + 14) + "px";
}
const hideTip = () => (tip.hidden = true);
// ------------------------------------------------------------ data loading
async function loadStats() {
state.stats = await (await fetch("data/stats.json")).json();
try { state.overlap = await (await fetch("data/overlap.json")).json(); } catch { state.overlap = null; }
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();
}
function recompute() {
state.P = state.stats.presets[state.preset];
state.res = state.P.analyse;
renderAll();
}
// ------------------------------------------------------------ header
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 total = state.stats.data.runs;
$("#data-status").innerHTML = `
<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">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
function stratumRate(chance, keyPart) {
const e = Object.entries(chance.by_stratum).find(([k]) => k.startsWith(keyPart));
return e ? e[1] : null;
}
const ROUTE_FACTORS = ["direction", "first_sighting", "resolution", "company"];
const NOT_A_CHOICE = /^(Unsure|Unknown|Multiple|\(not recorded\)|Unknown\/lost count|Unsure\/unknown)/;
function buildFindings() {
const r = state.res, out = [];
const cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), otherB = stratumRate(cb, "Form: other");
const encBlue = r.encounters.find((e) => e.context === "Blue (meadow)");
const encBlack = r.encounters.find((e) => e.context === "Black (shadow)");
if (cb.overall.n) {
const biasShown = chaseB && bulkB && chaseB.n >= 20 && bulkB.n >= 20 && chaseB.lo > bulkB.hi;
let t;
if (biasShown) {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits, but that figure is inflated.</b> Players chasing a rare dragon report it in ${pct(chaseB.p)} of their visits. Bulk logs, which record every run, show ${rateTxt(bulkB)}. The game cannot see what you are chasing, so that gap comes from which runs get reported.</p>`;
t += `<p>A realistic expectation is nearer the bulk-log rate, about one meadow visit in ${Math.round(1 / Math.max(bulkB.p, 0.001))}, than the headline figure.${otherB ? ` Form players who were not chasing a Blue report ${pct(otherB.p)}, which still carries some selective reporting.` : ""}</p>`;
} else {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits in the current selection.</b> Compare the data-source filter settings to see how much this depends on who logged the runs.</p>`;
}
out.push(["bias", "Reporting bias", t]);
}
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 = 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>`
: `<p><b>No recorded route choice changed the chance of the Blue appearing once reporting bias is held fixed.</b> Direction, first sighting, how you handled the cadet and who you entered with all have adjusted odds ratios whose 95% intervals include 1 (n = ${mb.n} meadow visits).</p>`;
t += `<p>Of ${rk.n_routes_tested} full routes with at least ${state.rtMin} meadow visits, ${adjSig.length} beat the others after adjustment and correction for multiple testing. The "precise pathways" shared on Reddit may still matter through choices the form does not record, such as the answers given inside each encounter.</p>`;
out.push(["blue", "Blue", t]);
}
if (encBlue && encBlue.overall.n) {
out.push(["blue", "Blue", `<p><b>Reaching the Blue is not enough. Only ${rateTxt(encBlue.overall)} of Blue attempts ended in a bond</b> (${pct(encBlue.intent_matched.p)} when the player wanted a Blue). The community PDF's step-by-step survival rates multiply out to about 25% for the standard answers. Expect several Blue encounters per bond, and do not treat one death as proof that an answer is wrong.</p>`]);
}
if (cs.overall.n) {
const bulkS = stratumRate(cs, "Bulk"), formS = Object.entries(cs.by_stratum).filter(([k]) => k.startsWith("Form"));
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>`;
if (encBlack && encBlack.overall.n) t += `<p>Once the Black appears it is the easiest dragon to bond: ${rateTxt(encBlack.overall)}.</p>`;
out.push(["black", "Black", t]);
}
// leads: unadjusted factor rows with q < 0.05 on route-type factors, for the shadow
const leadF = ["post_path", "attempt_group", "direction", "first_sighting", "resolution", "company", "combat_first"];
const sh = r.factors.shadow.rows.filter((x) => leadF.includes(x.factor) && x.q !== undefined && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
if (sh.length) {
const ms = r.models.shadow;
let t = `<p><b>Shadow leads to test, not established:</b> ${sh.map((x) => `<i>${esc(labelFactor(x.factor))}: ${esc(x.level)}</i> had the shadow in ${rateTxt(x)} vs the rest (OR ${fmtOR(x.or)}, q = ${fmtP(x.q)})`).join("; ")}.</p>`;
const att = ms && ms.terms.find((tm) => tm.factor === "attempt" && tm.level === "First attempt");
if (att) t += `<p>The first-attempt pattern survives adjustment for data source, chase goal and direction (OR ${fmtOR(att.or)}, 95% CI ${fmtOR(att.lo)}–${fmtOR(att.hi)}). That matches a theory on Reddit that a fresh account rolls the shadow more often, but players who strike lucky on a first run may also be more likely to submit the form.</p>`;
t += `<p>The cheapest test is a bulk log that records every tree climb, including the dull ones, with these choices noted.</p>`;
out.push(["lead", "Lead", t]);
}
// common dragons
const common = r.encounters.filter((e) => ["Red (valley)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Red (tree, descend quickly)"].includes(e.context) && e.intent_matched.n >= 10);
if (common.length) {
out.push(["", "Common", `<p><b>For the common colours, intent matters more than route.</b> Among players who wanted that colour: ${common.map((e) => `${esc(e.context)} ${pct(e.intent_matched.p, 0)} (${kn(e.intent_matched)})`).join(", ")}. The tree Red is the hardest bond in the game.</p>`]);
}
return out;
}
function renderFindings() {
$("#findings-list").innerHTML = buildFindings().map(([cls, tag, html], i) =>
`<div class="finding ${cls}"><span class="mark">${i + 1}</span><div><span class="tag">${esc(tag)}</span>${html}</div></div>`).join("");
}
const FACTOR_LABEL = { company: "Company", direction: "Direction", first_sighting: "First sighting", scream: "Scream choice", resolution: "Cadet encounter",
combat_first: "First combat move", post_path: "Fork in the road", hour: "After an hour", wing: "Wing", squad: "Squad",
attempt_group: "Attempt", entry: "Data source", source: "Data source", goal: "Chasing", attempt: "Attempt", period: "Date",
sighting_action: "Reaction to the first dragon", combat_second: "Second combat move", malek_intent: "Planned to seek Malek", };
const labelFactor = (f) => FACTOR_LABEL[f] || f;
// ------------------------------------------------------------ route map
// first row: bonding each dragon (all six treated alike); second row: the two rare sightings
const RARE_T = ["bond_Red", "bond_Orange", "bond_Brown", "bond_Green", "bond_Blue", "bond_Black", "bond_any"];
const OTHER_T = ["see_Blue", "see_shadow"];
function renderTargets() {
const chip = (t, featured) => {
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("");
$$(".tchip[data-t]").forEach((b) => b.addEventListener("click", () => { state.target = b.dataset.t; $("#best-routes").innerHTML = ""; renderTargets(); renderMap(); }));
}
const ORDER = {
company: ["Alone", "1 Squadmate", "2 Squadmates"],
direction: ["East", "Center", "West"],
first_sighting: ["Red", "Orange", "Brown", "Green"],
post_path: ["Forest", "West", "East", "(no fork)"],
hour: ["Climb the tree", "Valley centre"],
encounter: ["Tree: Red below", "Tree: two Greens", "Tree: shadow → Blue/Black", "Valley: bond the Red", "Meadow: Orange", "Meadow: Brown", "Meadow: Orange/Brown", "Meadow: Blue", "Meadow (no attempt recorded)"],
end: ["Bonded Red", "Bonded Green", "Bonded Orange", "Bonded Brown", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour"],
};
const SHORT = {
"Help → Killed the bullies yourself": "Help · killed bullies", "Help → Squadmate's revenge": "Help · squadmate's revenge",
"Help → Left bullies to the dragons": "Help · left to dragons", "Help → DIED in combat": "Help · died in combat", "Help → Unknown": "Help · unknown",
"Ignore the scream → Tourniquet": "Ignore · tourniquet", "Ignore the scream → Left injured cadet": "Ignore · left cadet",
"Ignore the scream → Took their weapons": "Ignore · took weapons", "Investigate & leave → Left them to it": "Investigate · walked away",
"Tree: shadow → Blue/Black": "Tree: shadow (Blue→Black)", "Meadow (no attempt recorded)": "Meadow: none recorded", "Unknown → Unknown": "Unknown",
};
const short = (v) => SHORT[v] || v;
function renderMap() {
const svg = $("#map");
svg.innerHTML = "";
// 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 = STAGES.length;
const colX = (i) => left + (i * (W - left - right - nodeW)) / (S - 1);
const cols = STAGES.map((s, i) => {
const ns = base.nodes.filter((n) => n.stage === i);
const ord = ORDER[s.key];
ns.sort((a, b) => {
const ia = ord ? ord.indexOf(a.value) : -1, ib = ord ? ord.indexOf(b.value) : -1;
if (ia !== -1 || ib !== -1) return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
return b.n - a.n;
});
return ns;
});
const pad = 7;
const maxTotal = Math.max(...cols.map((c) => c.reduce((s, n) => s + n.n, 0)));
const maxCount = Math.max(...cols.map((c) => c.length));
const scale = (H - top - bottom - pad * (maxCount - 1)) / maxTotal;
const pos = new Map();
cols.forEach((ns, i) => {
const hTot = ns.reduce((s, n) => s + Math.max(2, n.n * scale), 0) + pad * (ns.length - 1);
let y = top + (H - top - bottom - hTot) / 2;
ns.forEach((n) => { const h = Math.max(2, n.n * scale); pos.set(n.id, { x: colX(i), y, h, n }); y += h + pad; });
});
// colour scale: anchored on the route steps, not on the outcome column (where the target node is 100% by definition)
const lastStage = S - 1;
const stageOf = (id) => +id.split("|")[0];
const eligible = sel.links.filter((l) => l.n >= minN && stageOf(l.target) < lastStage);
const pmax = Math.max(0.005, ...eligible.map((l) => l.p), ...sel.nodes.filter((n) => n.n >= minN && n.stage < lastStage).map((n) => n.p));
const colorFor = (o) => (o.n < minN ? low : mix(low, tcol, Math.pow(Math.min(1, o.p / pmax), 0.75)));
// stage headers
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"; }
});
// links
const gLinks = svgEl("g", {}, svg);
const outOff = new Map(), inOff = new Map();
const linksSorted = sel.links.slice().sort((a, b) => pos.get(a.source).y - pos.get(b.source).y || pos.get(a.target).y - pos.get(b.target).y);
// order out-links by target y and in-links by source y for clean stacking
const byOut = {}, byIn = {};
linksSorted.forEach((l) => { (byOut[l.source] = byOut[l.source] || []).push(l); (byIn[l.target] = byIn[l.target] || []).push(l); });
Object.values(byOut).forEach((ls) => ls.sort((a, b) => pos.get(a.target).y - pos.get(b.target).y));
Object.values(byIn).forEach((ls) => ls.sort((a, b) => pos.get(a.source).y - pos.get(b.source).y));
const offOut = {}, offIn = {};
Object.entries(byOut).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offOut[l.id] = o; o += l.n * scale; }); });
Object.entries(byIn).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offIn[l.id] = o; o += l.n * scale; }); });
const drawOrder = state.widthMode === "prob" ? sel.links.slice().sort((a, b) => (a.n >= minN) - (b.n >= minN) || a.p - b.p) : linksSorted;
drawOrder.forEach((l) => {
const s = pos.get(l.source), t = pos.get(l.target);
if (!s || !t) return;
const x0 = s.x + nodeW, x1 = t.x, xm = (x0 + x1) / 2;
let el;
if (state.widthMode === "traffic") {
const w = Math.max(0.6, l.n * scale);
const y0 = s.y + offOut[l.id], y1 = t.y + offIn[l.id];
el = svgEl("path", {
d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}L${x1},${y1 + w}C${xm},${y1 + w} ${xm},${y0 + w} ${x0},${y0 + w}Z`,
fill: colorFor(l), "fill-opacity": l.n >= minN ? 0.62 : 0.3, class: "link",
}, gLinks);
} else {
const y0 = s.y + s.h / 2, y1 = t.y + t.h / 2;
const w = l.n >= minN ? 1.2 + 18 * (l.p / pmax) : 1;
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<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);
});
// nodes
const gNodes = svgEl("g", {}, svg);
cols.forEach((ns, i) => {
let lastLabelBottom = -1e9;
ns.forEach((bn) => {
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) {
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.n >= minN ? pct(sn.p, 0) : `n=${sn.n}`;
lastLabelBottom = ly;
}
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);
g.addEventListener("blur", hideTip);
});
});
renderLegend(pmax, tcol, low);
}
function renderLegend(pmax, tcol, low) {
$("#legend").innerHTML = `
<span>${state.widthMode === "traffic" ? "Band width = number of runs" : "Line width = chance of the outcome"}</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${low}, ${tcol})"></span> ${pct(pmax, 0)}</span>
<span>Grey = fewer than ${state.minN} runs</span>
<span><span style="color:var(--accent)">Gold headings</span> = steps the game rolls, not you</span>`;
}
function renderBestRoutes() {
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(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></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>`;
}
// ------------------------------------------------------------ small charts
// Horizontal rate bars with 95% CI whiskers.
function ciBars(el, rows, opts = {}) {
const W = 640, rowH = opts.rowH || 26, lw = opts.labelW || 190, top = 8, bottom = 26;
const H = top + bottom + rows.length * rowH;
const xmax = opts.max || Math.min(1, Math.max(0.05, ...rows.map((r) => r.hi || 0)) * 1.08);
const x = (v) => lw + (v / xmax) * (W - lw - 120);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ticks = niceTicks(xmax);
const ga = svgEl("g", { class: "axis" }, svg);
ticks.forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 8, "text-anchor": "middle" }, ga); tx.textContent = pct(t, 0);
});
rows.forEach((r, i) => {
const y = top + i * rowH + rowH / 2;
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg); lab.textContent = r.label;
if (r.indent) lab.setAttribute("fill", cssVar("--muted"));
if (!r.n) { const t = svgEl("text", { x: lw, y: y + 4, fill: cssVar("--faint") }, svg); t.textContent = "no runs"; return; }
const col = r.color || cssVar("--muted");
svgEl("rect", { x: lw, y: y - 7, width: Math.max(1, x(r.p) - lw), height: 14, fill: col, "fill-opacity": 0.28, rx: 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.lo), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.hi), x2: x(r.hi), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("circle", { cx: x(r.p), cy: y, r: 4, fill: col }, svg);
const v = svgEl("text", { x: x(r.hi) + 6, y: y + 4, "font-family": "var(--font-data)" }, svg);
v.textContent = `${pct(r.p)} · ${r.k}/${r.n}`;
});
el.innerHTML = ""; el.appendChild(svg);
}
function niceTicks(max) {
const steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.25];
const step = steps.find((s) => max / s <= 6) || 0.25;
const out = []; for (let v = 0; v <= max + 1e-9; v += step) out.push(+v.toFixed(4)); return out;
}
// Forest plot of odds ratios on a log axis.
function forest(el, terms, opts = {}) {
const W = 640, rowH = 22, lw = opts.labelW || 290, top = 8, bottom = 28;
const H = top + bottom + Math.max(1, terms.length) * rowH;
const lo = 0.05, hi = 20;
const x = (v) => lw + ((Math.log(Math.min(hi, Math.max(lo, v))) - Math.log(lo)) / (Math.log(hi) - Math.log(lo))) * (W - lw - 60);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ga = svgEl("g", { class: "axis" }, svg);
[0.1, 0.25, 0.5, 1, 2, 4, 10].forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4, "stroke-dasharray": t === 1 ? "" : "2 3", "stroke-width": t === 1 ? 1.5 : 1 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 10, "text-anchor": "middle" }, ga); tx.textContent = t;
});
terms.forEach((t, i) => {
const y = top + i * rowH + rowH / 2;
const sig = t.p !== undefined ? t.p < 0.05 : t.q < 0.05;
const col = sig ? cssVar("--accent") : cssVar("--muted");
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg);
lab.textContent = (t.label.length > 40 ? t.label.slice(0, 39) + "…" : t.label) + (t.n !== undefined ? ` (n=${t.n})` : "");
svgEl("line", { x1: x(t.lo), x2: x(t.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("rect", { x: x(t.or) - 4, y: y - 4, width: 8, height: 8, fill: col }, svg);
const v = svgEl("text", { x: W - 4, y: y + 4, "text-anchor": "end", "font-family": "var(--font-data)", fill: cssVar("--muted") }, svg);
v.textContent = fmtOR(t.or);
});
el.innerHTML = ""; el.appendChild(svg);
}
// ------------------------------------------------------------ rare section
const STRATUM_ORDER = ["Bulk logs (imports)", "Form: other/blank goal", "Form: chasing Black", "Form: chasing Blue", "Form: chasing Blue or Black"];
function renderRare() {
const r = state.res;
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]) => !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) && !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));
const refTxt = (m) => (m ? `Reference answers: ${Object.entries(m.refs).map(([f, v]) => `${labelFactor(f)} = ${v}`).join(", ")}. n = ${m.n}, events = ${m.events}. Gold = p < 0.05 (not corrected for the number of terms).` : "Not enough data.");
$("#model-blue-note").textContent = refTxt(mb);
$("#model-shadow-note").textContent = refTxt(ms);
renderDaily();
const enc = r.encounters.filter((e) => ["Blue (meadow)", "Blue (shadow)", "Black (shadow)"].includes(e.context));
ciBars($("#ch-rare-bond"), enc.flatMap((e) => [
{ label: e.context, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]), { labelW: 200, max: 1 });
renderPdfSteps();
}
function renderDaily() {
const d = state.res.daily.filter((x) => x.meadow_n + x.tree_n > 0);
const el = $("#ch-daily");
if (!d.length) { el.textContent = "No dated runs in the current filter."; return; }
const W = 640, H = 250, l = 44, rgt = 24, top = 16, mid = 125, bottom = 30;
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, 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) => 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);
[0, ymax / 2, ymax].forEach((t) => { svgEl("line", { x1: l, x2: W - rgt, y1: y(t), y2: y(t) }, ga); const tx = svgEl("text", { x: l - 6, y: y(t) + 3, "text-anchor": "end" }, ga); tx.textContent = pct(t, 0); });
const nm = svgEl("text", { x: l + 4, y: P.y0 + 10, fill: P.col, "font-weight": 600 }, svg); nm.textContent = P.name;
const yc = (v) => y(Math.min(ymax, v));
vals.forEach((v, i) => {
if (v.n < 3) return;
svgEl("line", { x1: x(i), x2: x(i), y1: yc(v.lo), y2: yc(v.hi), stroke: P.col, "stroke-opacity": 0.45, "stroke-width": 1.5 }, svg);
const c = svgEl("circle", { cx: x(i), cy: yc(v.p), r: 2 + Math.sqrt(v.n) / 2.2, fill: P.col, "fill-opacity": 0.85 }, svg);
c.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${d[i].date} · ${P.name}</div>${pct(v.p)} (${kn(v)})<br>95% CI ${ci(v)}`));
c.addEventListener("mouseleave", hideTip);
});
});
const ga = svgEl("g", { class: "axis" }, svg);
d.forEach((r, i) => { if (i % Math.ceil(d.length / 8) === 0 || i === d.length - 1) { const t = svgEl("text", { x: x(i), y: H - 10, "text-anchor": "middle" }, ga); t.textContent = r.date.slice(5); } });
el.innerHTML = ""; el.appendChild(svg);
}
function renderPdfSteps() {
const blue = [["Approach the Blue: “Absolutely…”", "90%"], ["Hold the Blue's glare and advance", "80%"], ["Do nothing (it seizes the other cadet)", "82%"], ["Hold glare and watch", "84%"], ["Straighten your spine", "83%"], ["Launch yourself right (boulder)", "93%"], ["“Bring down an empire”", "81%"], ["Move slowly forward, wait for an invitation", "81%"]];
const prod = [0.9, 0.8, 0.82, 0.84, 0.83, 0.93, 0.81, 0.81].reduce((a, b) => a * b, 1);
$("#pdf-steps").innerHTML = `<p class="small muted">As published in the community PDF (u/ClumsyBadger, u/Old_Regular3018). These come from hand-coded free-text answers. The underlying counts are not shown there, and many cells rest on fewer than 10 runs.</p>
<div class="tbl-wrap"><table><thead><tr><th>Meadow Blue, standard answers</th><th class="num">Survived step</th></tr></thead><tbody>${blue.map(([a, b]) => `<tr><td>${a}</td><td class="num">${b}</td></tr>`).join("")}
<tr><td><b>All eight steps (product)</b></td><td class="num"><b>${pct(prod, 0)}</b></td></tr></tbody></table></div>
<p class="small">The product, about ${pct(prod, 0)}, agrees with the form's own Blue bond rate (${rateTxt(state.res.encounters.find((e) => e.context === "Blue (meadow)").overall)}), which is a useful cross-check.</p>
<div class="tbl-wrap"><table><thead><tr><th>Black (after the shadow and the tree Blue)</th><th class="num">PDF outcome</th></tr></thead><tbody>
<tr><td>Turn to face the threat → hold its gaze</td><td class="num">66% bonded · 33% incinerated</td></tr>
<tr><td>Turn to face the threat → lower your eyes → try to mount → meet its gaze</td><td class="num">100% bonded (very few runs)</td></tr></tbody></table></div>`;
}
// ------------------------------------------------------------ every dragon
function renderDragons() {
const r = state.res;
const order = ["Red (valley)", "Red (tree, descend quickly)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Blue (meadow)", "Blue (shadow)", "Black (shadow)"];
const rows = order.map((c) => r.encounters.find((e) => e.context === c)).filter(Boolean).flatMap((e) => [
{ label: `${e.context}`, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]);
const box = $("#ch-encounters");
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"), "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 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, 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"] };
$("#tbl-first").innerHTML = `<table><thead><tr><th>Company · direction</th>${cols.map((c) => `<th class="num">${c}</th>`).join("")}<th class="num">Runs</th></tr></thead><tbody>${r.first_sighting.map((x) => ({ ...x, n: cols.reduce((t, c) => t + (x.colors[c] || 0), 0), gap: (x.colors.Unsure || 0) + (x.colors.Unknown || 0) })).filter((x) => x.n >= 3).map((x) => `<tr><td>${esc(x.key.replace("|", " · "))}</td>${cols.map((c) => { const n = x.colors[c] || 0; const off = n && POOL[x.key] && !POOL[x.key].includes(c); return `<td class="num" style="${off ? "color:var(--warn);font-weight:600" : n ? "" : "color:var(--faint)"}" title="${off ? "Outside the documented pool" : ""}">${n ? `${n}<span class="muted"> · ${pct(n / x.n, 0)}</span>` : "·"}</td>`; }).join("")}<td class="num">${x.n}${x.gap ? `<span class="muted" title="Riders who were not sure which dragon they saw, left out"> +${x.gap} unsure</span>` : ""}</td></tr>`).join("")}</tbody></table>`;
}
// ------------------------------------------------------------ route table
function renderRouteTable() {
const sel = $("#rt-target");
if (!sel.options.length) {
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 = +e.target.value; renderRouteTable(); renderFindings(); });
}
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>`;
$("#tbl-routes").innerHTML = rk.rows.length ? `<table><thead><tr><th>#</th><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Hits</th><th class="num">Rate</th><th class="num">95% CI</th><th></th><th class="num">Crude OR</th><th class="num">q</th><th class="num">Adj. OR</th><th class="num">Adj. q</th></tr></thead><tbody>
${rk.rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}${r.n < 20 ? " thin" : ""}"><td class="num">${i + 1}</td><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${r.k}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td>${bar(r)}</td><td class="num">${fmtOR(r.or)}</td><td class="num">${fmtP(r.q)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td></tr>`).join("")}
</tbody></table>` : `<p class="small muted" style="padding:12px">No routes reach the minimum. Lower it.</p>`;
}
// ------------------------------------------------------------ factor explorer
function renderFactors() {
const so = $("#fx-outcome"), sf = $("#fx-factor");
if (!so.options.length) {
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(); });
}
const ft = state.res.factors[state.fxOutcome];
const rows = ft.rows.filter((r) => r.factor === state.fxFactor);
$("#tbl-factors").innerHTML = `<table><thead><tr><th>${esc(labelFactor(state.fxFactor))}</th><th class="num">Hits/runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">OR vs rest</th><th class="num">p</th><th class="num">q</th></tr></thead><tbody>
<tr><td><i>All</i></td><td class="num">${kn(ft.overall)}</td><td class="num">${pct(ft.overall.p)}</td><td class="num">${ci(ft.overall)}</td><td></td><td></td><td></td></tr>
${rows.map((r) => `<tr class="${r.q < 0.05 ? "sig" : ""}${r.or === undefined ? " thin" : ""}"><td>${esc(r.level)}</td><td class="num">${kn(r)}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${r.or !== undefined ? `${fmtOR(r.or)} <span class="muted">(${fmtOR(r.or_lo)}–${fmtOR(r.or_hi)})</span>` : "too few"}</td><td class="num">${fmtP(r.fisher_p)}</td><td class="num">${r.q !== undefined ? `<span class="qbadge${r.q < 0.05 ? " s" : ""}">${fmtP(r.q)}</span>` : ""}</td></tr>`).join("")}
</tbody></table>${ft.missing && ft.missing[state.fxFactor] ? `<p class="small muted">${ft.missing[state.fxFactor].toLocaleString()} runs with no usable answer to this question ("unsure", blank, or not asked on that version of the form) are left out of these comparisons rather than treated as a choice.</p>` : ""}`;
forest($("#ch-factor"), rows.filter((r) => r.or !== undefined).map((r) => ({ label: r.level, or: r.or, lo: r.or_lo, hi: r.or_hi, q: r.q, p: undefined, n: r.n })), { labelW: 220 });
}
// ------------------------------------------------------------ quality
function renderQuality() {
const r = state.res, m = r.meta;
const flags = Object.entries(m.flag_counts).sort((a, b) => b[1] - a[1]);
const outs = Object.entries(m.outcomes).sort((a, b) => b[1] - a[1]);
$("#quality-panels").innerHTML = `
<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 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>
${state.overlap && state.overlap.comparable ? `<div class="panel"><h3>The same run reported twice?</h3><p class="small">A rider may log a run in the form and post it in a megathread comment too. With no player IDs, a copy can only be measured, not proven, so nothing is removed. Of ${state.overlap.comparable} Reddit runs detailed enough to compare, ${state.overlap.matched} give the same answers as a form row sent within ${state.overlap.rule.window_days} day; chance alone (the same test a few weeks off) gives about ${state.overlap.expected_by_chance}. So about ${Math.round(state.overlap.likely_double)} of ${state.overlap.comment_runs} Reddit runs look reported twice${state.overlap.likely_double < 0.1 * state.overlap.comment_runs ? ", too few to matter" : ""}.</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(Object.entries(m.sources).filter(([k]) => !["Form", "Reddit comments", "DragonKind bot", "Reported on the Atlas"].includes(k)).reduce((s, [, n]) => s + n, 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>`;
}
const sourceRate = (outKey, source) => state.res.source_rates[outKey][source];
// ------------------------------------------------------------ share
function redditPost() {
const r = state.res, cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), bulkS = stratumRate(cs, "Bulk");
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 = 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 = [];
L.push(`# I ran the numbers on ${r.n.toLocaleString()} logged threshing runs. Here's what holds up (and what doesn't)`);
L.push("");
L.push(`*Per the megathread rules, anything that names a specific route is behind spoiler tags.*`);
L.push("");
L.push(`Data: the community Threshing Routes form/spreadsheet (thanks u/ClumsyBadger, u/Old_Regular3018, u/Smart_Trifle_2099 and everyone who logged runs). ${Object.entries(r.meta.sources).map(([k, v]) => `${v} ${k === "Form" ? "form submissions" : k}`).join(", ")}; form dates ${r.meta.date_min} to ${r.meta.date_max}. Every rate below has a 95% confidence interval.`);
L.push("");
L.push(`**TL;DR**`);
L.push("");
L.push(`* **The meadow Blue shows up a lot less than the spreadsheet suggests.** Runs logged by Blue-chasers show it ${pct(chaseB && chaseB.p)} of the time, but bulk logs (people who recorded *every* run) show ${bulkB ? `${pct(bulkB.p)} (${kn(bulkB)})` : "n/a"}. The game can't know what you're chasing, so that gap is reporting bias. Expect something closer to the bulk-log number.`);
L.push(`* **${sigRoute.length ? "Only these route choices mattered for the Blue appearing" : "No recorded route choice changed the Blue's odds"}** once you account for that bias${sigRoute.length ? `: ${sigRoute.map((s) => s.term).join("; ")}` : ""} (direction, first dragon, how you handled the cadet, company). ${adjSig} of ${rk.n_routes_tested} full routes beat the rest after correcting for multiple testing. The "precise pathways" might still matter through choices the form doesn't record (like how you react to the first dragon), but the form can't confirm them.`);
L.push(`* **Getting the Blue to show up is only half of it.** Only ${encB ? `${pct(encB.overall.p)} (${kn(encB.overall)})` : "n/a"} of Blue attempts bonded, which matches the PDF's step-by-step numbers (~25%). Dying with the "right" answer is normal.`);
L.push(`* **The tree shadow (→ Black) is rarer than the spreadsheet suggests.** All rows: ${pct(cs.overall.p)} (${kn(cs.overall)}), but bulk logs show ${bulkS ? `${kn(bulkS)} (upper 95% bound ${pct(bulkS.hi)})` : "n/a"}. ${bulkS && bulkS.n ? `Plan on roughly 1 in ${Math.round(1 / Math.max(bulkS.hi, 0.001) / 10) * 10} climbs at best.` : ""} Once you get the Black, it bonds ${encK ? `${pct(encK.overall.p)} (${kn(encK.overall)})` : "n/a"} of the time.`);
if (leads.length) L.push(`* **Leads worth testing (not proven):** >!${leads.map((x) => `${labelFactor(x.factor)} = ${x.level}: shadow in ${pct(x.p)} (${kn(x)}) vs the rest`).join("; ")}!<. If you bulk-log your tree climbs *including the boring ones*, we can settle this.`);
L.push("");
L.push(`**How to help:** log every run in the form, including the ones where nothing rare happened. Those dull runs are what make the rates trustworthy.`);
L.push("");
L.push(`Interactive route map, full methods, and code to reproduce every number: [Threshing Route Atlas](LINK)`);
L.push("");
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 game's author has said no single roll is worse than 1 in 20 and that the Black is not luck, but no route guarantees a bond.*`);
return L.join("\n");
}
$("#cp-reddit").addEventListener("click", () => copyText(redditPost(), "Reddit post"));
$("#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");
try { const t = await (await fetch(b.dataset.src)).text(); pre.textContent = t; pre.hidden = false; pre.scrollTop = 0; }
catch (e) { pre.textContent = "Could not load " + b.dataset.src; pre.hidden = false; }
}));
// ------------------------------------------------------------ controls
$$("#width-mode button").forEach((b) => b.addEventListener("click", () => {
state.widthMode = b.dataset.v;
$$("#width-mode button").forEach((x) => x.setAttribute("aria-pressed", x === b));
renderMap();
}));
$("#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() {
renderStatus(); renderFindings(); renderTargets(); renderMap(); renderRare(); renderDragons(); renderRouteTable(); renderFactors(); renderQuality();
if ($("#best-routes").innerHTML) renderBestRoutes();
if (window.AtlasUI) window.AtlasUI.render(state);
}
// re-colour when the theme changes
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const rerender = () => state.res && renderAll();
mq.addEventListener && mq.addEventListener("change", rerender);
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 };
if (window.DragonRegister) window.DragonRegister.mount({ copy: copyText, toast });
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); });
})();