The Threshing Routes form was redesigned (5,651 responses). Both implementations
(engine.js and clean.py) now read either version:
- one direction question + one colour question, with the older per-direction
columns used only to fill gaps and cross-check
- cadet encounter as an action path (scream, first and second combat move)
plus a separate outcome
- new fields: sighting_action, combat_second, rare_reported, malek_intent,
left_squadmates, tail; "Why are you doing this run?" mapped onto the goal
("Blue or Black" for rare chasers)
- the rare-dragon question feeds saw_blue_meadow / saw_shadow and the branch
The old export still codes identically. JS/Python parity: all match.
Data: form 2,573 -> 5,651 rows, Dragon Register 216 -> 273, new route PDF
fingerprint. Supersedes the automated pull request #2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ
703 lines
56 KiB
JavaScript
703 lines
56 KiB
JavaScript
/* app.js — renders the Threshing Route Atlas from engine.js results. All numbers come from ThreshEngine. */
|
||
(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_Blue", widthMode: "traffic", minN: 10, conds: {},
|
||
fxOutcome: "blue_meadow", fxFactor: "resolution", rtTarget: "see_Blue", rtMin: 10,
|
||
};
|
||
|
||
// ------------------------------------------------------------ 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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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(E.TARGETS[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 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 = {};
|
||
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);
|
||
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 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");
|
||
$("#data-status").innerHTML = `
|
||
<span><b>${state.res.n.toLocaleString()}</b> runs${state.res.n !== state.allRuns.length ? ` of ${state.allRuns.length.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>` : ""}`;
|
||
}
|
||
|
||
// ------------------------------------------------------------ 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 Blue 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 = E.rankRoutes(state.runs, "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(s.term)} (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 how you react to the first dragon.</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 fk = formS.reduce((a, [, w]) => a + w.k, 0), fn = formS.reduce((a, [, w]) => a + w.n, 0);
|
||
const fw = E.wilson(fk, fn);
|
||
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 source, goal, direction and date (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", 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
|
||
const RARE_T = ["bond_Blue", "bond_Black", "see_Blue", "see_shadow"];
|
||
const OTHER_T = ["bond_Red", "bond_Green", "bond_Orange", "bond_Brown", "bond_any"];
|
||
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>`;
|
||
};
|
||
$("#targets-rare").innerHTML = RARE_T.map((t) => chip(t, t.startsWith("bond"))).join("");
|
||
$("#targets-other").innerHTML = OTHER_T.map((t) => chip(t, false)).join("");
|
||
$$(".tchip").forEach((b) => b.addEventListener("click", () => { state.target = b.dataset.t; $("#best-routes").innerHTML = ""; renderTargets(); renderMap(); }));
|
||
}
|
||
const ORDER = {
|
||
company: ["Alone", "1 Squadmate", "2 Squadmates", "Unknown"],
|
||
direction: ["East", "Center", "West", "Multiple", "Unknown"],
|
||
first_sighting: ["Red", "Orange", "Brown", "Green", "Unsure", "Unknown"],
|
||
post_path: ["Forest", "West", "East", "(no fork)", "Unknown"],
|
||
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;
|
||
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]));
|
||
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 colX = (i) => left + (i * (W - left - right - nodeW)) / (S - 1);
|
||
const cols = E.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
|
||
E.STAGES.forEach((s, i) => {
|
||
const chance = s.key === "first_sighting" || s.key === "encounter";
|
||
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${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("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 = 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 lx = p.x + nodeW + 5, ly = p.y + p.h / 2 + 4;
|
||
if (ly - 11 > lastLabelBottom || isSel) {
|
||
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}` : "";
|
||
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>`;
|
||
g.addEventListener("mousemove", (e) => showTip(e, 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(); } });
|
||
});
|
||
});
|
||
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}`;
|
||
}
|
||
|
||
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 = E.rankRoutes(state.runs, 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>
|
||
<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("")}
|
||
</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
|
||
// 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]) => k !== "Unknown/lost count").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)).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, 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" },
|
||
];
|
||
panels.forEach((P) => {
|
||
const vals = d.map((r) => E.wilson(r[P.k], r[P.n]));
|
||
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")], ["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 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>
|
||
<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>`;
|
||
const cols = ["Red", "Orange", "Brown", "Green", "Unsure", "Unknown"];
|
||
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.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] && !["Unsure", "Unknown"].includes(c) && !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}</td></tr>`).join("")}</tbody></table>`;
|
||
}
|
||
|
||
// ------------------------------------------------------------ route table
|
||
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.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(); });
|
||
}
|
||
const rk = E.rankRoutes(state.runs, 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(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.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>`;
|
||
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 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>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);
|
||
}
|
||
|
||
// ------------------------------------------------------------ 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 = E.rankRoutes(state.runs, "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 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");
|
||
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 = 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 = ""; });
|
||
$("#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, runsCSV };
|
||
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); });
|
||
})();
|