// v1.9: Explore | Compare. An ARIA tablist like the ratings page's (dnield.com/ratings), keyboard
// operable: Tab reaches the selected tab, the arrow keys, Home and End move and select.
viewof tab = {
const nav = document.createElement("div");
nav.className = "dash-tabs";
nav.setAttribute("role", "tablist");
nav.setAttribute("aria-label", "Dashboard views");
const btns = [["explore", "Explore"], ["compare", "Compare"]].map(([id, label]) => {
const b = document.createElement("button");
b.type = "button";
b.id = `dash-tab-${id}`;
b.dataset.tab = id;
b.setAttribute("role", "tab");
b.setAttribute("aria-controls", `dash-${id}`);
b.textContent = label;
nav.appendChild(b);
return b;
});
const show = (id, focus) => btns.forEach((b) => {
const on = b.dataset.tab === id;
b.setAttribute("aria-selected", String(on));
b.tabIndex = on ? 0 : -1;
if (on && focus) b.focus();
});
const set = (id, focus) => {
show(id, focus);
if (nav.value === id) return;
nav.value = id;
nav.dispatchEvent(new Event("input", { bubbles: true }));
};
btns.forEach((b) => b.addEventListener("click", () => set(b.dataset.tab, false)));
nav.addEventListener("keydown", (e) => {
const i = btns.findIndex((b) => b.dataset.tab === nav.value), n = btns.length;
const j = { ArrowRight: (i + 1) % n, ArrowLeft: (i - 1 + n) % n, Home: 0, End: n - 1 }[e.key];
if (j === undefined) return;
e.preventDefault();
set(btns[j].dataset.tab, true);
});
nav.value = hashParams.get("tab") === "compare" ? "compare" : "explore";
show(nav.value, false);
return nav;
}Who plays your opening?
How often an opening is played, online on Lichess and over the board in top players’ classical games, split into White’s choices and Black’s — and how often you’d meet it compared with your opponent
Play a line on the board, or pick one of the 3,810 named openings below it, then choose the games: Lichess online games, by speed and rating, or classical over-the-board games among top players (the SuperGMs, or one of 47 leading players as White, Black or either). True reach is the share of games that reach the position by any move order. Because moves alternate, the share along your move order factorises exactly into W, the product of White’s choices, times B, the product of Black’s. The same factors answer a second question: if you always play the line, you get it whenever your opponent cooperates.
VERSION = "228b2592ec10"
asset = (path) => new URL(`${path}?v=${VERSION}`, document.baseURI).href
dashMod = import(asset("dash.js"))
boardMod = import(asset("board.js"))
controlsMod = import(asset("controls.js"))
exportMod = import(asset("export.js"))
makeStore = dashMod.makeStore
toPlain = dashMod.toPlain
otbAs = dashMod.otbAs
toPlainCompare = dashMod.toPlainCompare
monthDate = dashMod.monthDate
monthLabel = dashMod.monthLabel
createBoard = boardMod.createBoard
multiSelect = controlsMod.multiSelect
bandSummary = controlsMod.bandSummary
selectBox = controlsMod.selectBox
combobox = controlsMod.combobox
chartWithDownload = exportMod.chartWithDownload
exportChart = exportMod.exportChart
EXPORT_FONT = exportMod.EXPORT_FONT
slugify = exportMod.slug
Plot = import("https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6.16/+esm")
ChessLib = import("https://cdn.jsdelivr.net/npm/chess.js@1.4.0/dist/esm/chess.js")
store = makeStore("data", VERSION)
ix = store.loadIndex()
COL = ({ white: "#2a78d6", black: "#eb6834", draw: "#b9b8b0", reach: "#1baf7a", prod: "#52514e", ink: "#0b0b0b", muted: "#898781", grid: "#e1e0d9" })
M = ix.n_months
openingRows = ix.openings.map((o) => ({ id: o.id, eco: o.eco, name: o.name, moves: ix.pgn(o.moves), line: o.moves, plies: o.moves.length, rank: o.rank }))
ITALIAN = ["e4", "e5", "Nf3", "Nc6", "Bc4"]
// Shareable state in the URL hash:
// #moves=e4,e5,Nf3&speeds=Blitz,Rapid&bands=1600,1800&from=2019-01&to=2021-12&smooth=3&metric=results&zoom=score&view=levels
// (from= defaults to 2017-01 and to= to the latest month; both are written only when they differ;
// metric=results opens panel 1 on Win percentage and is written only then: Popularity is the default;
// zoom=score opens Win percentage on "Score only (zoomed)", is written only then, and is ignored without metric=results)
// (#opening=<id> from v1 links still works: it sets the board to that line)
// v1.9, the Compare tab:
// #moves=e4,c5,Nf3,Nc6,Bb5&tab=compare&a.speeds=Bullet,Blitz&a.bands=0,1000&b.speeds=Rapid&b.bands=2000,2200,2500
// tab=compare opens the Compare tab and is written only while it is selected (links without tab= open on Explore).
// a.speeds / a.bands / b.speeds / b.bands set Set A and Set B, each written only when it differs from the
// default (Set A: all speeds, bands 0/1000/1200/1400, i.e. under 1600; Set B: all speeds, bands 2000/2200/2500).
// speeds= / bands= stay Explore's filters; moves, from/to and smooth are shared by both tabs.
// v2.0, the Classical OTB Games source (data/otb/, loaded only once a set uses it):
// #moves=e4,c5,Nf3,Nc6,Bb5&src=otb&who=carlsen&as=white
// #moves=e4,c5,Nf3,Nc6,Bb5&tab=compare&a.bands=2000,2200,2500&b.src=otb
// src=otb (Explore) / a.src=otb / b.src=otb pick the source (default lichess); who= / a.who= / b.who= the
// OTB set (default supergm, the elite set; else a roster slug such as carlsen); as= / a.as= / b.as= the
// player's colour (white | black; default either). Each is written only when it differs from the default,
// and who/as only for an OTB set (as only for a player). OTB pools a rolling 12 months, and so does
// Compare whenever either set is OTB; the 3-month pooling (smooth=3) applies to Lichess-only views.
// The window runs to 2026-10 when every set in view is OTB, else to Lichess's last month (2026-07);
// to= is written only when the window ends before the view's last month. Links without these keys
// open exactly as in v1.9.
hashParams = new URLSearchParams(location.hash.slice(1))
hashList = (k) => hashParams.has(k) ? hashParams.get(k).split(",").filter(Boolean) : null
// v2.0: the window selectors run over both sources' months: OTB_MONTHS is data/otb/index.json's
// n_months (2013-01..2026-10), fixed here so the selectors need no OTB fetch (checked when it loads).
OTB_MONTHS = 166
MU = Math.max(M, OTB_MONTHS)
monthIndex = (s) => {
const m = /^(\d{4})-(\d{2})$/.exec(s ?? "");
const [y0, mm0] = ix.first_month.split("-").map(Number);
return m ? Math.max(0, Math.min(MU - 1, (+m[1] - y0) * 12 + (+m[2] - mm0))) : null;
}
// The window opens on 2017-01 .. latest month by default (2013-2016 is the early,
// thin Lichess era); #from= / #to= override it. A link that gives only an early
// #to= (v1.4 omitted from= when it was the first month) keeps meaning "from the start".
DEFAULT_FROM = monthIndex("2017-01") ?? 0
hashMonth = (k, dflt) => monthIndex(hashParams.get(k)) ?? dflt
fromDefault = (hashMonth("to", MU - 1) < DEFAULT_FROM) ? 0 : DEFAULT_FROM
// v2.0: the last month of the view a link opens on (all sets in view OTB: 2026-10; else 2026-07)
MviewInit = (hashParams.get("tab") === "compare" ? hashSrc("a.") === "otb" && hashSrc("b.") === "otb" : hashSrc("") === "otb") ? OTB_MONTHS : M
initialMoves = hashList("moves") ?? (hashParams.has("opening") ? ix.byId.get(+hashParams.get("opening"))?.moves : null) ?? ITALIAN
// v1.9: the Compare tab's two filter sets (owner's defaults: under 1600 vs 2000+, all speeds)
DEFAULT_A = ({ speeds: ix.speeds, bands: [0, 1000, 1200, 1400] })
DEFAULT_B = ({ speeds: ix.speeds, bands: [2000, 2200, 2500] })
SET = ({ a: "#0b0b0b", b: "#1baf7a" }) // Set A ink, Set B aqua (White and Black keep #2a78d6 / #eb6834)
// v2.0: the source of a set and, for OTB, who and the colour ("" = Explore's keys, "a." / "b." = the sets')
SRC_OPTIONS = [["lichess", "Lichess Online Games"], ["otb", "Classical OTB Games"]]
AS_OPTIONS = [["either", "Either"], ["white", "White"], ["black", "Black"]]
hashSrc = (pre) => hashParams.get(`${pre}src`) === "otb" ? "otb" : "lichess"
hashWho = (pre) => /^[a-z0-9-]+$/.test(hashParams.get(`${pre}who`) ?? "") ? hashParams.get(`${pre}who`) : "supergm"
hashAs = (pre) => ["white", "black"].includes(hashParams.get(`${pre}as`)) ? hashParams.get(`${pre}as`) : "either"
hashSet = (k, D0) => ({
src: hashSrc(`${k}.`), who: hashWho(`${k}.`), as: hashAs(`${k}.`),
speeds: hashList(`${k}.speeds`)?.filter((s) => ix.speeds.includes(s)) ?? D0.speeds,
bands: hashList(`${k}.bands`)?.map(Number).filter((b) => ix.bands.includes(b)) ?? D0.bands })
// the Who list: SuperGMs pinned first, then the roster by name, each with its classical game count
whoOptions = (oix) => {
const f = d3.format(",");
const sg = oix.who[0];
return [{ id: sg.id, text: "SuperGMs", hint: `${f(sg.games)} games`, match: "elite super grandmasters supergm" },
...oix.who.slice(1).slice().sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)).map((w) => ({ id: w.id, text: w.name, hint: `${f(w.games)} games`, match: w.full }))];
}
// a Who combobox; its list is filled once the OTB index is loaded (fillWho), never before OTB is chosen
whoControl = (init, cls = "") => {
const c = combobox({ label: "Who", value: init, pendingText: init === "supergm" ? "SuperGMs" : "…" });
if (cls) c.classList.add(...cls.split(" "));
return c;
}
fillWho = (c) => store.otbIndex().then((oix) => {
if (oix.n_months !== OTB_MONTHS) console.error(`data/otb/index.json n_months ${oix.n_months} != OTB_MONTHS ${OTB_MONTHS}`);
c.setOptions(whoOptions(oix), "supergm");
})
// One set's row on the Compare tab: a colour swatch, its name, and its own Speed and Rating dropdowns
// (controls.js). .value = { speeds, bands }; an "input" event fires on every change.
// v2.0: each row also has its own Source; Lichess shows Speed and Rating, Classical OTB shows Who and,
// for a player, Plays as. .value = { src, speeds, bands, who, as } (the hidden filters keep their values).
setControl = (name, color, init) => {
const row = document.createElement("div");
row.className = "dash-set";
row.setAttribute("role", "group");
row.setAttribute("aria-label", `${name} filters`);
const lab = document.createElement("span");
lab.className = "dash-set-k";
lab.innerHTML = `<span class="dash-swatch" style="background:${color}" aria-hidden="true"></span>${name}`;
const src = selectBox({ label: "Source", options: SRC_OPTIONS, value: init.src, className: "dash-src" });
const sp = multiSelect({ label: "Speed", options: ix.speeds, value: init.speeds });
const bd = multiSelect({ label: "Rating", options: ix.bands, value: init.bands,
format: (b) => ix.band_labels[ix.bands.indexOf(b)], summary: bandSummary(ix.bands, ix.band_labels) });
const who = whoControl(init.who);
const as = selectBox({ label: "Plays as", options: AS_OPTIONS, value: init.as, className: "dash-as" });
row.append(lab, src, sp, bd, who, as);
let filled = false;
const upd = () => {
row.value = { src: src.value, speeds: sp.value, bands: bd.value, who: who.value, as: as.value };
row.classList.toggle("is-otb", src.value === "otb");
row.classList.toggle("is-player", who.value !== "supergm");
if (src.value === "otb" && !filled) { filled = true; fillWho(who); }
};
for (const c of [src, sp, bd, who, as]) c.addEventListener("input", upd); // runs before the event bubbles to the row's own listeners
upd();
row.controls = { src, speeds: sp, bands: bd, who, as };
return row;
}// Which tab shows: a class on <body> (dash.css hides the other tab's panel, Explore's Speed and Rating
// cells on Compare and the set rows on Explore), and the tab panels' ARIA roles.
{
document.body.classList.toggle("dash-tab-compare", tab === "compare");
for (const id of ["explore", "compare"]) {
const el = document.getElementById(`dash-${id}`);
if (!el) continue;
el.setAttribute("role", "tabpanel");
el.setAttribute("aria-labelledby", `dash-tab-${id}`);
el.hidden = (id === "compare") !== (tab === "compare");
}
}// v2.0: the months of both sources (to 2026-10); the To list shows only the months of the sets in view
// (options past the view's last month are hidden and To is held at that month), see windowFit below.
// The initial To is already within the view the link opens on, so loading never moves it.
viewof period = Inputs.form({
from: Inputs.select(d3.range(MU), { label: "From", value: Math.min(hashMonth("from", fromDefault), MviewInit - 1), format: (i) => monthLabel(ix, i) }),
to: Inputs.select(d3.range(MU), { label: "To", value: Math.min(hashMonth("to", MU - 1), MviewInit - 1), format: (i) => monthLabel(ix, i) }),
}){
// Title: the board position's own name (by position, so transpositions are
// named); off the tree, the deepest named position before it, "+ k moves".
const re = offTree ? await reentry : null;
const named = re && re.o ? { o: re.o, at: line.length } : namedAlong;
const depth = re && re.o ? line.length : (offTree ? line.length : treeLine.length);
let title = named ? `<span class="eco">${esc(named.o.eco)}</span>${esc(named.o.name)}` : "Start position";
if (named && named.at < depth) title += ` <span class="dash-after">+ ${depth - named.at} move${depth - named.at > 1 ? "s" : ""}</span>`;
let note = "";
if (offTree) {
const at = `${Math.floor(inTree / 2) + 1}.${inTree % 2 ? ".." : ""} ${esc(line[inTree])}`;
note = `<div class="dash-off"><b>Outside the data.</b> ${at} leaves the named-opening tree: the data cover the 7,855
positions on the 3,810 named lines and every move between them, nothing else. The panels below follow your line
up to ${inTree ? `<span class="dash-moves">${esc(lineText(treeLine))}</span>` : "the start position"}.</div>`;
if (re && re.o) note += `<div class="dash-off back"><b>Back in the tree:</b> this position is
<b>${esc(re.o.eco)} ${esc(re.o.name)}</b>, but your move order passes through positions outside the tree, so W and B
can't be followed along it. <button type="button" class="dash-link" data-opening="${re.o.id}">Show it by its named order</button></div>`;
}
const d = D(`<div class="dash-chosen">${title}</div><div class="dash-moves">${esc(lineText(line))}</div>${note}`);
d.querySelectorAll("button[data-opening]").forEach((b) => b.addEventListener("click", () => viewof line.setLine(ix.byId.get(+b.dataset.opening).moves)));
return d;
}{
if (offTree) return D(`<p class="dash-note">No explorer data here: this position is outside the named-opening tree.</p>`);
if (tab === "compare") {
// v1.9, Compare: each move's share of the games continuing from here, in Set A and in Set B
const [ea, eb] = await Promise.all([store.explorerSet(res.line.node, setA, m0, m1),
store.explorerSet(res.line.node, setB, m0, m1)]);
const fmt = d3.format(",");
const byB = new Map(eb.rows.map((r) => [r.san, r]));
const rowsC = ea.rows.map((r) => ({ san: r.san, a: r, b: byB.get(r.san) }))
.sort((x, y) => (y.a.n + (y.b?.n ?? 0)) - (x.a.n + (x.b?.n ?? 0)));
const cell = (r) => r ? `<td class="num" title="${fmt(r.n)} games">${pct(r.share)}</td>` : `<td class="num">—</td>`;
const body = rowsC.map((r) => `<tr><td><button type="button" class="dash-mv" data-san="${esc(r.san)}">${esc(r.san)}</button></td>
${cell(r.a)}${cell(r.b)}</tr>`).join("")
+ (ea.T || eb.T ? `<tr class="other"><td>other moves</td><td class="num">${pct(ea.other_share)}</td><td class="num">${pct(eb.other_share)}</td></tr>` : "");
const d = D(`<table class="dash-ex dash-ex-cmp"><thead><tr><th>Move</th><th class="num">${key(SET.a)} Share in A</th><th class="num">${key(SET.b)} Share in B</th></tr></thead>
<tbody>${body || `<tr><td colspan="3" class="dash-note">No continuations in the data for these sets.</td></tr>`}</tbody></table>
<div class="dash-note">${fmt(ea.T)} games in Set A and ${fmt(eb.T)} in Set B continued from this position (${monthLabel(ix, m0)}–${monthLabel(ix, m1)}).
Each share is of that set's games. Moves listed are those leading to another position in the named-opening tree; "other moves" is everything else.</div>`);
d.querySelectorAll("button[data-san]").forEach((b) => b.addEventListener("click", () => viewof line.setLine([...line, b.dataset.san])));
return d;
}
const ex = await store.explorerSet(res.line.node, specE, m0, m1);
const rowsEx = [...ex.rows].sort((a, b) => b.n - a.n);
const fmt = d3.format(",");
const wdlBar = (w) => {
const t = w[0] + w[1] + w[2];
if (!t) return `<span class="dash-wdl empty"></span>`;
const seg = (x, cls) => x / t >= 0.12 ? `<span class="${cls}" style="width:${100 * x / t}%">${Math.round(100 * x / t)}%</span>` : `<span class="${cls}" style="width:${100 * x / t}%"></span>`;
return `<span class="dash-wdl" title="All-time results ${srcE === "otb" ? "for this OTB set" : "for the selected speeds and ratings"}: White ${pct(w[0] / t)}, draws ${pct(w[1] / t)}, Black ${pct(w[2] / t)}">${seg(w[0], "w")}${seg(w[1], "d")}${seg(w[2], "b")}</span>`;
};
const body = rowsEx.map((r) => `<tr><td><button type="button" class="dash-mv" data-san="${esc(r.san)}">${esc(r.san)}</button></td>
<td class="num">${fmt(r.n)}</td><td class="num">${pct(r.share)}</td><td>${wdlBar(r.wdl)}</td></tr>`).join("")
+ (ex.T ? `<tr class="other"><td>other moves</td><td class="num">${fmt(ex.other)}</td><td class="num">${pct(ex.other_share)}</td><td></td></tr>` : "");
const d = D(`<table class="dash-ex"><thead><tr><th>Move</th><th class="num">Games</th><th class="num">Share</th><th>White · draw · Black</th></tr></thead>
<tbody>${body || `<tr><td colspan="4" class="dash-note">No continuations in the data for this selection.</td></tr>`}</tbody></table>
<div class="dash-note">${fmt(ex.T)} games continued from this position (${monthLabel(ix, m0)}–${monthLabel(ix, m1)}, ${srcE === "otb" ? `classical OTB, ${esc(otbDesc(specE))}` : "selected speeds and ratings"}).
Moves listed are those leading to another position in the named-opening tree; "other moves" is everything else.
Result bars are all-time for ${srcE === "otb" ? "this OTB set" : "the selected speeds and ratings"}.</div>`);
d.querySelectorAll("button[data-san]").forEach((b) => b.addEventListener("click", () => viewof line.setLine([...line, b.dataset.san])));
return d;
}specE = srcE === "otb" ? ({ src: "otb", who: whoE, as: asE }) : ({ src: "lichess", speeds, bands })
anyOtbC = setA.src === "otb" || setB.src === "otb"
MviewE = srcE === "otb" ? OTB_MONTHS : M
MviewC = setA.src === "otb" && setB.src === "otb" ? OTB_MONTHS : M
Mview = tab === "compare" ? MviewC : MviewE
m1 = Math.min(Math.max(period.from, period.to), Mview - 1)
m0 = Math.min(period.from, period.to, m1)
// pooling: OTB a fixed rolling 12 months; Compare pools both sets at 12 whenever either is OTB
smoothE = srcE === "otb" ? 12 : (pooled ? 3 : 1)
smoothC = anyOtbC ? 12 : (pooled ? 3 : 1)
smooth = smoothE
res = store.computeSet(line, specE, m0, m1, smoothE)
inTree = res.line.inTree
treeLine = line.slice(0, inTree)
offTree = inTree < line.length
// the named opening at a node: prefer the one whose moves are exactly this
// line; else the shortest named line ending there (all share the position)
nameAt = (node, moves) => {
const c = ix.namesAt.get(node);
if (!c) return null;
const key = moves.join(" ");
return c.find((o) => o.moves.join(" ") === key) ?? [...c].sort((a, b) => a.moves.length - b.moves.length || a.rank - b.rank)[0];
}
// deepest named position along the in-tree part of the line
namedAlong = {
let v = ix.root, best = null;
const nodes = [ix.root, ...res.line.edges.map((e) => e.child)];
for (let i = nodes.length - 1; i >= 0 && !best; i--) {
const o = nameAt(nodes[i], treeLine.slice(0, i));
if (o) best = { o, at: i };
}
return best;
}
// a line that left the tree may have come back into it (a transposition
// through positions outside S): recognise the position by its FEN
reentry = offTree ? store.nodeOfFen(viewof line.fen()).then((v) => (v === null ? null : { node: v, o: nameAt(v, []) })) : null
rows = res.cnt ? d3.range(m0, m1 + 1).map((m, j) => {
const s = res.ser, a = res.att;
const r = { m, date: monthDate(ix, m), label: monthLabel(ix, m) };
for (const k of ["W", "B", "WxB", "reach", "gap", "E_white", "E_black", "edge_white", "edge_black",
"edge_white_reach", "edge_black_reach", "W_lo", "W_hi", "B_lo", "B_hi", "reach_lo", "reach_hi",
"win_w", "win_d", "win_b", "score", "score_lo", "score_hi", "res_n",
"spec_edge_white", "spec_edge_black", "spec_edge_white_lo", "spec_edge_white_hi",
"spec_edge_black_lo", "spec_edge_black_hi"])
r[k] = Number.isFinite(s[k][m]) ? s[k][m] : NaN;
r.c_W = a.c_W[j]; r.c_B = a.c_B[j]; r.c_total = a.c_total[j];
return r;
}) : []
win = res.cnt ? res.win : ({ c: [], T: [], n: [] })
// v2.0: OTB set names (the roster's names arrive with the OTB index, loaded only when a set uses it)
oix = srcE === "otb" || anyOtbC ? store.otbIndex() : null
OTB_CREDIT = "OTB: The Week in Chess, Lichess broadcasts and other archives, deduplicated"
SG_RULE = "higher-rated player >2700, other ≥2600"
fullOf = (who) => who === "supergm" ? "SuperGMs" : (oix?.byWho.get(who)?.full ?? who)
shortOf = (who) => oix?.byWho.get(who)?.short ?? who
otbDesc = (S) => S.who === "supergm" ? `SuperGMs (${SG_RULE})`
: `${fullOf(S.who)}${otbAs(S) === "either" ? ", either colour" : ` as ${otbAs(S) === "white" ? "White" : "Black"}`}`
// a player with a colour chosen: "white" | "black" (the panels then name the player and the opponents)
playerSide = (S) => S.src === "otb" && S.who !== "supergm" && otbAs(S) !== "either" ? otbAs(S) : null
pside = playerSide(specE)
pname = pside ? shortOf(whoE) : null
// board side "W" | "B" -> who plays it in this set: the player's name, "Opponents", or null (no player)
sideWho = (side) => !pside ? null : ((side === "W") === (pside === "white") ? pname : "Opponents")
sideMoves = (side) => `${sideWho(side) === "Opponents" ? "Opponents'" : `${sideWho(side)}'s`} moves (${side === "W" ? "White" : "Black"})`
popNote = {
if (srcE === "otb") {
// v2.0.1: no minimum game count for OTB, so a point is missing only where no game supports it; say why
const noWB = rows.length > 0 && !rows.some((d) => Number.isFinite(d.W));
const noReach = rows.length > 0 && !rows.some((d) => Number.isFinite(d.reach));
const thin = noReach ? " No game in this set reaches this position in the window."
: noWB ? " No monthly W and B here: in every point's 12 months some move of this order was not played." : "";
return `Classical OTB, ${otbDesc(specE)}, ${monthLabel(ix, m0)}–${monthLabel(ix, m1)}, rolling 12 months (each monthly point pools the trailing 12).${thin}`;
}
const sp = speeds.length === ix.speeds.length ? "all speeds" : (speeds.join(" + ") || "no speeds");
const bl = bands.length === ix.bands.length ? "all ratings" : (bands.map((b) => ix.band_labels[ix.bands.indexOf(b)]).join(", ") || "no ratings");
return `Lichess rated standard games (no arena/swiss, no bots), ${monthLabel(ix, m0)}–${monthLabel(ix, m1)}, ${sp}, ${bl}. `
+ (smooth === 3 ? "Monthly, counts pooled over 3 months." : "Monthly.");
}
pct = (x, d = 1) => !Number.isFinite(x) ? "—" : x >= 0.1 ? `${(100 * x).toFixed(d)}%` : x >= 0.001 ? `${(100 * x).toFixed(d + 1)}%` : `${(100 * x).toPrecision(2)}%`
tickPct = (d) => d3.format("~%")(+d.toPrecision(6))
// Log-axis ticks at 1/2/3/5, 1/3 or 1 x 10^k depending on the span, so a wide
// range never draws a thicket of unlabeled minor ticks.
logTicks = (vals) => {
const v = vals.filter((x) => Number.isFinite(x) && x > 0);
// v2.0: no data at all (every month suppressed, common for a thin OTB set): no y ticks, rather than
// Plot's default 1..10 log ticks, whose labels crowd in a short export
if (!v.length) return [];
const lo = d3.min(v), hi = d3.max(v), span = Math.log10(hi / lo);
if (span < 0.6) return d3.ticks(lo, hi, 5).filter((t) => t > 0); // narrow range: plain nice ticks
const mult = span > 2.5 ? [1] : span > 1.2 ? [1, 3] : [1, 2, 3, 5];
const out = [];
for (let e = Math.floor(Math.log10(lo)) - 1; e <= Math.ceil(Math.log10(hi)); e++)
for (const mlt of mult) { const t = +(mlt * 10 ** e).toPrecision(6); if (t >= lo / 1.15 && t <= hi * 1.15) out.push(t); }
return out.length >= 2 ? out : undefined;
}
oneIn = (p) => !Number.isFinite(p) || p <= 0 ? "—" : p >= 0.5 ? `1 in ${(1 / p).toFixed(1)}` : `1 in ${d3.format(",")(Math.round(1 / p))}`
// the specialist edge, two decimals below 10 (1.87×, 0.53×)
times2 = (x) => !Number.isFinite(x) ? "—" : x >= 10 ? `${d3.format(",")(Math.round(x))}×` : `${x.toFixed(2)}×`
key = (color, kind = "solid") => `<span class="dash-key ${kind}" style="border-color:${color};${kind === "box" ? `background:${color}` : ""}"></span>`
esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c])
D = (s) => { const d = document.createElement("div"); d.innerHTML = s; return d; }
font = ({ fontFamily: "'Atkinson Hyperlegible', sans-serif", fontSize: "12px", background: "transparent", overflow: "visible" })
lineText = (moves) => moves.length ? ix.pgn(moves) : "the start position"
// keep the URL in step with the state, so any view can be shared
{
const p = new URLSearchParams();
p.set("moves", line.join(","));
if (speeds.length !== ix.speeds.length) p.set("speeds", speeds.join(","));
if (bands.length !== ix.bands.length) p.set("bands", bands.join(","));
// v2.0: the source, and for OTB who and the colour (each only when it differs from the default)
const otbKeys = (pre, S) => {
if (S.src !== "otb") return;
p.set(`${pre}src`, "otb");
if (S.who !== "supergm") { p.set(`${pre}who`, S.who); if (otbAs(S) !== "either") p.set(`${pre}as`, otbAs(S)); }
};
otbKeys("", specE);
if (m0 !== DEFAULT_FROM) p.set("from", monthLabel(ix, m0));
if (m1 !== Mview - 1) p.set("to", monthLabel(ix, m1));
if (pooled) p.set("smooth", "3");
if (metric1 === "Win percentage") p.set("metric", "results");
if (zoom1) p.set("zoom", "score");
if (view2 === "Levels") p.set("view", "levels");
// v1.9: the Compare tab (only while selected) and its two sets (each only when it differs from the default)
if (tab === "compare") p.set("tab", "compare");
const same = (x, y) => x.length === y.length && x.every((v) => y.includes(v));
for (const [k, S, D0] of [["a", setA, DEFAULT_A], ["b", setB, DEFAULT_B]]) {
otbKeys(`${k}.`, S);
if (!same(S.speeds, D0.speeds)) p.set(`${k}.speeds`, S.speeds.join(","));
if (!same(S.bands, D0.bands)) p.set(`${k}.bands`, S.bands.join(","));
}
history.replaceState(null, "", "#" + p.toString().replace(/%2C/g, ","));
}chartName = {
if (!treeLine.length) return { title: "Start position", subtitle: "Move order: none (the start position)", slug: "start-position" };
const nm = namedAlong;
const exact = nm && nm.at === treeLine.length && nm.o.moves.join(" ") === treeLine.join(" ");
const base = nm ? `${nm.o.eco} ${nm.o.name}` : "Unnamed line";
let subtitle = `Move order: ${ix.pgn(treeLine)}`;
if (offTree) subtitle += `. The entered line, ${ix.pgn(line)}, leaves the named-opening tree after this; the chart follows it up to here.`;
return {
title: exact ? base : `${base} (via ${ix.pgn(treeLine)})`,
subtitle,
slug: nm ? `${nm.o.eco}_${slugify(nm.o.name)}` : "line",
};
}
// v2.0: an OTB export names its set in the subtitle and credits the OTB archives; a Lichess export is as v1.9
exportSpec = (panel, panelSlug, build, legend, footNote) => ({
build, legend,
title: `${chartName.title} — ${panel}`,
subtitle: srcE === "otb" ? `Classical OTB, ${otbDesc(specE)}, rolling 12 months. ${chartName.subtitle}` : chartName.subtitle,
footer: footNote ? `${popNote} ${footNote}` : popNote,
source: srcE === "otb" ? `Source: dnield.com/openings · ${OTB_CREDIT}` : "Source: dnield.com/openings · Lichess open database",
filename: `opening_${chartName.slug}_${panelSlug}_${monthLabel(ix, m0)}_${monthLabel(ix, m1)}.png`,
})
// On-screen charts are built with no preset (P undefined) and keep their fixed size and fonts.
// A PNG export passes its preset: the banner keeps the v1.5 look exactly; the others get
// phone-readable type (P.f.axis px) and margins/ticks sized to it, and the height the layout
// leaves. mlK: widest y tick label, in em, so marginLeft follows the font size.
plotLayout = (P, h, w, { hDefault, mlBanner, mlK }) => {
if (!P) return { height: hDefault, marginLeft: mlBanner, marginTop: 30, style: font };
if (P.legacy) return { height: hDefault, marginLeft: mlBanner, marginTop: 30, style: { ...font, fontFamily: EXPORT_FONT, fontSize: "13px" } };
const ml = Math.round(P.f.axis * mlK);
return { height: h, marginLeft: ml, marginTop: Math.round(P.f.axis * 2.9), marginBottom: Math.round(P.f.axis * 2.5),
style: { ...font, fontFamily: EXPORT_FONT, fontSize: `${P.f.axis}px` } };
}
// fewer x ticks on a narrow export, so the year/month labels do not collide
// y ticks: at most one per 2.4 lines of text in the plot's height (a thinned subset of the list)
yMax = (P, L) => P && !P.legacy ? Math.max(2, Math.floor((L.height - L.marginTop - L.marginBottom) / (P.f.axis * 2.4))) : Infinity
thin = (a, k) => !a || a.length <= k ? a : Array.from({ length: k }, (_, i) => a[Math.round(i * (a.length - 1) / (k - 1))])
xTicks = (P, w, ml) => P && !P.legacy ? { ticks: Math.max(2, Math.floor((w - ml - 24) / (P.f.axis * 6.2))), tickPadding: Math.round(P.f.axis * 0.45) } : {}
// gate-4 hook: the page's own numbers for any line, read back through the browser pane
{
window.dashCompute = async (moves, sp, bd, a, b, sm) => {
const r = await store.compute(moves, sp, bd, a, b, sm);
const out = toPlain(r, a, b);
out.explorer = await store.explorer(r.line.node, sp, bd, a, b);
return out;
};
// v1.9: the Compare tab's numbers (sets A, B = { speeds, bands }) for gate 4's compare group
window.dashCompare = async (moves, A, B, a, b, sm) => toPlainCompare(await store.compare(moves, A, B, a, b, sm), a, b);
// v2.0: any set spec ({ src: "otb", who, as } or { speeds, bands }) through the same code the panels use
window.dashComputeSet = async (moves, S, a, b, sm) => {
const r = await store.computeSet(moves, S, a, b, sm);
const out = toPlain(r, a, b);
out.explorer = await store.explorerSet(r.line.node, S, a, b);
return out;
};
window.dashOtbIndex = () => store.otbIndex();
window.dashIndex = ix;
return true;
}// v2.0: which filters show (dash.css): Explore's Speed/Rating or Who/Plays as, the fixed OTB pooling
{
document.body.classList.toggle("dash-src-otb", srcE === "otb");
document.body.classList.toggle("dash-who-player", whoE !== "supergm");
document.body.classList.toggle("dash-pool-fixed", tab === "compare" ? anyOtbC : srcE === "otb");
}// v2.0, windowFit: the To (and From) lists offer only the months of the sets in view, and a To at the
// view's last month follows it (2026-07 <-> 2026-10) when the view changes.
{
const f = viewof period, [sf, st] = f.querySelectorAll("select");
const last = f.lastView ?? Mview;
for (const sel of [sf, st]) for (const o of sel.options) { const off = +o.value >= Mview; o.hidden = off; o.disabled = off; }
f.lastView = Mview;
for (const [sel, isTo] of [[sf, false], [st, true]]) {
const i = +sel.value;
const want = i >= Mview ? Mview - 1 : (isTo && i === last - 1 && Mview > last ? Mview - 1 : i);
// the select's own input event: Inputs.select takes the new value and the form passes it on
if (want !== i) { sel.value = String(want); sel.dispatchEvent(new Event("input", { bubbles: true })); }
}
}zoom1 = results1 && show1 === "Score only (zoomed)"
// results ship only at the named openings' final positions
hasResults = !!(res.cnt && res.ser.hasResults)
COL_DRAW = "#8f8d86" // COL.draw darkened so a thin line holds up on white
sc = (x) => Number.isFinite(x) ? x.toFixed(3) : "—"
games = (x) => !Number.isFinite(x) ? "—" : x >= 1e6 ? `${(x / 1e6).toFixed(2)} M` : d3.format(",")(x)
RESULTS_FOOT = "Results of games reaching this position by any move order; score = (wins + ½ draws) / games, White's view."!results1 ? D(`<div class="dash-legend">
<span>${key(COL.reach)} True reach: any move order</span>
<span>${key(COL.prod, "dashed")} W×B: this move order only</span>
<span>${key(COL.reach, "box").replace("background:", "opacity:.25;background:")} 95% interval</span></div>`)
: !hasResults ? html``
: zoom1 ? D(`<div class="dash-legend">
<span>${key(COL.ink, "thick")} Average score (White's view)</span>
<span>${key(COL.ink, "box").replace("background:", "opacity:.18;background:")} 95% interval on the score</span></div>`)
: D(`<div class="dash-legend">
<span>${key(COL.white)} White wins</span><span>${key(COL_DRAW)} Draws</span><span>${key(COL.black)} Black wins</span>
<span>${key(COL.ink, "thick")} Average score (White's view)</span>
<span>${key(COL.ink, "box").replace("background:", "opacity:.18;background:")} 95% interval on the score</span></div>`)chart1 = (w, h, P) => { const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: 4.9 }); return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: scale1, label: "share of games", tickFormat: tickPct, grid: true, ...(scale1 === "log" ? { ticks: thin(logTicks(rows.flatMap((d) => [d.reach_lo, d.reach_hi, d.WxB])), yMax(P, L)) } : { nice: true, ...(P && !P.legacy ? { ticks: yMax(P, L) } : {}) }) },
marks: [
Plot.areaY(rows, { x: "date", y1: "reach_lo", y2: "reach_hi", fill: COL.reach, fillOpacity: 0.18, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "reach", stroke: COL.reach, strokeWidth: 2, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "WxB", stroke: COL.prod, strokeWidth: 2, strokeDasharray: "5,4", curve: "monotone-x" }),
Plot.ruleX(rows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(rows, Plot.pointerX({ x: "date", y: "reach",
title: (d) => `${d.label}\nTrue reach ${pct(d.reach)} (${pct(d.reach_lo)}–${pct(d.reach_hi)})\nW×B ${pct(d.WxB)}\nThis order carries ${pct(d.gap, 0)}` })),
],
}) }// Win percentage: results of the games reaching the final position by any move order.
// The score (W + D/2)/A shares the percentage axis (a score of 0.5 sits at 50%).
chart1r = (w, h, P) => { const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: 3.6 }); return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: "linear", label: "share of games / score", tickFormat: tickPct, grid: true, nice: true,
domain: [0, Math.max(0.6, d3.max(rows.flatMap((d) => [d.win_w, d.win_b, d.score_hi]).filter(Number.isFinite)) ?? 0)],
...(P && !P.legacy ? { ticks: yMax(P, L) } : {}) },
marks: [
Plot.areaY(rows, { x: "date", y1: "score_lo", y2: "score_hi", fill: COL.ink, fillOpacity: 0.18, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "win_d", stroke: COL_DRAW, strokeWidth: 1.75, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "win_b", stroke: COL.black, strokeWidth: 1.75, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "win_w", stroke: COL.white, strokeWidth: 1.75, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "score", stroke: COL.ink, strokeWidth: 2.75, curve: "monotone-x" }),
Plot.ruleX(rows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(rows, Plot.pointerX({ x: "date", y: "score",
title: (d) => `${d.label}\nWhite wins ${pct(d.win_w)}\nDraws ${pct(d.win_d)}\nBlack wins ${pct(d.win_b)}\nScore ${sc(d.score)} (${sc(d.score_lo)}–${sc(d.score_hi)})\n${games(d.res_n)} games` })),
],
}) }zoomDomain = {
const v = rows.flatMap((d) => [d.score_lo, d.score_hi]).filter(Number.isFinite);
const lo = v.length ? d3.min(v) : 0.5, hi = v.length ? d3.max(v) : 0.5, padY = 0.1 * (hi - lo);
let a = lo - padY, b = hi + padY;
if (b - a < 0.04) { const mid = (lo + hi) / 2; a = mid - 0.02; b = mid + 0.02; }
if (a < 0) { b = Math.min(1, b - a); a = 0; }
if (b > 1) { a = Math.max(0, a - (b - 1)); b = 1; }
return [a, b];
}
// ticks on whole hundredths (two decimals, as the summary's "average score 0.522"):
// the finest of 0.01 / 0.02 / 0.05 / 0.1 / 0.2 that gives at most k ticks
zoomTicks = (k) => {
const [a, b] = zoomDomain;
for (const st of [0.01, 0.02, 0.05, 0.1, 0.2]) {
const t = d3.range(Math.ceil(a / st - 1e-9), Math.floor(b / st + 1e-9) + 1).map((i) => +(i * st).toFixed(2));
if (t.length <= k || st === 0.2) return t;
}
}
chart1z = (w, h, P) => { const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: 3.6 }); return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: "linear", label: "average score (White's view)", domain: zoomDomain, grid: true,
ticks: zoomTicks(Math.min(6, yMax(P, L))), tickFormat: d3.format(".2f") },
marks: [
...(zoomDomain[0] <= 0.5 && 0.5 <= zoomDomain[1] ? [
Plot.ruleY([0.5], { stroke: COL.muted, strokeWidth: 1, strokeDasharray: "4,3", ariaLabel: () => "even-rule" }),
Plot.text([0.5], { y: (d) => d, text: () => "even", frameAnchor: "right", textAnchor: "end", lineAnchor: "bottom", dy: -3,
fill: COL.prod, ariaLabel: () => "even-label" })] : []),
Plot.areaY(rows, { x: "date", y1: "score_lo", y2: "score_hi", fill: COL.ink, fillOpacity: 0.18, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "score", stroke: COL.ink, strokeWidth: 2.75, curve: "monotone-x" }),
Plot.ruleX(rows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(rows, Plot.pointerX({ x: "date", y: "score",
title: (d) => `${d.label}
Score ${sc(d.score)} (${sc(d.score_lo)}–${sc(d.score_hi)})
${games(d.res_n)} games` })),
],
}) }{
if (!results1)
return chartWithDownload(chart1(Math.max(240, Math.min(width, 1100))), () => exportSpec("How popular is it?", "popularity",
(w, h, P) => chart1(w, h, P), [
{ label: "True reach: any move order", color: COL.reach, kind: "line" },
{ label: "W×B: this move order only", color: COL.prod, kind: "dashed" },
{ label: "95% interval", color: COL.reach, kind: "area" }]));
if (!hasResults) {
// no results here: a note in the chart's place, and its Download disabled
const box = chartWithDownload(D(`<p class="dash-callout dash-unavail">Monthly results are available for the named openings'
final positions. Enter or pick a named opening.</p>`), () => null);
const b = box.querySelector(".dash-dl");
b.disabled = true; b.classList.add("off");
b.title = "Nothing to download: monthly results are available for the named openings' final positions";
return box;
}
if (zoom1)
return chartWithDownload(chart1z(Math.max(240, Math.min(width, 1100))), () => exportSpec("How does it score? (score only)", "results-score",
(w, h, P) => chart1z(w, h, P), [
{ label: "Average score (White's view)", color: COL.ink, kind: "line" },
{ label: "95% interval on the score", color: COL.ink, kind: "area" }], RESULTS_FOOT));
return chartWithDownload(chart1r(Math.max(240, Math.min(width, 1100))), () => exportSpec("How does it score?", "results",
(w, h, P) => chart1r(w, h, P), [
{ label: "White wins", color: COL.white, kind: "line" },
{ label: "Draws", color: COL_DRAW, kind: "line" },
{ label: "Black wins", color: COL.black, kind: "line" },
{ label: "Average score (White's view)", color: COL.ink, kind: "line" },
{ label: "95% interval on the score", color: COL.ink, kind: "area" }], RESULTS_FOOT));
}!results1 ? html`<div class="dash-note">${popNote}</div>
<p class="dash-copy">Over this window, this move order accounts for
<b>${pct(win.gap, 0)}</b> of the games that reach the position (W×B ${pct(win.WxB)} vs true reach ${pct(win.reach)}).</p>`
: !hasResults ? html`<div class="dash-note">${popNote}</div>`
: html`<div class="dash-note">${popNote} ${RESULTS_FOOT}</div>
<p class="dash-copy">Over this window: White <b>${pct(win.win_w)}</b> · Draw <b>${pct(win.win_d)}</b> · Black <b>${pct(win.win_b)}</b>
· average score <b>${sc(win.score)}</b> (${games(win.res_n)} games)${pside ? html`; ${esc(pname)}'s score <b>${sc(pside === "white" ? win.score : 1 - win.score)}</b>` : ""}.</p>`2 · Who moved it, White or Black?
view2 === "Levels" ? D(`<p class="dash-sub"><b>W</b> = how often White makes White's moves on the line when offered the
chance (1st move included); <b>B</b> = the same for Black. W × B is the dashed line in panel 1.</p>
<div class="dash-legend"><span>${key(COL.white)} ${pside ? `W: ${esc(sideMoves("W"))}` : "W: White steers here"}</span><span>${key(COL.black)} ${pside ? `B: ${esc(sideMoves("B"))}` : "B: Black allows it"}</span>
<span>shaded: 95% interval</span></div>`)
: D(`<p class="dash-sub">Change since the start of the window (first 12 months, geometric mean). On a log scale the two
contributions add up exactly to the net change, with no interaction left over.</p>
<div class="dash-legend"><span>${key(COL.white, "box")} ${pside ? esc(sideMoves("W")) : "White's contribution"}</span><span>${key(COL.black, "box")} ${pside ? esc(sideMoves("B")) : "Black's contribution"}</span>
<span>${key(COL.ink)} Net change in W×B</span></div>`)chart2 = (w, h, P) => {
const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: view2 === "Levels" ? 4.9 : 3.7 });
if (view2 === "Levels") {
return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: scale1, label: "probability", tickFormat: tickPct, grid: true, ...(scale1 === "log" ? { ticks: thin(logTicks(rows.flatMap((d) => [d.W_lo, d.W_hi, d.B_lo, d.B_hi])), yMax(P, L)) } : { nice: true, ...(P && !P.legacy ? { ticks: yMax(P, L) } : {}) }) },
marks: [
Plot.areaY(rows, { x: "date", y1: "W_lo", y2: "W_hi", fill: COL.white, fillOpacity: 0.15, curve: "monotone-x" }),
Plot.areaY(rows, { x: "date", y1: "B_lo", y2: "B_hi", fill: COL.black, fillOpacity: 0.15, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "W", stroke: COL.white, strokeWidth: 2, curve: "monotone-x" }),
Plot.lineY(rows, { x: "date", y: "B", stroke: COL.black, strokeWidth: 2, curve: "monotone-x" }),
Plot.ruleX(rows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(rows, Plot.pointerX({ x: "date", y: "W",
title: (d) => `${d.label}\nW (${sideWho("W") ?? "White"}) ${pct(d.W)} (${pct(d.W_lo)}–${pct(d.W_hi)})\nB (${sideWho("B") ?? "Black"}) ${pct(d.B)} (${pct(d.B_lo)}–${pct(d.B_hi)})` })),
],
});
}
const long = rows.flatMap((d) => [
{ date: d.date, side: "W", v: d.c_W, label: d.label }, // not "White"/"Black": Plot would
{ date: d.date, side: "B", v: d.c_B, label: d.label }, // read those as CSS colours
]).filter((d) => Number.isFinite(d.v));
const ext = d3.extent([...long.map((d) => d.v), ...rows.map((d) => d.c_total).filter(Number.isFinite),
...rows.map((d) => Math.max(0, d.c_W) + Math.max(0, d.c_B)).filter(Number.isFinite),
...rows.map((d) => Math.min(0, d.c_W) + Math.min(0, d.c_B)).filter(Number.isFinite), 0]);
const cands = [-0.9, -0.75, -0.5, -0.33, -0.2, -0.1, 0, 0.1, 0.25, 0.5, 0.75, 1, 2, 4, 9];
const slack = P && !P.legacy ? 0 : 0.05; // on screen and in the banner a tick may sit just past the data; the phone exports keep ticks inside the plot
const ticks = cands.map((p) => Math.log(1 + p)).filter((t) => t >= ext[0] - slack && t <= ext[1] + slack);
const fmt = (t) => { const p = Math.exp(t) - 1; return Math.abs(p) < 1e-9 ? "0%" : `${p > 0 ? "+" : ""}${Math.round(100 * p)}%`; };
// v2.0.2: a few-game Classical OTB set's noisy months stretch the range while the candidates crowd around 0
// (-10% / 0% / +10% collided in the Phone export): keep 0 and walk outwards as Compare's gap chart does.
// Lichess keeps its v2.0.1 ticks exactly.
let yTicksA = thin(ticks, yMax(P, L));
if (srcE === "otb") {
const minGap = 0.9 * (ext[1] - ext[0]) / Math.max(1, thinScreen(P, L) - 1);
const walk = (side) => { const out = []; let last = 0;
for (const t of side) if (Math.abs(t - last) >= minGap) { out.push(t); last = t; }
return out; };
yTicksA = [...walk(ticks.filter((t) => t < 0).sort((a, b) => b - a)).reverse(), ...(ticks.includes(0) ? [0] : []),
...walk(ticks.filter((t) => t > 0).sort((a, b) => a - b))];
}
return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), d3.utcMonth.offset(monthDate(ix, m1), 1)], ...xTicks(P, w, L.marginLeft) },
y: { label: "change vs window start (log scale)", ticks: yTicksA, tickFormat: fmt, grid: true },
color: { domain: ["W", "B"], range: [COL.white, COL.black] },
marks: [
Plot.rectY(long, { x: "date", interval: "month", y: "v", fill: "side", order: ["W", "B"], insetLeft: 0.5, insetRight: 0.5, fillOpacity: 0.9 }),
Plot.ruleY([0], { stroke: COL.ink, strokeOpacity: 0.4 }),
Plot.lineY(rows, { x: (d) => d3.utcDay.offset(d.date, 14), y: "c_total", stroke: COL.ink, strokeWidth: 1.5 }),
Plot.ruleX(rows, Plot.pointerX({ x: (d) => d3.utcDay.offset(d.date, 14), stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(rows, Plot.pointerX({ x: (d) => d3.utcDay.offset(d.date, 14), y: "c_total",
title: (d) => `${d.label}\nNet ${fmt(d.c_total)}\n${pside ? `${sideMoves("W")} ${fmt(d.c_W)}\n${sideMoves("B")} ${fmt(d.c_B)}` : `White ${fmt(d.c_W)}\nBlack ${fmt(d.c_B)}`}\n(log contributions add: ${d.c_W?.toFixed(3)} + ${d.c_B?.toFixed(3)} = ${d.c_total?.toFixed(3)})` })),
],
});
}chartWithDownload(chart2(Math.max(240, Math.min(width, 1100))), () => view2 === "Levels"
? exportSpec("Who moved it: W and B", "who-moved-it-levels", (w, h, P) => chart2(w, h, P), [
{ label: pside ? `W: ${sideMoves("W")}` : "W: White steers here", color: COL.white, kind: "line" },
{ label: pside ? `B: ${sideMoves("B")}` : "B: Black allows it", color: COL.black, kind: "line" },
{ label: "shaded: 95% interval", color: COL.muted, kind: "area" }])
: exportSpec("Who moved it: change since the window start", "who-moved-it-attribution", (w, h, P) => chart2(w, h, P), [
{ label: pside ? sideMoves("W") : "White's contribution", color: COL.white, kind: "box" },
{ label: pside ? sideMoves("B") : "Black's contribution", color: COL.black, kind: "box" },
{ label: "Net change in W×B (log scale; the parts add exactly)", color: COL.ink, kind: "line" }])){
const fmt = (t) => !Number.isFinite(t) ? "—" : `${t >= 0 ? "+" : ""}${Math.round(100 * (Math.exp(t) - 1))}%`;
const last = rows.filter((d) => Number.isFinite(d.c_total)).slice(-12);
const g = (k) => last.length ? d3.mean(last, (d) => d[k]) : NaN;
return html`<div class="dash-note">${popNote}</div>
${view2 === "Attribution" ? html`<p class="dash-copy">Last 12 months vs the first 12 of the window: net <b>${fmt(g("c_total"))}</b>
= ${pside ? esc(sideMoves("W")) : "White"} <b>${fmt(g("c_W"))}</b> and ${pside ? esc(sideMoves("B")) : "Black"} <b>${fmt(g("c_B"))}</b> (log contributions, so they add exactly).</p>` : ""}`;
}3 · How often would you see it, and how often would your opponent?
{
const P = persp;
const tile = (k, v, s, color, cls = "") => `<div class="dash-tile${cls}"><div class="k">${color ? key(color) : ""}${k}</div><div class="v">${v}</div><div class="s">${s}</div></div>`;
let tiles;
if (P === "Both sides") {
const r = win.spec_edge_white; // B ÷ W: > 1 favours White, < 1 favours Black
const fav = !Number.isFinite(r) ? "—" : r > 1 ? `favours White ${times2(r)}` : r < 1 ? `favours Black ${times2(win.spec_edge_black)}` : "even (1.00×)";
// v2.0: with a player and a colour chosen, the tiles name the player and the opponents
const gets = (side) => { const x = sideWho(side); return `${esc(x)} (${side === "W" ? "White" : "Black"}'s moves) ${x === "Opponents" ? "get" : "gets"} it`; };
const decide = (side) => { const x = sideWho(side); return x === "Opponents" ? "the opponents'" : `${esc(x)}'s`; };
tiles = pside ? [
tile(gets("W"), oneIn(win.E_white), `E<sub>White</sub> = B: ${decide("B")} moves decide`, COL.white),
tile(gets("B"), oneIn(win.E_black), `E<sub>Black</sub> = W: ${decide("W")} moves decide`, COL.black),
tile("Specialist edge", fav, `E<sub>White</sub> ÷ E<sub>Black</sub> = B ÷ W = ${times2(r)}: how many times more often ${esc(sideWho("W"))} (White) reach${sideWho("W") === "Opponents" ? "" : "es"} this than ${esc(sideWho("B"))} (Black)`, null, " dash-spec"),
] : [
tile("A White specialist gets it", oneIn(win.E_white), `E<sub>White</sub> = B: Black's moves decide`, COL.white),
tile("A Black specialist gets it", oneIn(win.E_black), `E<sub>Black</sub> = W: White's moves decide`, COL.black),
tile("Specialist edge", fav, `E<sub>White</sub> ÷ E<sub>Black</sub> = B ÷ W = ${times2(r)}: how many times more often a White specialist reaches this than a Black one`, null, " dash-spec"),
];
} else if (pside) {
// v2.0: a player with a colour chosen: the tiles name the player and the opponents (colours by board side)
const w = P === "White", O = w ? "Black" : "White";
const me = sideWho(w ? "W" : "B"), them = sideWho(w ? "B" : "W");
const plays = (x) => x === "Opponents" ? "play" : "plays", poss = (x) => x === "Opponents" ? "the opponents'" : `${x}'s`;
const Eyou = w ? win.E_white : win.E_black, Eopp = w ? win.E_black : win.E_white;
const spec = w ? win.spec_edge_white : win.spec_edge_black;
tiles = [
tile(`${esc(me)} (always ${plays(me)} ${P}'s moves)`, oneIn(Eyou), `E<sub>${P}</sub> = ${w ? "B" : "W"}: ${esc(poss(them))} moves decide`, w ? COL.white : COL.black),
tile(`${esc(them)} (${O}'s moves) ${them === "Opponents" ? "get" : "gets"} it`, oneIn(Eopp), `E<sub>${O}</sub> = ${w ? "W" : "B"}: ${esc(poss(me))} moves decide`, w ? COL.black : COL.white),
tile("Specialist edge", times2(spec), `E<sub>${P}</sub> ÷ E<sub>${O}</sub> = ${w ? "B ÷ W" : "W ÷ B"}: how many times more often ${esc(me === "Opponents" ? "the opponents reach" : `${me} reaches`)} this than ${esc(them === "Opponents" ? "the opponents do" : `${them} does`)}, as ${O}`, null, " dash-spec"),
];
} else {
const w = P === "White", O = w ? "Black" : "White";
const Eyou = w ? win.E_white : win.E_black, Eopp = w ? win.E_black : win.E_white;
const spec = w ? win.spec_edge_white : win.spec_edge_black;
tiles = [
tile(`You (always play ${P}'s moves)`, oneIn(Eyou), `E<sub>${P}</sub> = ${w ? "B" : "W"}: your opponent's moves decide`, w ? COL.white : COL.black),
tile(`Your opponent (a ${O} specialist) gets it`, oneIn(Eopp), `E<sub>${O}</sub> = ${w ? "W" : "B"}: ${P}'s moves decide`, w ? COL.black : COL.white),
tile("Specialist edge", times2(spec), `E<sub>you</sub> ÷ E<sub>opponent</sub> = ${w ? "B ÷ W" : "W ÷ B"}: how many times more often you reach this than an opponent who specialises in ${O}`, null, " dash-spec"),
];
}
return D(`<div class="dash-tiles">${tiles.join("")}</div>`);
}series3 = pside
// v2.0: a player with a colour chosen: name the player and the opponents (colours by board side)
? (persp === "Black"
? [{ k: "E_black", name: `${sideWho("B")} (Black)`, color: COL.black }, { k: "E_white", name: `${sideWho("W")} (White)`, color: COL.white }]
: [{ k: "E_white", name: `${sideWho("W")} (White)`, color: COL.white }, { k: "E_black", name: `${sideWho("B")} (Black)`, color: COL.black }])
: persp === "Both sides"
? [{ k: "E_white", name: "White specialist", color: COL.white }, { k: "E_black", name: "Black specialist", color: COL.black }]
: persp === "White"
? [{ k: "E_white", name: "You (White)", color: COL.white }, { k: "E_black", name: "Your opponent (Black specialist)", color: COL.black }]
: [{ k: "E_black", name: "You (Black)", color: COL.black }, { k: "E_white", name: "Your opponent (White specialist)", color: COL.white }]// the specialist edge in a tooltip line: E_you ÷ E_opponent, or its direction under "Both sides"
specLine3 = (d) => persp === "White" ? `Specialist edge ${times2(d.spec_edge_white)}`
: persp === "Black" ? `Specialist edge ${times2(d.spec_edge_black)}`
: !Number.isFinite(d.spec_edge_white) ? "Specialist edge —"
: d.spec_edge_white >= 1 ? `Favours White ${times2(d.spec_edge_white)}` : `Favours Black ${times2(d.spec_edge_black)}`chart3 = (w, h, P) => {
const L = plotLayout(P, h, w, { hDefault: 280, mlBanner: 76, mlK: 5.4 });
const inv = (x) => Number.isFinite(x) && x > 0 ? 1 / x : NaN;
return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: "log", label: "once every … games", grid: true, tickFormat: (d) => `1 in ${d3.format("~s")(d)}`,
ticks: thin(logTicks(rows.flatMap((d) => series3.map((s) => inv(d[s.k])))), yMax(P, L)) },
marks: [
...series3.map((s) => Plot.lineY(rows, { x: "date", y: (d) => inv(d[s.k]), stroke: s.color, strokeWidth: 2.25, curve: "monotone-x" })),
Plot.ruleX(rows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(rows, Plot.pointerX({ x: "date", y: (d) => inv(d[series3[0].k]),
title: (d) => [d.label, ...series3.map((s) => `${s.name} ${oneIn(d[s.k])}`), specLine3(d)].join("\n") })),
],
});
}{
const legend3 = series3.map((s) => ({ label: s.name, color: s.color, kind: "line" }));
const legend = legend3.map((l) => `<span>${key(l.color, l.kind === "dashed" ? "dashed" : "solid")} ${l.name ?? l.label}</span>`).join("");
const panel = pside ? `${series3[0].name} vs ${series3[1].name}`
: persp === "Both sides" ? "White specialist vs Black specialist" : `You (${persp}) vs a ${persp === "White" ? "Black" : "White"} specialist`;
const box = chartWithDownload(chart3(Math.max(240, Math.min(width, 1100))), () => exportSpec(panel, "you-vs-opponent", (w, h, P) => chart3(w, h, P), legend3,
"A specialist always plays one side's moves of the line, so meets it when the other side cooperates (White: B, Black: W). On the log scale the gap between the two lines is the specialist edge."));
return html`${D(`<div class="dash-legend">${legend}</div>`)}${box}
<p class="dash-sub">On the log scale, the gap between the two lines is the specialist edge: how many times more often one side reaches this than the other.</p><div class="dash-note">${popNote}</div>`;
}4 · The move path
{
if (!res.cnt) return D(`<p class="dash-note">No moves yet.</p>`);
const c = win.c, T = win.T, n = win.n;
const fin = c.filter(Number.isFinite);
const minC = fin.length ? Math.min(...fin) : NaN;
const body = res.cnt.edges.map((e, i) => {
const side = (i % 2 === 0 ? "White" : "Black") + (pside ? ` (${esc(sideWho(i % 2 === 0 ? "W" : "B"))})` : "");
const col = i % 2 === 0 ? COL.white : COL.black;
const thin = T[i] < (srcE === "otb" ? 1 : 30) || n[i] < 1; // v2.0.1: no minimum game count for OTB
const label = `${Math.floor(i / 2) + 1}.${i % 2 === 0 ? "" : ".."} ${esc(e.san)}`;
const bar = Number.isFinite(c[i]) ? `<span class="dash-bar" style="width:${Math.max(1, 160 * c[i])}px;background:${col}"></span>` : "";
return `<tr class="${c[i] === minC ? "rare" : ""}"><td>${i + 1}</td><td>${key(col)} ${side}</td><td class="dash-moves">${label}</td>
<td class="num">${thin ? `<span class="dash-gap">${pct(c[i])}</span>` : pct(c[i])}</td><td>${bar}</td>
<td class="num">${d3.format(",")(n[i])}</td><td class="num">${d3.format(",")(T[i])}</td></tr>`;
}).join("");
return D(`<p class="dash-sub">Each move's share among the games that reached the position before it, pooled over the window.
W multiplies the blue rows and B the orange ones. The rarest move is highlighted.</p>
<table class="dash-path"><thead><tr><th>Ply</th><th>Side</th><th>Move</th><th class="num">c<sub>i</sub></th><th></th>
<th class="num">Played</th><th class="num">Reached</th></tr></thead><tbody>${body}</tbody></table>
<p class="dash-copy">Window: W = <b>${pct(win.W)}</b>, B = <b>${pct(win.B)}</b>, W×B = <b>${pct(win.WxB)}</b>,
true reach = <b>${pct(win.reach)}</b> of ${d3.format(",")(win.N)} games.</p>
<div class="dash-note">${popNote}</div>`);
}Monthly numbers (table view)
Inputs.table(rows.map((d) => ({ month: d.label, W: d.W, B: d.B, "W×B": d.WxB, reach: d.reach, gap: d.gap,
"specialist edge (White = B÷W)": d.spec_edge_white })), {
format: { W: (x) => pct(x), B: (x) => pct(x), "W×B": (x) => pct(x), reach: (x) => pct(x), gap: (x) => pct(x, 0),
"specialist edge (White = B÷W)": times2 }, rows: 12 })Data, Lichess Online Games: the Lichess open database, rated standard games 2013-01 to 2026-07, through a per-month opening-tree extract (counts summed over ply, the Lichess-explorer convention). Bots, arena/swiss games and abandoned or cheat-terminated games are excluded. Rating bands are by the two players’ average rating. Opening names: lichess-org/chess-openings.
Data, Classical OTB Games: over-the-board games from The Week in Chess, Lichess broadcasts and other archives, deduplicated, 2013-01 to 2026-10, at a verified classical time control only. Each event’s time control was reviewed against archived reports and clocks; rapid, blitz and games of unclear speed are left out, as are correspondence and engine games. SuperGMs are the games in which one player was rated strictly above 2700 and the other at least 2600, by the ratings recorded with the game (not peak ratings). Each player set holds one of 47 leading players’ classical games against every opponent and at every age, juniors’ early games included; a game between two of the 47 counts in both players’ sets. A month holds tens to a few hundred such games, so every OTB point pools a rolling 12 months (the trailing 12 months of counts, with 95% intervals from the pooled counts), and Compare pools both sets the same way whenever either is OTB. OTB points have no minimum game count (Lichess points need 30 games at each step), so a point resting on a handful of games is shown with its wide interval; a player’s line can rest on very few games. The 2020 gap is real: classical over-the-board events largely stopped during the pandemic. The moves are counted exactly as for Lichess (the first 30 plies, positions on the named-opening tree). The data cover the positions on the named lines and every move between two of them. Panel 1’s win percentages are the results of the games that reach a named opening’s final position by any move order, counted from White’s side. Board: chess.js (BSD-2-Clause). Chess pieces by Colin M.L. Burnett (Cburnett), via Wikimedia Commons, used under the BSD licence (licence and sources).
cmpOn = tab === "compare"
cmp = cmpOn ? store.compare(line, setA, setB, m0, m1, smoothC) : null
cmpReady = !!(cmp && cmp.ser)
CMP_SET_KEYS = ["W", "B", "WxB", "reach", "reach_lo", "reach_hi", "score", "score_lo", "score_hi", "res_n", "win_w", "win_d", "win_b",
"spec_edge_white", "spec_edge_white_lo", "spec_edge_white_hi", "spec_edge_black", "spec_edge_black_lo", "spec_edge_black_hi"]
cmpRows = cmpReady ? d3.range(m0, m1 + 1).map((m) => {
const r = { m, date: monthDate(ix, m), label: monthLabel(ix, m) };
const fin = (x) => (Number.isFinite(x) ? x : NaN);
for (const k of CMP_SET_KEYS) { r[`a_${k}`] = fin(cmp.a.ser[k][m]); r[`b_${k}`] = fin(cmp.b.ser[k][m]); }
for (const k of dashMod.COMPARE_KEYS) r[k] = fin(cmp.ser[k][m]);
return r;
}) : []
gw = cmpReady ? cmp.win : ({})
wa = cmpReady ? cmp.a.win : ({})
wb = cmpReady ? cmp.b.win : ({})
speedText = (sp) => sp.length === ix.speeds.length ? "all speeds" : sp.length ? sp.join(" + ") : "no speeds"
bandText = (bd) => {
if (bd.length === ix.bands.length) return "all ratings";
if (!bd.length) return "no ratings";
const s = bandSummary(ix.bands, ix.band_labels)(bd, ix.bands).replace(/^Rating: /, "");
if (/^under \d+$/.test(s)) return `<${s.slice(6)}`;
if (/ bands$/.test(s)) return ix.bands.filter((b) => bd.includes(b)).map((b) => ix.band_labels[ix.bands.indexOf(b)]).join(", ");
return s;
}
// v2.0: an OTB set is named by its source; with any OTB set in view a Lichess set says "Lichess, ..." too
setDesc = (S) => S.src === "otb" ? `Classical OTB, ${otbDesc(S)}` : `${anyOtbC ? "Lichess, " : ""}${speedText(S.speeds)}, ${bandText(S.bands)}`
setsLine = `A: ${setDesc(setA)} · B: ${setDesc(setB)}`
setPop = (S) => S.src === "otb" ? `classical OTB games, ${otbDesc(S)}` : `Lichess rated standard games (no arena/swiss, no bots), ${speedText(S.speeds)}, ${bandText(S.bands)}`
cmpPopNote = !anyOtbC ? `Lichess rated standard games (no arena/swiss, no bots), ${monthLabel(ix, m0)}–${monthLabel(ix, m1)}. `
+ `Set A: ${setDesc(setA)}; Set B: ${setDesc(setB)}. ` + (smoothC === 3 ? "Monthly, counts pooled over 3 months." : "Monthly.")
: `Set A: ${setPop(setA)}; Set B: ${setPop(setB)}. ${monthLabel(ix, m0)}–${monthLabel(ix, m1)}. `
+ "Both sets pooled over a rolling 12 months (each monthly point pools the trailing 12), so the gap compares like with like."
cmpSource = !anyOtbC ? "Source: dnield.com/openings · Lichess open database"
: setA.src === "otb" && setB.src === "otb" ? `Source: dnield.com/openings · ${OTB_CREDIT}`
: `Source: dnield.com/openings · Lichess open database · ${OTB_CREDIT}`
// a Compare chart's PNG export: as Explore's, with both sets named in the subtitle and the footer
cmpSpec = (panel, panelSlug, build, legend, footNote) => ({
build, legend,
title: `${chartName.title} — ${panel}`,
subtitle: `${setsLine}. ${chartName.subtitle}`,
footer: footNote ? `${cmpPopNote} ${footNote}` : cmpPopNote,
source: cmpSource,
filename: `opening_${chartName.slug}_${panelSlug}_${monthLabel(ix, m0)}_${monthLabel(ix, m1)}.png`,
})
// B vs A from a log gap: a ratio ("2.30×") or a log-percent change ("+40%")
xr = (t) => Number.isFinite(t) ? times2(Math.exp(t)) : "—"
gapPct = (t) => {
if (!Number.isFinite(t)) return "—";
const r = Math.round(100 * (Math.exp(t) - 1));
return r === 0 ? "0%" : `${r > 0 ? "+" : ""}${d3.format(",")(r)}%`;
}
ctile = (k, v, s, color) => `<div class="dash-tile"><div class="k">${color ? key(color) : ""}${k}</div><div class="v">${v}</div><div class="s">${s}</div></div>`
// a chart's place taken by a note, with its Download disabled (as Explore's "not available" state)
noteBox = (msg, why) => {
const box = chartWithDownload(D(`<p class="dash-callout dash-unavail">${msg}</p>`), () => null);
const b = box.querySelector(".dash-dl");
b.disabled = true; b.classList.add("off"); b.title = why;
return box;
}
setLegend = (extra = "") => `<div class="dash-legend"><span>${key(SET.a, "thick")} Set A: ${esc(setDesc(setA))}</span>
<span>${key(SET.b, "thick")} Set B: ${esc(setDesc(setB))}</span>${extra}</div>`
setLegendExport = (extra = []) => [{ label: `Set A: ${setDesc(setA)}`, color: SET.a, kind: "line" },
{ label: `Set B: ${setDesc(setB)}`, color: SET.b, kind: "line" }, ...extra]
// on-screen y ticks for the gap chart: at most this many (exports use their own budget)
thinScreen = (P, L, k = 8) => P && !P.legacy ? yMax(P, L) : k{
if (!cmpOn) return html``;
const parts = [anyOtbC ? `<p class="dash-sub">One opening under two filter sets, drawn in the same charts:
<b>Set A</b> (${esc(setDesc(setA))}, ink) and <b>Set B</b> (${esc(setDesc(setB))}, aqua). Choose each set's source and
filters above; the line and the window are shared with Explore. With a Classical OTB set in the comparison, both sets
are pooled over a rolling 12 months, so the gap compares like with like.</p>`
: `<p class="dash-sub">One opening under two filter sets, drawn in the same charts:
<b>Set A</b> (${esc(setDesc(setA))}, ink) and <b>Set B</b> (${esc(setDesc(setB))}, aqua). Choose each set's speeds and
ratings above; the line, the window and the pooling are shared with Explore.</p>`];
if (!cmpReady) parts.push(`<p class="dash-callout">Make a move on the board (or pick a named opening) to compare it between the two sets.</p>`);
else if (cmp.same) parts.push(`<p class="dash-callout dash-same"><b>The two sets are the same</b>, so there is no gap between them to show.
Change Set A's or Set B's speeds or ratings above.</p>`);
else if (cmp.overlap && setA.src === "otb") {
// v2.0: two OTB sets can share games (roster players' mutual games; a player's elite games are SuperGMs games too)
parts.push(`<p class="dash-callout dash-overlap"><b>The sets can share games:</b> a game between two of the roster players
counts in both players' sets, and a player's games against the elite count among the SuperGMs' too. Shared games make
the gap smaller than between separate groups, and the 95% intervals, which treat the sets as independent, are only approximate.</p>`);
}
else if (cmp.overlap) {
const sp = setA.speeds.filter((s) => setB.speeds.includes(s)), bd = setA.bands.filter((b) => setB.bands.includes(b));
parts.push(`<p class="dash-callout dash-overlap"><b>The sets overlap:</b> games at ${esc(speedText(sp))}, ${esc(bandText(bd))} count in
both, so the two sets share games. The gap between them is smaller than between separate groups would be, and the 95% intervals,
which treat the sets as independent, are only approximate.</p>`);
}
for (const [nm, S] of [["Set A", setA], ["Set B", setB]])
if (cmpReady && S.src !== "otb" && (!S.speeds.length || !S.bands.length)) parts.push(`<p class="dash-callout dash-empty">${nm} selects no games: choose at least one speed and one rating band.</p>`);
return D(parts.join(""));
}1 · How popular is it, A vs B?
cchart1 = (w, h, P) => { const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: 4.9 }); return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: "log", label: "share of games (true reach)", tickFormat: tickPct, grid: true,
ticks: thin(logTicks(cmpRows.flatMap((d) => [d.a_reach_lo, d.a_reach_hi, d.b_reach_lo, d.b_reach_hi])), yMax(P, L)) },
marks: [
Plot.areaY(cmpRows, { x: "date", y1: "a_reach_lo", y2: "a_reach_hi", fill: SET.a, fillOpacity: 0.12, curve: "monotone-x" }),
Plot.areaY(cmpRows, { x: "date", y1: "b_reach_lo", y2: "b_reach_hi", fill: SET.b, fillOpacity: 0.2, curve: "monotone-x" }),
Plot.lineY(cmpRows, { x: "date", y: "a_reach", stroke: SET.a, strokeWidth: 2, curve: "monotone-x" }),
Plot.lineY(cmpRows, { x: "date", y: "b_reach", stroke: SET.b, strokeWidth: 2, curve: "monotone-x" }),
Plot.ruleX(cmpRows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(cmpRows, Plot.pointerX({ x: "date", y: "b_reach",
title: (d) => `${d.label}\nA ${pct(d.a_reach)} (${pct(d.a_reach_lo)}–${pct(d.a_reach_hi)})\nB ${pct(d.b_reach)} (${pct(d.b_reach_lo)}–${pct(d.b_reach_hi)})\nB ÷ A ${xr(d.gap_net)} (${xr(d.gap_net_lo)}–${xr(d.gap_net_hi)})` })),
],
}) }{
if (!cmpReady) return html``;
const r = Math.exp(gw.gap_net);
const head = cmp.same ? ctile("B vs A, true reach", "the same sets", "Set A and Set B select the same games", null)
: ctile("B vs A, true reach", !Number.isFinite(r) ? "—" : r >= 1 ? `${times2(r)} more common` : `${times2(1 / r)} rarer`,
`in B than in A over this window (B ÷ A = ${xr(gw.gap_net)}, 95% interval ${xr(gw.gap_net_lo)}–${xr(gw.gap_net_hi)}, the sets treated as independent)`, null);
const tiles = [ctile("Set A", pct(wa.reach), `${oneIn(wa.reach)} games · ${esc(setDesc(setA))}`, SET.a),
ctile("Set B", pct(wb.reach), `${oneIn(wb.reach)} games · ${esc(setDesc(setB))}`, SET.b), head];
const box = chartWithDownload(cchart1(Math.max(240, Math.min(width, 1100))), () => cmpSpec("How popular is it, A vs B?", "compare-popularity",
(w, h, P) => cchart1(w, h, P), setLegendExport([{ label: "95% interval", color: COL.muted, kind: "area" }]),
"True reach: the share of games that reach the position by any move order. B ÷ A interval by the delta method, the sets treated as independent."));
return html`${D(`<div class="dash-tiles">${tiles.join("")}</div>${setLegend(`<span>shaded: 95% interval</span>`)}`)}${box}
<div class="dash-note">${cmpPopNote}</div>
<p class="dash-copy">Over this window the position is reached in <b>${pct(wa.reach)}</b> of Set A's games and <b>${pct(wb.reach)}</b>
of Set B's: B ÷ A = <b>${xr(gw.gap_net)}</b>.</p>`;
}2 · Who explains the gap?
// B vs A per month, split exactly: White's part gap_W = log(W_B/W_A) and Black's gap_B = log(B_B/B_A)
// stack to the net gap_WxB = log(WxB_B/WxB_A). The same log-percent axis as panel 2's Attribution view.
cchart2 = (w, h, P) => {
const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: 4.1 });
const long = cmpRows.flatMap((d) => [
{ date: d.date, side: "W", v: d.gap_W }, // "W"/"B", not "White"/"Black" (Plot reads those as colours)
{ date: d.date, side: "B", v: d.gap_B },
]).filter((d) => Number.isFinite(d.v));
const ext = d3.extent([...long.map((d) => d.v), ...cmpRows.map((d) => d.gap_WxB).filter(Number.isFinite),
...cmpRows.map((d) => Math.max(0, d.gap_W) + Math.max(0, d.gap_B)).filter(Number.isFinite),
...cmpRows.map((d) => Math.min(0, d.gap_W) + Math.min(0, d.gap_B)).filter(Number.isFinite), 0]);
const cands = [-0.99, -0.98, -0.95, -0.9, -0.8, -0.75, -0.6, -0.5, -0.33, -0.2, -0.1, 0, 0.1, 0.25, 0.5, 1, 1.5, 2, 3, 4, 9, 19, 49, 99];
const slack = P && !P.legacy ? 0 : 0.05;
const ticks = cands.map((p) => Math.log(1 + p)).filter((t) => t >= ext[0] - slack && t <= ext[1] + slack);
// a gap between two sets can span a wide range, where the candidates crowd around 0: keep 0, then walk
// outwards keeping only ticks at least 1/(k-1) of the range apart (k = the tick budget)
const minGap = 0.9 * (ext[1] - ext[0]) / Math.max(1, thinScreen(P, L) - 1);
const walk = (side) => { const out = []; let last = 0;
for (const t of side) if (Math.abs(t - last) >= minGap) { out.push(t); last = t; }
return out; };
const spaced = [...walk(ticks.filter((t) => t < 0).sort((a, b) => b - a)).reverse(), ...(ticks.includes(0) ? [0] : []),
...walk(ticks.filter((t) => t > 0).sort((a, b) => a - b))];
return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), d3.utcMonth.offset(monthDate(ix, m1), 1)], ...xTicks(P, w, L.marginLeft) },
y: { label: "B vs A (log scale)", ticks: spaced, tickFormat: gapPct, grid: true },
color: { domain: ["W", "B"], range: [COL.white, COL.black] },
marks: [
Plot.rectY(long, { x: "date", interval: "month", y: "v", fill: "side", order: ["W", "B"], insetLeft: 0.5, insetRight: 0.5, fillOpacity: 0.9 }),
Plot.ruleY([0], { stroke: COL.ink, strokeOpacity: 0.4 }),
Plot.lineY(cmpRows, { x: (d) => d3.utcDay.offset(d.date, 14), y: "gap_WxB", stroke: COL.ink, strokeWidth: 1.5 }),
Plot.ruleX(cmpRows, Plot.pointerX({ x: (d) => d3.utcDay.offset(d.date, 14), stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(cmpRows, Plot.pointerX({ x: (d) => d3.utcDay.offset(d.date, 14), y: "gap_WxB",
title: (d) => `${d.label} (B vs A)\nNet, W×B ${gapPct(d.gap_WxB)} A ${pct(d.a_WxB)} · B ${pct(d.b_WxB)}\nWhite (W) ${gapPct(d.gap_W)} A ${pct(d.a_W)} · B ${pct(d.b_W)}\nBlack (B) ${gapPct(d.gap_B)} A ${pct(d.a_B)} · B ${pct(d.b_B)}\n(log parts add: ${d.gap_W?.toFixed(3)} + ${d.gap_B?.toFixed(3)} = ${d.gap_WxB?.toFixed(3)})` })),
],
});
}{
if (!cmpReady) return html``;
const legend = `<div class="dash-legend"><span>${key(COL.white, "box")} White's moves (W)</span><span>${key(COL.black, "box")} Black's moves (B)</span>
<span>${key(COL.ink)} Net: W×B in B vs A</span></div>`;
const sub = `<p class="dash-sub">How much more (or less) common this move order is in Set B than in Set A, month by month:
+40% means 40% more common in B. A bar above zero means that side's moves make the line more common in B.
On a log scale White's part and Black's part add up exactly to the net, with no interaction left over.</p>`;
if (cmp.same)
return html`${D(sub + legend)}${noteBox("The two sets are the same, so there is no gap to split. Change Set A or Set B above.",
"Nothing to download: the two sets are the same")}<div class="dash-note">${cmpPopNote}</div>`;
const box = chartWithDownload(cchart2(Math.max(240, Math.min(width, 1100))), () => cmpSpec("Who explains the gap? (B vs A)", "compare-gap",
(w, h, P) => cchart2(w, h, P), [
{ label: "White's moves (W)", color: COL.white, kind: "box" },
{ label: "Black's moves (B)", color: COL.black, kind: "box" },
{ label: "Net: W×B in B vs A (log scale; the parts add exactly)", color: COL.ink, kind: "line" }],
"B vs A: White's part log(W_B / W_A) plus Black's part log(B_B / B_A) is the net log(W×B_B / W×B_A) exactly; +40% means 40% more common in B."));
return html`${D(sub + legend)}${box}<div class="dash-note">${cmpPopNote}</div>
<p class="dash-copy">Over this window this move order is <b>${xr(gw.gap_WxB)}</b> as common in B as in A (W×B ${pct(wa.WxB)} vs ${pct(wb.WxB)});
White's moves account for <b>×${Number.isFinite(gw.gap_W) ? times2(Math.exp(gw.gap_W)).replace("×", "") : "—"}</b>, Black's for
<b>×${Number.isFinite(gw.gap_B) ? times2(Math.exp(gw.gap_B)).replace("×", "") : "—"}</b> (the two multiply to the net exactly).
By true reach, any move order, it is ${xr(gw.gap_net)}.</p>`;
}3 · How does it score, A vs B?
cScoreDomain = {
const v = cmpRows.flatMap((d) => [d.a_score_lo, d.a_score_hi, d.b_score_lo, d.b_score_hi]).filter(Number.isFinite);
const lo = v.length ? d3.min(v) : 0.5, hi = v.length ? d3.max(v) : 0.5, padY = 0.1 * (hi - lo);
let a = lo - padY, b = hi + padY;
if (b - a < 0.04) { const mid = (lo + hi) / 2; a = mid - 0.02; b = mid + 0.02; }
if (a < 0) { b = Math.min(1, b - a); a = 0; }
if (b > 1) { a = Math.max(0, a - (b - 1)); b = 1; }
return [a, b];
}
cScoreTicks = (k) => {
const [a, b] = cScoreDomain;
// v2.0.2: 0.25 and 0.5 steps too, for a few-game OTB set whose scores span most of 0..1 (labels collided at Wide)
for (const st of [0.01, 0.02, 0.05, 0.1, 0.2, 0.25, 0.5]) {
const t = d3.range(Math.ceil(a / st - 1e-9), Math.floor(b / st + 1e-9) + 1).map((i) => +(i * st).toFixed(2));
if (t.length <= k || st === 0.5) return t;
}
}
cchart3 = (w, h, P) => { const L = plotLayout(P, h, w, { hDefault: 300, mlBanner: 68, mlK: 3.6 }); return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: "linear", label: "average score (White's view)", domain: cScoreDomain, grid: true,
ticks: cScoreTicks(Math.min(6, yMax(P, L))), tickFormat: d3.format(".2f") },
marks: [
...(cScoreDomain[0] <= 0.5 && 0.5 <= cScoreDomain[1] ? [
Plot.ruleY([0.5], { stroke: COL.muted, strokeWidth: 1, strokeDasharray: "4,3", ariaLabel: () => "even-rule" }),
Plot.text([0.5], { y: (d) => d, text: () => "even", frameAnchor: "right", textAnchor: "end", lineAnchor: "bottom", dy: -3,
fill: COL.prod, ariaLabel: () => "even-label" })] : []),
Plot.areaY(cmpRows, { x: "date", y1: "a_score_lo", y2: "a_score_hi", fill: SET.a, fillOpacity: 0.12, curve: "monotone-x" }),
Plot.areaY(cmpRows, { x: "date", y1: "b_score_lo", y2: "b_score_hi", fill: SET.b, fillOpacity: 0.2, curve: "monotone-x" }),
Plot.lineY(cmpRows, { x: "date", y: "a_score", stroke: SET.a, strokeWidth: 2.25, curve: "monotone-x" }),
Plot.lineY(cmpRows, { x: "date", y: "b_score", stroke: SET.b, strokeWidth: 2.25, curve: "monotone-x" }),
Plot.ruleX(cmpRows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(cmpRows, Plot.pointerX({ x: "date", y: "b_score",
title: (d) => `${d.label}\nA ${sc(d.a_score)} (${sc(d.a_score_lo)}–${sc(d.a_score_hi)}) ${games(d.a_res_n)} games\nB ${sc(d.b_score)} (${sc(d.b_score_lo)}–${sc(d.b_score_hi)}) ${games(d.b_res_n)} games` })),
],
}) }{
if (!cmpReady) return html``;
if (!cmp.a.ser.hasResults)
return html`${noteBox(`Monthly results are available for the named openings' final positions. Enter or pick a named opening.`,
"Nothing to download: monthly results are available for the named openings' final positions")}<div class="dash-note">${cmpPopNote}</div>`;
// v2.0: a player with a colour chosen also gets that player's own score
const t = (nm, S, w, color) => { const ps = playerSide(S);
return ctile(`${nm}: average score`, sc(w.score),
`White ${pct(w.win_w)} · Draw ${pct(w.win_d)} · Black ${pct(w.win_b)} · ${games(w.res_n)} games`
+ (ps ? ` · ${esc(shortOf(S.who))}'s score ${sc(ps === "white" ? w.score : 1 - w.score)}` : ""), color); };
const box = chartWithDownload(cchart3(Math.max(240, Math.min(width, 1100))), () => cmpSpec("How does it score, A vs B?", "compare-score",
(w, h, P) => cchart3(w, h, P), setLegendExport([{ label: "95% interval on the score", color: COL.muted, kind: "area" }]), RESULTS_FOOT));
return html`${D(`<div class="dash-tiles">${t("Set A", setA, wa, SET.a)}${t("Set B", setB, wb, SET.b)}</div>${setLegend(`<span>shaded: 95% interval on the score</span>`)}`)}${box}
<div class="dash-note">${cmpPopNote} ${RESULTS_FOOT}</div>`;
}4 · Specialist edge, A vs B
edgeKey4 = persp4 === "White" ? "spec_edge_white" : "spec_edge_black"
edgeFmt = (d) => `${+(+d).toPrecision(3)}×`
cchart4 = (w, h, P) => {
const L = plotLayout(P, h, w, { hDefault: 280, mlBanner: 76, mlK: 3.6 });
const k = edgeKey4;
// the domain covers the bands and 1x, padded 5% (log) each side, so the "equal" rule never sits on the frame
const vals = [1, ...cmpRows.flatMap((d) => [d[`a_${k}_lo`], d[`a_${k}_hi`], d[`b_${k}_lo`], d[`b_${k}_hi`]])].filter((x) => Number.isFinite(x) && x > 0);
const dom = [d3.min(vals) / 1.05, d3.max(vals) * 1.05];
return Plot.plot({
width: w, ...L,
x: { type: "utc", label: null, domain: [monthDate(ix, m0), monthDate(ix, m1)], ...xTicks(P, w, L.marginLeft) },
y: { type: "log", label: `${persp4} specialist edge (${persp4 === "White" ? "B ÷ W" : "W ÷ B"})`, grid: true, tickFormat: edgeFmt, domain: dom,
ticks: thin(logTicks(vals)?.filter((t) => t >= dom[0] && t <= dom[1]), yMax(P, L)) },
marks: [
Plot.ruleY([1], { stroke: COL.muted, strokeWidth: 1, strokeDasharray: "4,3", ariaLabel: () => "equal-rule" }),
Plot.text([1], { y: (d) => d, text: () => "equal", frameAnchor: "right", textAnchor: "end", lineAnchor: "bottom", dy: -3,
fill: COL.prod, ariaLabel: () => "equal-label" }),
Plot.areaY(cmpRows, { x: "date", y1: `a_${k}_lo`, y2: `a_${k}_hi`, fill: SET.a, fillOpacity: 0.12, curve: "monotone-x" }),
Plot.areaY(cmpRows, { x: "date", y1: `b_${k}_lo`, y2: `b_${k}_hi`, fill: SET.b, fillOpacity: 0.2, curve: "monotone-x" }),
Plot.lineY(cmpRows, { x: "date", y: `a_${k}`, stroke: SET.a, strokeWidth: 2.25, curve: "monotone-x" }),
Plot.lineY(cmpRows, { x: "date", y: `b_${k}`, stroke: SET.b, strokeWidth: 2.25, curve: "monotone-x" }),
Plot.ruleX(cmpRows, Plot.pointerX({ x: "date", stroke: COL.muted, strokeWidth: 1 })),
Plot.tip(cmpRows, Plot.pointerX({ x: "date", y: `b_${k}`,
title: (d) => `${d.label}\n${persp4} specialist edge\nA ${times2(d[`a_${k}`])}\nB ${times2(d[`b_${k}`])}` })),
],
});
}{
if (!cmpReady) return html``;
const w = persp4 === "White", O = w ? "Black" : "White", k = edgeKey4;
const head = ctile(`${persp4} specialist edge (${w ? "B ÷ W" : "W ÷ B"})`, `${times2(wa[k])} in A, ${times2(wb[k])} in B`,
`how many times more often a ${persp4} specialist reaches this than a ${O} specialist, in each set`, null);
const box = chartWithDownload(cchart4(Math.max(240, Math.min(width, 1100))), () => cmpSpec(`${persp4} specialist edge, A vs B`, "compare-edge",
(w2, h, P) => cchart4(w2, h, P), setLegendExport([{ label: "95% interval", color: COL.muted, kind: "area" }]),
`Specialist edge: how many times more often a ${persp4} specialist (always plays ${persp4}'s moves of the line) reaches it than a ${O} specialist; ${w ? "B ÷ W" : "W ÷ B"}. Above 1× favours ${persp4}.`));
return html`${D(`<div class="dash-tiles">${head}</div>${setLegend(`<span>shaded: 95% interval</span>`)}`)}${box}
<p class="dash-sub">Above the dashed "equal" line, a ${persp4} specialist meets this more often than a ${O} specialist does.</p>
<div class="dash-note">${cmpPopNote}</div>`;
}