Files
Airplay-Predictor/src/web/index.html
T

666 lines
54 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Airplay Predictor</title>
<style>
:root {
--bg: #f7f6f2; --panel: #ffffff; --ink: #1d1d1b; --muted: #6b6a64; --line: #e4e2da;
--accent: #c2410c; --accent-soft: #fde7d9; --good: #15803d; --bad: #b91c1c;
--p3: #2563eb; --p4: #c2410c; --p5: #7c3aed; --p6: #0f766e; --p8: #a16207;
--shadow: 0 1px 2px rgba(0,0,0,.05), 0 8px 24px rgba(0,0,0,.06);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #141412; --panel: #1d1d1a; --ink: #ecebe6; --muted: #9b9a92; --line: #2f2e2a;
--accent: #fb923c; --accent-soft: #3a2316; --good: #4ade80; --bad: #f87171;
--p3: #60a5fa; --p4: #fb923c; --p5: #a78bfa; --p6: #2dd4bf; --p8: #facc15;
--shadow: 0 1px 2px rgba(0,0,0,.3), 0 8px 24px rgba(0,0,0,.3);
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
header { padding: 28px 24px 8px; max-width: 1240px; margin: 0 auto; }
h1 { margin: 0; font-size: 26px; letter-spacing: -.02em; }
h1 span { color: var(--accent); }
.sub { color: var(--muted); margin-top: 4px; font-size: 14px; }
nav { display: flex; gap: 4px; margin-top: 18px; border-bottom: 1px solid var(--line); }
nav button { background: none; border: 0; padding: 10px 14px; font: inherit; color: var(--muted); cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; }
nav button.on { color: var(--ink); border-color: var(--accent); font-weight: 600; }
main { max-width: 1240px; margin: 0 auto; padding: 16px 24px 60px; }
.controls { display: flex; flex-wrap: wrap; gap: 14px 22px; align-items: end; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; box-shadow: var(--shadow); }
.ctl { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
.ctl b { color: var(--ink); text-transform: none; letter-spacing: 0; font-size: 14px; }
input[type=range] { width: 220px; accent-color: var(--accent); }
input[type=search], select { font: inherit; padding: 7px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); min-width: 160px; }
label.chk { display: flex; gap: 6px; align-items: center; text-transform: none; letter-spacing: 0; font-size: 14px; color: var(--ink); }
.tablewrap { margin-top: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; overflow-x: auto; box-shadow: var(--shadow); }
table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
th, td { padding: 9px 12px; text-align: right; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { font-size: 12px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; cursor: pointer; user-select: none; position: sticky; top: 0; background: var(--panel); }
th.l, td.l { text-align: left; }
tbody tr { cursor: pointer; }
tbody tr:hover { background: var(--accent-soft); }
td.name { font-weight: 600; }
td.name small { color: var(--muted); font-weight: 400; margin-left: 6px; }
.bar { display: inline-flex; align-items: center; gap: 8px; }
.bar i { display: inline-block; height: 8px; border-radius: 4px; background: var(--accent); }
.cell { display: inline-block; min-width: 44px; padding: 2px 6px; border-radius: 6px; text-align: center; font-size: 13px; }
.more { display: block; margin: 12px auto; font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); color: var(--ink); cursor: pointer; }
.empty { padding: 40px; text-align: center; color: var(--muted); }
/* drawer */
#shade { position: fixed; inset: 0; background: rgba(0,0,0,.35); opacity: 0; pointer-events: none; transition: opacity .2s; }
#shade.on { opacity: 1; pointer-events: auto; }
#drawer { position: fixed; top: 0; right: 0; bottom: 0; width: min(760px, 100vw); background: var(--panel); transform: translateX(100%); transition: transform .25s ease; overflow-y: auto; box-shadow: -10px 0 40px rgba(0,0,0,.2); }
#drawer.on { transform: none; }
.dhead { display: flex; gap: 16px; align-items: center; padding: 20px 22px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel); z-index: 1; }
.dhead img { width: 64px; height: 64px; border-radius: 50%; object-fit: cover; background: var(--line); }
.dhead h2 { margin: 0; font-size: 22px; }
.dhead .x { margin-left: auto; font-size: 22px; background: none; border: 0; color: var(--muted); cursor: pointer; }
.sec { padding: 16px 22px; border-bottom: 1px solid var(--line); }
.sec h3 { margin: 0 0 10px; font-size: 13px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
.kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; }
.kpi { background: var(--bg); border-radius: 10px; padding: 10px 12px; }
.kpi div { font-size: 12px; color: var(--muted); }
.kpi b { font-size: 22px; }
.kpi .d { font-size: 13px; margin-left: 6px; }
.up { color: var(--good); } .down { color: var(--bad); }
.legend { display: flex; flex-wrap: wrap; gap: 12px; font-size: 12px; color: var(--muted); margin-top: 6px; }
.legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 4px; vertical-align: -1px; }
svg text { fill: var(--muted); font-size: 11px; }
.wi { display: grid; grid-template-columns: 1fr; gap: 12px; }
.wi .row { display: grid; grid-template-columns: 210px 1fr 60px; align-items: center; gap: 10px; font-size: 14px; }
.wi input[type=range] { width: 100%; }
.wtable td, .wtable th { padding: 6px 8px; }
.note { color: var(--muted); font-size: 13px; }
.tracks { columns: 2; font-size: 14px; } .tracks div { break-inside: avoid; padding: 2px 0; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip { background: var(--bg); border-radius: 999px; padding: 3px 10px; font-size: 13px; }
/* best week calendar */
.cal { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: 8px; margin-top: 16px; }
.day { border-radius: 10px; padding: 10px; border: 1px solid var(--line); background: var(--panel); position: relative; min-height: 78px; }
.day .d { font-size: 12px; color: var(--muted); }
.day .v { font-size: 22px; font-weight: 700; margin-top: 4px; font-variant-numeric: tabular-nums; }
.day.soon { opacity: .55; background: repeating-linear-gradient(45deg, var(--bg), var(--bg) 6px, var(--panel) 6px, var(--panel) 12px); }
.day.soon .v { font-size: 13px; font-weight: 500; color: var(--muted); }
.day.best { outline: 3px solid var(--good); outline-offset: -1px; }
.day .tag { position: absolute; top: 8px; right: 8px; font-size: 11px; color: var(--muted); }
.bw-head { display: flex; flex-wrap: wrap; gap: 16px; align-items: baseline; margin-top: 18px; }
.bw-head h2 { margin: 0; }
.lvl0 { background: color-mix(in srgb, var(--good) 28%, var(--panel)); }
.lvl1 { background: color-mix(in srgb, var(--good) 14%, var(--panel)); }
.lvl2 { background: var(--panel); }
.lvl3 { background: color-mix(in srgb, var(--bad) 10%, var(--panel)); }
/* model tab */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 18px; box-shadow: var(--shadow); }
.card h3 { margin-top: 0; }
.card p { color: var(--muted); }
.prose { max-width: 760px; }
.prose li { margin: 6px 0; }
/* next week */
.nw-hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 18px; align-items: end; margin-top: 6px; }
.eyebrow { font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--accent); font-weight: 700; }
.nw-hero h2 { margin: 4px 0 6px; font-size: 26px; letter-spacing: -.02em; }
.nw-kpis { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
.nw-kpis .kpi b { font-size: 26px; }
.nw-kpis .kpi small { display: block; color: var(--muted); font-size: 12px; margin-top: 2px; }
.nw-h { margin: 26px 0 10px; font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); }
.board { display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; }
.board .col { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; box-shadow: var(--shadow); border-top: 4px solid var(--c); }
.board .col h4 { margin: 0 0 8px; font-size: 15px; color: var(--c); }
.board .it { display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; padding: 6px 0; border-bottom: 1px solid var(--line); cursor: pointer; font-size: 14px; }
.board .it:last-child { border-bottom: 0; }
.board .it i { grid-column: 1 / -1; height: 4px; border-radius: 2px; background: var(--c); opacity: .75; }
.board .it b { font-variant-numeric: tabular-nums; }
.nw-filters { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 12px; }
.pill { border: 1px solid var(--line); background: var(--panel); color: var(--ink); border-radius: 999px; padding: 6px 12px; font: inherit; font-size: 13px; cursor: pointer; }
.pill.on { background: var(--ink); color: var(--panel); border-color: var(--ink); }
.cand { display: grid; grid-template-columns: repeat(auto-fill, minmax(330px, 1fr)); gap: 14px; }
.cc { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 16px; box-shadow: var(--shadow); cursor: pointer; display: flex; flex-direction: column; gap: 10px; }
.cc:hover { border-color: var(--accent); }
.cc .top { display: flex; align-items: flex-start; gap: 10px; }
.cc .nm { font-weight: 700; font-size: 17px; line-height: 1.2; }
.cc .nm small { display: block; font-weight: 400; color: var(--muted); font-size: 12px; margin-top: 2px; }
.cc .big { margin-left: auto; text-align: right; }
.cc .big b { font-size: 30px; font-variant-numeric: tabular-nums; letter-spacing: -.02em; }
.cert { display: inline-block; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; padding: 2px 8px; border-radius: 999px; }
.cert.c0 { background: color-mix(in srgb, var(--good) 22%, var(--panel)); color: var(--good); }
.cert.c1 { background: color-mix(in srgb, var(--good) 12%, var(--panel)); color: var(--good); }
.cert.c2 { background: var(--accent-soft); color: var(--accent); }
.cert.c3, .cert.c4 { background: var(--bg); color: var(--muted); }
.rel { display: grid; grid-template-columns: 1fr auto; gap: 4px 10px; align-items: center; font-size: 13px; color: var(--muted); }
.rel .track2 { height: 10px; border-radius: 5px; background: var(--line); overflow: hidden; }
.rel .track2 i { display: block; height: 100%; background: var(--accent); border-radius: 5px; }
.rel b { color: var(--ink); }
.chs { display: flex; flex-wrap: wrap; gap: 6px; }
.chs span { font-size: 12px; padding: 2px 8px; border-radius: 6px; background: color-mix(in srgb, var(--c) 14%, var(--panel)); color: var(--ink); }
.live { background: var(--bg); border-radius: 10px; padding: 10px 12px; font-size: 13px; }
.live .st { font-weight: 700; }
.meter { position: relative; height: 8px; border-radius: 4px; background: var(--line); margin: 8px 0 4px; overflow: hidden; }
.meter i { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 4px; background: var(--c); }
.meter u { position: absolute; top: -2px; bottom: -2px; width: 2px; background: var(--ink); }
.tag2 { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); border: 1px solid var(--line); border-radius: 6px; padding: 1px 6px; }
.track { display: grid; grid-template-columns: 340px 1fr; gap: 18px; align-items: start; }
@media (max-width: 900px) { .nw-hero, .track { grid-template-columns: 1fr; } .board { grid-template-columns: repeat(2, 1fr); } .nw-kpis { grid-template-columns: 1fr 1fr 1fr; } }
@media (max-width: 640px) { .board { grid-template-columns: 1fr; } .nw-kpis { grid-template-columns: 1fr; } .cand { grid-template-columns: 1fr; } }
@media (max-width: 640px) {
header, main { padding-left: 16px; padding-right: 16px; }
input[type=range] { width: 100%; }
.ctl { width: 100%; }
.wi .row { grid-template-columns: 1fr 60px; } .wi .row label { grid-column: 1 / -1; }
.tracks { columns: 1; }
.hide-sm { display: none; }
}
</style>
</head>
<body>
<header>
<h1>Airplay <span>Predictor</span></h1>
<div class="sub" id="sub">Loading…</div>
<nav>
<button class="on" data-tab="rank">Ranking</button>
<button data-tab="next">Next week</button>
<button data-tab="best">Best week</button>
<button data-tab="model">How good is it?</button>
</nav>
</header>
<main>
<section id="tab-rank">
<div class="controls">
<div class="ctl">Release week <b id="hlabel">—</b><input type="range" id="h" min="0" max="25" value="0"></div>
<div class="ctl">Added within
<select id="w"><option value="1">1 week</option><option value="2" selected>2 weeks</option><option value="4">4 weeks</option><option value="6">6 weeks</option><option value="8">8 weeks</option><option value="10">10 weeks</option><option value="12">12 weeks</option></select>
</div>
<div class="ctl">Station
<select id="ch">
<option value="any">Any DR station</option>
<option value="p3">P3</option>
<option value="p4">P4 (best region)</option>
<option value="p5">P5</option>
<option value="p6beat">P6 Beat</option>
<option value="p8jazz">P8 Jazz</option>
</select>
</div>
<div class="ctl">Sort by
<select id="sort">
<option value="p">Chance of a new add</option>
<option value="plays">Expected plays</option>
<option value="up">Biggest climbers</option>
</select>
</div>
<div class="ctl">Artist <input type="search" id="q" placeholder="Search…"></div>
<div class="ctl"><label class="chk"><input type="checkbox" id="dk"> Danish acts only</label></div>
</div>
<div class="tablewrap">
<table>
<thead><tr>
<th class="l">#</th><th class="l">Artist</th><th>New add</th>
<th class="hide-sm">P3</th><th class="hide-sm">P4</th><th class="hide-sm">P5</th><th class="hide-sm">P6</th><th class="hide-sm">P8</th>
<th class="l hide-sm">In rotation now</th><th>Plays / wk (80%)</th>
</tr></thead>
<tbody id="rows"><tr><td colspan="10" class="empty">Loading…</td></tr></tbody>
</table>
</div>
<button class="more" id="more" hidden>Show more</button>
<p class="note"><b>New add</b> = if the artist releases a new song in the chosen week, the chance DR adds it within the chosen number of weeks: the artist enters rotation (at or above the station's weekly play threshold) after at least 4 weeks out, or, for artists who are always on, their plays jump well above their own baseline and stay up (that finds 77% of the songs DR's real lists show as new). Learned from past releases with no other release in the 6 weeks before, so a current song's success isn't counted as a new one's; a release less than 6 weeks after the artist's last one gets no estimate ("too soon"). The new song's NMF Denmark placement is weighed by how often the artist's releases were placed. "In rotation now" lists DR stations where the artist is on the list now, then Bauer stations (grey) with 14+ plays in the last 7 days. Click an artist for history and a what-if, or open <b>Best week</b> for their release calendar.</p>
</section>
<section id="tab-next" hidden><div id="nw"><p class="empty">Loading…</p></div></section>
<section id="tab-best" hidden>
<div class="controls">
<div class="ctl">Artist <input type="search" id="bw-q" list="bw-list" placeholder="Type an artist…" autocomplete="off"><datalist id="bw-list"></datalist></div>
<div class="ctl">Station
<select id="bw-ch"><option value="any">Any DR station</option><option value="P3">P3</option><option value="P4">P4 (best region)</option><option value="P5">P5</option><option value="P6">P6 Beat</option><option value="P8">P8 Jazz</option></select>
</div>
<div class="ctl">From <input type="date" id="bw-from"></div>
<div class="ctl">To <input type="date" id="bw-to"></div>
<div class="ctl">Added within
<select id="bw-w"><option value="1">1 week</option><option value="2" selected>2 weeks</option><option value="4">4 weeks</option><option value="6">6 weeks</option><option value="8">8 weeks</option><option value="10">10 weeks</option><option value="12">12 weeks</option></select>
</div>
<div class="ctl">New Music Friday Denmark
<select id="bw-nmf"><option value="auto">As often as their releases were placed</option><option value="yes">Placed</option><option value="no">Not placed</option></select>
</div>
</div>
<div id="bw-out"><p class="empty">Pick an artist to see the best week to release a new song.</p></div>
</section>
<section id="tab-model" hidden>
<div class="prose">
<h2>What the model does</h2>
<p>For every artist DR has played, it estimates the chance of a <b>new add</b>: the artist entering rotation on a station (at or above its weekly play threshold) after at least 4 weeks out of rotation, within an 8-week window starting 0–12 weeks from now. It also forecasts weekly plays. It learns from 51 weeks of DR's per-artist weekly play counts plus the artist's IFPI chart history (Track Top-40, Airplay Top-20).</p>
<p>DR publishes plays per artist, not per song, so "new add" can't yet tell a new song from an old one coming back. In the one week of song-level plays we have, only 3–12% of artists in rotation on a station had two songs in rotation at once, so "drops out first, then gets added" is the usual pattern. The weekly rotation lists (song level) will sharpen this.</p>
<p id="taus" class="note"></p>
</div>
<h2>Backtest</h2>
<div class="cards" id="cards"></div>
<div class="prose">
<h2>20 years of IFPI charts</h2>
<p>A second test, on the national charts: when a song enters the Track Top-40 without having been on the Airplay Top-20, does it reach the Airplay Top-20 within 8 weeks? Scored year by year from 2010, each year with a model fitted on the years before it. It beats the base rate by +0.13 in log-loss skill (PR-AUC 0.41 vs 0.20), and the strongest signal is the artist's own radio history: earlier Airplay Top-20 songs and how often their earlier hits crossed over.</p>
<p>Since streaming started counting (Nov 2014), 55% of songs on both charts hit the Track Top-40 first (median 5 weeks before airplay), 29% move together and 17% are radio first. Another 837 songs reached the Airplay Top-20 without ever charting on the Track Top-40.</p>
<h2>Known limits</h2>
<ul>
<li><b>The artist pool is artists connected to DR.</b> About 7,900 artists: those DR played in mid-November 2026 (3,250) plus artists credited on tracks DR has played and their groups (4,700). Nearly half had no DR plays in the last 4 weeks, so the pool isn't only current airplay, but it isn't every releasing artist either.</li>
<li><b>Per artist, not per song.</b> DR's history counts plays per artist, so "a new song was added" is learned from releases with no other release in the 6 weeks before. For artists who just released, a new song would compete with the current one.</li>
<li><b>Rotation thresholds</b> are fitted to six of DR's weekly rotation lists inside the 51-week window ("plays ≥ threshold" matches the real lists with F1 ≈ 0.74 on P3/P4, 0.78 on P6, about 0.5 on P5/P8, which play more off-list).</li>
<li><b>Christmas</b> is only seen once, as history. Forecasts for weeks 48–52 don't know about Christmas songs yet.</li>
</ul>
</div>
</section>
</main>
<div id="shade"></div>
<aside id="drawer" aria-hidden="true"></aside>
<script>
const BASE = location.pathname.replace(/\/(index\.html)?$/, '');
const API = p => fetch(BASE + '/api/' + p).then(r => r.json());
const GROUPS = [['p3', 'P3'], ['p4', 'P4'], ['p5', 'P5'], ['p6beat', 'P6'], ['p8jazz', 'P8']];
const P4S = ['p4kbh','p4sjaelland','p4fyn','p4syd','p4trekanten','p4vest','p4aarhus','p4nord','p4bornholm','p4esbjerg'];
const BAUER = { nov: 'NOVA', dso: 'Radio Soft', the: 'The Voice', pop: 'Pop FM', rhu: 'Radio 100' };
const COLORS = { p3: 'var(--p3)', p4: 'var(--p4)', p5: 'var(--p5)', p6beat: 'var(--p6)', p8jazz: 'var(--p8)' };
let meta = null, data = { 1: null }, shown = 100, current = [];
const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const pct = p => p == null ? '—' : (p >= 0.995 ? '>99' : p < 0.005 ? '<1' : Math.round(p * 100)) + '%';
const fmtDate = s => new Date(s + 'T00:00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });
// Chance of a new add in the window (station group g, or any DR station).
function chanP(r, g) {
// The new-song chance (null when the release week is too soon after the artist's last release).
const any = r.add_any_rel, per = r.add_rel;
if (g === 'any') return any;
if (any == null) return null;
if (g === 'p4') return Math.max(...P4S.map(c => per?.[c] ?? 0));
return per?.[g];
}
function nowPlays(r, g) {
const now = r.now || {};
const v = c => now[c]?.plays ?? 0;
if (g === 'any') return Object.keys(now).reduce((s, c) => s + v(c), 0);
if (g === 'p4') return P4S.reduce((s, c) => s + v(c), 0) / P4S.length;
return v(g);
}
function nowChips(now, bauer) {
now = now || {};
const on = GROUPS.filter(([g]) => g === 'p4' ? P4S.some(c => now[c]?.on) : now[g]?.on).map(([, l]) => l);
// Bauer: no published lists; 14+ plays in the last 7 days (two a day) shown as heavy rotation.
const b = Object.entries(bauer || {}).filter(([, n]) => n >= 14).sort((x, y) => y[1] - x[1]).map(([s, n]) => `${BAUER[s] || s} ${n}`);
const all = on.concat(b.map(x => `<span class="note">${x}</span>`));
return all.length ? all.join(' · ') : '<span class="note">—</span>';
}
function chanPlays(r, g) {
if (g === 'any') return r.mean;
if (g === 'p4') return P4S.reduce((s, c) => s + (r.plays[c] ?? 0), 0) / P4S.length;
return r.plays[g];
}
function heat(p) {
if (p == null) return '';
const a = Math.min(1, Math.max(0, p / 0.5));
return `background: color-mix(in srgb, var(--accent) ${Math.round(a * 85)}%, transparent); color: ${a > .55 ? '#fff' : 'inherit'}`;
}
async function loadMeta() {
meta = await API('meta');
if (!meta.ready) { $('sub').textContent = 'No forecasts yet: run `airplay model rank`.'; return; }
$('h').max = meta.horizons.length;
$('sub').textContent = `DR plays through the week of ${fmtDate(meta.origin_week)} · forecasts made ${meta.made_at.slice(0, 10)} · model ${meta.model}`;
if (meta.tau) $('taus').textContent = 'Rotation thresholds (plays per week): ' + meta.channels.map((c, i) => `${c} ${meta.tau[i]}`).join(', ') + '.';
renderModel();
}
function windowStart(h) {
const d = new Date(meta.origin_week + 'T00:00:00Z');
d.setUTCDate(d.getUTCDate() + 7 * (h + 1));
return d.toISOString().slice(0, 10);
}
async function loadRank() {
const h = +$('h').value, w = $('w').value, k = h + '|' + w;
$('hlabel').textContent = `${fmtDate(windowStart(h))}${h ? ` (+${h} wk)` : ' (next week)'}`;
if (!data[k]) {
const res = await API(`rank?h=${h}&w=${w}`);
data[k] = res.rows;
if (!res.live) setTimeout(() => { delete data[k]; loadRank(); }, 60000); // models still loading on the server
fillArtistList(res.rows);
}
render();
}
function render() {
const h = +$('h').value, g = $('ch').value, sort = $('sort').value, q = $('q').value.trim().toLowerCase(), dk = $('dk').checked;
let rows = data[h + '|' + $('w').value].filter(r => (!q || r.name.toLowerCase().includes(q)) && (!dk || r.danish));
const key = sort === 'p' ? r => [chanP(r, g) ?? 0, chanPlays(r, g) ?? 0]
: sort === 'plays' ? r => [chanPlays(r, g) ?? 0, 0]
: r => [(chanPlays(r, g) ?? 0) - nowPlays(r, g), 0];
rows = rows.map(r => [key(r), r]).sort((a, b) => b[0][0] - a[0][0] || b[0][1] - a[0][1]).map(x => x[1]);
current = rows;
const body = rows.slice(0, shown).map((r, i) => {
const p = chanP(r, g), pl = chanPlays(r, g);
const range = g === 'any' ? ` <small class="note">(${Math.round(r.lo)}–${Math.round(r.hi)})</small>` : '';
return `<tr data-id="${esc(r.id)}">
<td class="l">${i + 1}</td>
<td class="l name">${esc(r.name)}${r.danish ? '<small>DK</small>' : ''}${r.too_soon ? '<small title="Less than 6 weeks after their last release: no new-song estimate for this week">too soon</small>' : ''}</td>
<td><span class="bar"><i style="width:${Math.round((p ?? 0) * 70)}px"></i>${pct(p)}</span></td>
${GROUPS.map(([c]) => `<td class="hide-sm"><span class="cell" style="${heat(chanP(r, c))}">${pct(chanP(r, c))}</span></td>`).join('')}
<td class="l hide-sm">${nowChips(r.now, r.bauer)}</td>
<td>${pl == null ? '—' : pl.toFixed(pl < 10 ? 1 : 0)}${range}</td>
</tr>`;
}).join('');
$('rows').innerHTML = body || '<tr><td colspan="10" class="empty">No artists match.</td></tr>';
$('more').hidden = rows.length <= shown;
}
// ---------- artist drawer ----------
function openDrawer(html) { $('drawer').innerHTML = html; $('drawer').classList.add('on'); $('shade').classList.add('on'); $('drawer').setAttribute('aria-hidden', 'false'); }
function closeDrawer() { $('drawer').classList.remove('on'); $('shade').classList.remove('on'); $('drawer').setAttribute('aria-hidden', 'true'); }
function historyChart(a) {
// Weekly plays: P3, P4 (mean of regions), P5, P6, P8 as lines, then the forecast of total plays as a band.
const W = 700, H = 220, L = 34, R = 10, T = 10, B = 26;
const fcs = a.forecasts.filter(x => x.mean != null);
const n = a.weeks.length, f = fcs.length;
const series = GROUPS.map(([g]) => g === 'p4'
? a.weeks.map((_, i) => P4S.reduce((s, c) => s + (a.plays[c]?.[i] ?? 0), 0) / P4S.length)
: (a.plays[g] || []).slice());
const total = a.weeks.map((_, i) => Object.values(a.plays).reduce((s, v) => s + (v[i] ?? 0), 0));
const maxY = Math.max(5, ...series.flat(), ...fcs.map(x => (x.hi ?? 0) / 4), ...total.map(t => t / 4));
const X = i => L + (W - L - R) * i / (n + f - 1);
const Y = v => T + (H - T - B) * (1 - v / maxY);
let s = `<svg viewBox="0 0 ${W} ${H}" width="100%" role="img" aria-label="Weekly plays per station">`;
for (let k = 0; k <= 4; k++) {
const v = maxY * k / 4;
s += `<line x1="${L}" x2="${W - R}" y1="${Y(v)}" y2="${Y(v)}" stroke="var(--line)"/><text x="${L - 6}" y="${Y(v) + 4}" text-anchor="end">${Math.round(v)}</text>`;
}
s += `<rect x="${X(n - 0.5)}" y="${T}" width="${X(n + f - 1) - X(n - 0.5)}" height="${H - T - B}" fill="var(--accent-soft)" opacity=".6"/>`;
s += `<text x="${X(n - 0.3)}" y="${T + 12}">forecast</text>`;
// forecast band of total plays scaled to "per station" (÷ 4 so it shares the axis), labelled
if (f) {
const up = fcs.map((x, i) => `${X(n + i)},${Y((x.hi ?? 0) / 4)}`).join(' ');
const dn = fcs.map((x, i) => `${X(n + i)},${Y((x.lo ?? 0) / 4)}`).reverse().join(' ');
s += `<polygon points="${up} ${dn}" fill="var(--muted)" opacity=".18"/>`;
s += `<polyline points="${X(n - 1)},${Y(total[n - 1] / 4)} ${fcs.map((x, i) => `${X(n + i)},${Y((x.mean ?? 0) / 4)}`).join(' ')}" fill="none" stroke="var(--muted)" stroke-width="2" stroke-dasharray="4 3"/>`;
s += `<polyline points="${total.map((t, i) => `${X(i)},${Y(t / 4)}`).join(' ')}" fill="none" stroke="var(--muted)" stroke-width="1.5" opacity=".6"/>`;
}
GROUPS.forEach(([g], k) => {
const v = series[k];
if (!v.some(x => x > 0)) return;
s += `<polyline points="${v.map((y, i) => `${X(i)},${Y(y)}`).join(' ')}" fill="none" stroke="${COLORS[g]}" stroke-width="2"/>`;
});
[0, Math.floor(n / 2), n - 1].forEach(i => s += `<text x="${X(i)}" y="${H - 8}" text-anchor="middle">${fmtDate(a.weeks[i])}</text>`);
if (f) s += `<text x="${X(n + f - 1)}" y="${H - 8}" text-anchor="end">${fmtDate(fcs[f - 1].week)}</text>`;
s += '</svg>';
s += `<div class="legend">${GROUPS.map(([g, l]) => `<span><i style="background:${COLORS[g]}"></i>${l}${g === 'p4' ? ' (avg region)' : ''}</span>`).join('')}<span><i style="background:var(--muted)"></i>All DR ÷ 4, forecast with 80% band</span></div>`;
return s;
}
async function showArtist(id) {
openDrawer('<div class="sec">Loading…</div>');
const a = await API('artist?id=' + encodeURIComponent(id));
if (a.error) { openDrawer(`<div class="sec">${esc(a.error)}</div>`); return; }
const h = +$('h').value, w = $('w').value;
const fc = (data[h + '|' + w] || []).find(r => r.id === id) || {};
const fp = a.forecasts.find(x => x.h === Math.max(Math.min(h, 12), 1)) || {};
const facts = [a.country, a.description, a.debut ? `active since ${a.debut}` : null].filter(Boolean).map(esc).join(' · ');
const runs = {};
a.charts.forEach(c => { const k = c.chart + '|' + c.title; (runs[k] ??= { ...c, weeks: 0, best: 99, first: c }); runs[k].weeks++; runs[k].best = Math.min(runs[k].best, c.position); runs[k].first = c; });
const runList = Object.values(runs).slice(0, 12);
openDrawer(`
<div class="dhead">
${a.image ? `<img src="${esc(a.image)}" alt="">` : '<img alt="">'}
<div><h2>${esc(a.name)}</h2><div class="note">${facts}</div></div>
<button class="x" aria-label="Close" onclick="closeDrawer()">×</button>
</div>
<div class="sec">
<h3>If they release a new song in the week of ${fmtDate(windowStart(h))}: chance DR adds it within ${w} weeks</h3>
${fc.too_soon ? '<p class="note"><b>Too soon:</b> less than 6 weeks after their last release, so there\'s no new-song estimate for this week. Pick a later week, or see their calendar.</p>' : `<div class="kpis">
<div class="kpi"><div>Any DR station</div><b>${pct(fc.add_any_rel)}</b></div>
${GROUPS.map(([g, l]) => `<div class="kpi"><div>${l}</div><b>${pct(chanP(fc, g))}</b></div>`).join('')}
</div>
${fc.add_any_nmf != null ? `<p class="note">If it's placed on New Music Friday Denmark: <b>${pct(fc.add_any_nmf)}</b> (their releases were placed about ${pct(fc.p_nmf)} of the time).</p>` : ''}`}
<p><button class="more" style="margin:8px 0" onclick="closeDrawer(); openBest('${esc(id)}', '${esc(a.name).replace(/'/g, "\\'")}')">See the best week to release →</button></p>
<p class="note">In rotation now: ${nowChips(a.now, Object.fromEntries(Object.entries(a.bauer || {}).map(([s, v]) => [s, v.plays])))} · plays in the week of ${fp.week ? fmtDate(fp.week) : '—'}: <b>${Math.round(fp.mean ?? 0)}</b> (${Math.round(fp.lo ?? 0)}–${Math.round(fp.hi ?? 0)})</p>
</div>
<div class="sec"><h3>Weekly plays, last 51 weeks and next 12</h3>${historyChart(a)}</div>
<div class="sec"><h3>What if…</h3><div id="wi" class="note">Loading the model…</div></div>
${a.bauer ? `<div class="sec"><h3>Bauer radio, last 7 days</h3><div class="chips">${Object.entries(a.bauer).sort((x, y) => y[1].plays - x[1].plays).map(([s, v]) => `<span class="chip"><b>${BAUER[s] || s}</b> ${v.plays} plays: ${v.songs.map(t => `${esc(t.title)} (${t.plays})`).join(', ')}</span>`).join('')}</div><p class="note">Bauer publishes no rotation lists or history; plays are collected daily from now on, and Bauer adds join the model once there are a few weeks of logs.</p></div>` : ''}
${a.top_tracks.length ? `<div class="sec"><h3>Most played on DR (all time)</h3><div class="tracks">${a.top_tracks.map(t => `<div>${esc(t.title)} <span class="note">${t.total}</span></div>`).join('')}</div></div>` : ''}
${runList.length ? `<div class="sec"><h3>Chart runs (IFPI)</h3><div class="chips">${runList.map(r => `<span class="chip">${r.chart === 't40' ? 'Track Top-40' : 'Airplay Top-20'}: ${esc(r.title)}, peak #${r.best}, ${r.weeks} wk, ${r.first.year}</span>`).join('')}</div></div>` : ''}
`);
whatIfUI(a, h);
}
function whatIfUI(a, h) {
const box = $('wi');
box.innerHTML = `<div class="wi">
<div class="row"><label for="wi-h">Release week (weeks from now)</label><input type="range" id="wi-h" min="0" max="12" value="${Math.min(h, 12)}"><b id="wi-hv"></b></div>
<div class="row"><label for="wi-r">Releases a new song that week</label><input type="checkbox" id="wi-r" checked><b></b></div>
<div class="row"><label for="wi-n">…placed on New Music Friday Denmark</label><input type="checkbox" id="wi-n"><b></b></div>
<div class="row"><label for="wi-e">New chart entry, weeks ago</label><input type="range" id="wi-e" min="-1" max="26" value="-1"><b id="wi-ev"></b></div>
<div class="row"><label for="wi-t">Track Top-40 position now</label><input type="range" id="wi-t" min="0" max="40" value="0"><b id="wi-tv"></b></div>
<div class="row"><label for="wi-a">Airplay Top-20 position now</label><input type="range" id="wi-a" min="0" max="20" value="0"><b id="wi-av"></b></div>
<div id="wi-out"></div>
<p class="note">Move the release week, switch the release or NMF placement, and change the artist's chart situation (as if it were true this week) to see how the forecast moves.</p>
</div>`;
let init = false, timer = null;
const label = () => {
$('wi-hv').textContent = '+' + $('wi-h').value;
$('wi-ev').textContent = $('wi-e').value < 0 ? 'none' : $('wi-e').value;
$('wi-tv').textContent = +$('wi-t').value ? '#' + $('wi-t').value : 'off';
$('wi-av').textContent = +$('wi-a').value ? '#' + $('wi-a').value : 'off';
};
const run = async () => {
label();
let qs = `id=${encodeURIComponent(a.id)}&h=${$('wi-h').value}`;
qs += `&release=${$('wi-r').checked ? 'yes' : 'no'}&nmf=${$('wi-n').checked ? 'yes' : 'no'}`;
if (init) qs += `&entry=${$('wi-e').value < 0 ? 'none' : $('wi-e').value}&t40=${$('wi-t').value}&air=${$('wi-a').value}`;
const r = await fetch(BASE + '/api/whatif?' + qs);
if (r.status === 503) { $('wi-out').innerHTML = '<p class="note">The model is still loading on the server; try again in a minute.</p>'; return; }
const w = await r.json();
if (w.error) { $('wi-out').innerHTML = `<p class="note">${esc(w.error)}</p>`; return; }
if (!init) {
init = true;
$('wi-e').value = w.current.entry == null ? -1 : Math.min(26, w.current.entry);
$('wi-t').value = w.current.t40; $('wi-a').value = w.current.air;
label();
}
const d = (x, y, f) => { const v = y - x; if (Math.abs(v) < 0.005 * (f === 'p' ? 1 : 100)) return ''; return `<span class="d ${v > 0 ? 'up' : 'down'}">${v > 0 ? '+' : ''}${f === 'p' ? Math.round(v * 100) + ' pts' : Math.round(v)}</span>`; };
const rows = [['Any DR station', w.base.add_any, w.scenario.add_any]].concat(GROUPS.map(([g, l]) => [l, chanP(w.base, g), chanP(w.scenario, g)]));
const onNow = Object.keys(w.current.in_rotation || {});
$('wi-out').innerHTML = `<p class="note">${w.release ? (w.too_soon ? 'Too soon after their last release for a new-song estimate this week; the numbers below are the model\'s extrapolation.' : `A new song released the week of ${fmtDate(w.window_start)}: chance DR adds it within 2 weeks.`) : `No new release: chance of a new add from current songs in the 8 weeks from ${fmtDate(w.window_start)}.`} In rotation now on ${onNow.length ? onNow.length + ' station(s)' : 'no station'}. Now: ${w.current.t40 ? 'Track Top-40 #' + w.current.t40 : 'not on the Track Top-40'}, ${w.current.air ? 'Airplay Top-20 #' + w.current.air : 'not on the Airplay Top-20'}, ${w.current.entry == null ? 'no chart entry on record' : 'latest new chart entry ' + w.current.entry + ' weeks ago'}.</p>
<div class="kpis">${rows.map(([l, b, s]) => `<div class="kpi"><div>${l}</div><b>${pct(s)}</b>${d(b, s, 'p')}<div>was ${pct(b)}</div></div>`).join('')}
<div class="kpi"><div>Plays, first week</div><b>${Math.round(w.scenario.mean)}</b>${d(w.base.mean, w.scenario.mean, 'n')}<div>was ${Math.round(w.base.mean)}</div></div></div>`;
};
['wi-h', 'wi-r', 'wi-n', 'wi-e', 'wi-t', 'wi-a'].forEach(id => $(id).addEventListener('input', () => { label(); clearTimeout(timer); timer = setTimeout(run, 120); }));
run();
}
// ---------- model tab ----------
function renderModel() {
const sc = (meta.backtest || []).filter(x => x.metric.startsWith('event_'));
const win = sc.length ? Math.max(...sc.map(x => x.h)) : 2;
const get = (m, k) => sc.find(x => x.model === m && x.metric === k && x.h === win)?.value;
const ms = [['rate by in-rotation-now', 'Rate by "in rotation now"'], ['rate by last-12-weeks level', 'Rate by last-12-weeks airplay'], ['release timing only', 'Release timing only'],
['model + pooled isotonic (pre-release)', 'Model before release, isotonic (any station on this site)'], ['model + pooled Platt (pre-release)', 'Model before release, Platt (per station on this site)'],
['model, NMF known (post-release)', 'Model, NMF placement known']];
const f = (v, d) => v == null || isNaN(v) ? '—' : v.toFixed(d);
const ska = get('model + pooled isotonic (pre-release)', 'event_skill_any_vs_level'), skc = get('model + pooled Platt (pre-release)', 'event_skill_ch_vs_level');
const sign = v => `<b class="${v > 0 ? 'up' : 'down'}">${v > 0 ? '+' : ''}${f(v, 3)}</b>`;
$('cards').innerHTML = sc.length ? `<div class="card"><h3>If an artist releases a new song, does DR add it within ${win} week${win > 1 ? 's' : ''}?</h3>
<table class="wtable"><thead><tr><th class="l"></th><th>Any station<br>log-loss</th><th>Any station<br>PR-AUC</th><th>Per station<br>log-loss</th><th>Per station<br>PR-AUC</th></tr></thead><tbody>
${ms.map(([m, l]) => `<tr><td class="l">${l}</td><td>${f(get(m, 'event_logloss_any'), 3)}</td><td>${f(get(m, 'event_prauc_any'), 3)}</td><td>${f(get(m, 'event_logloss_ch'), 4)}</td><td>${f(get(m, 'event_prauc_ch'), 3)}</td></tr>`).join('')}
</tbody></table>
<p>Walk-forward over the past year: each week's releases scored by a model fitted only on releases whose outcome was already known, artists included only from when they were knowable. Skill vs last-12-weeks airplay: ${sign(ska)} any station, ${sign(skc)} per station. Lower log-loss and higher PR-AUC are better; a leak test confirms no feature uses data from after the forecast week.</p></div>`
: '<p class="note">No backtest stored yet (`airplay model events`).</p>';
}
// ---------- next week ----------
let nw = null, nwFilter = 'all', nwGroup = 'any';
const GROUP_C = { P3: 'var(--p3)', P4: 'var(--p4)', P5: 'var(--p5)', P6: 'var(--p6)', P8: 'var(--p8)' };
// A single week is a narrow window (an average artist: about 0.3%), so certainty is shown against
// that: how many times an average artist's chance.
let nwBase = 0.003;
const certainty = p => { const m = p / nwBase; return m >= 25 ? [0, 'Top pick'] : m >= 15 ? [1, 'Strong'] : m >= 8 ? [2, 'Contender'] : [3, 'Outside chance']; };
const oneIn = p => p >= 0.5 ? `${Math.round(p * 10)} in 10` : `1 in ${Math.max(2, Math.round(1 / p))}`;
const fmtLong = s => new Date(s + 'T00:00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'long', timeZone: 'UTC' });
const plusDays = (s, d) => { const x = new Date(s + 'T00:00:00Z'); x.setUTCDate(x.getUTCDate() + d); return x.toISOString().slice(0, 10); };
async function loadNext() {
if (nw) return renderNext();
const r = await fetch(`${BASE}/api/nextweek`); nw = await r.json();
renderNext();
}
// What this week's plays say, for the artist's most likely station group.
function liveLine(g) {
if (!g || !g.tau) return '';
const tau = g.tau, pace = g.pace, wk = g.this_week, lw = g.last_week;
const [cls, text] = lw >= tau ? ['up', 'Already in rotation last week'] : pace >= tau ? ['up', 'Crossing the line this week'] : pace >= 0.6 * tau ? ['', 'Building'] : wk > 0 ? ['', 'Some plays so far'] : ['down', 'No plays yet this week'];
const w = Math.min(100, 100 * pace / (tau * 1.5)), m = 100 / 1.5;
return `<div class="live" style="--c:${GROUP_C[g.group]}"><span class="st ${cls}">${text}</span> on ${g.group}: ${wk} plays so far this week, on pace for ${pace}; last week ${lw}. Rotation line ${tau}.
<div class="meter"><i style="width:${w}%"></i><u style="left:${m}%" title="rotation line"></u></div></div>`;
}
function renderNext() {
const d = nw;
if (!d || !d.ready) { $('nw').innerHTML = '<p class="empty">The next-week forecast is produced by the daily run; it is not there yet.</p>'; return; }
const end = plusDays(d.week, 6), t = d.track || {};
// Track record: bins of the walk-forward test of exactly this forecast.
const bins = []; let lo = 0;
// Bands with fewer than 30 past forecasts say nothing yet; left out.
d.bins.forEach((hi, i) => { if (t[`any_bin${i}_n`] >= 30) bins.push({ lo, hi, n: t[`any_bin${i}_n`], pred: t[`any_bin${i}_pred`], obs: t[`any_bin${i}_obs`] }); lo = hi; });
const pct1 = p => (p * 100).toFixed(p < 0.1 ? 1 : 0) + '%';
// The track record shown up front: the highest band with enough forecasts to mean something.
const showcase = bins.filter(b => b.n >= 200 && b.lo > 0).sort((a, b) => b.lo - a.lo)[0] || bins[0];
nwBase = t.any_rate || 0.003;
const top10 = d.list.slice(0, 10).reduce((s, x) => s + x.p, 0), pmax = Math.max(...d.list.map(x => x.p), 0.01);
const groups = ['P3', 'P4', 'P5', 'P6', 'P8'];
const enrich = x => { const gs = Object.entries(x.groups).map(([g, v]) => ({ group: g, ...v })).sort((a, b) => b.p - a.p); return { ...x, gs, best: gs[0] }; };
let list = d.list.map(enrich);
if (nwFilter === 'new') list = list.filter(x => !x.seasonal); else if (nwFilter === 'seasonal') list = list.filter(x => x.seasonal);
if (nwGroup !== 'any') list = list.filter(x => x.groups[nwGroup]).sort((a, b) => b.groups[nwGroup].p - a.groups[nwGroup].p);
const card = x => {
const p = nwGroup === 'any' ? x.p : x.groups[nwGroup].p, [ci, cl] = certainty(p);
const g = nwGroup === 'any' ? x.best : { group: nwGroup, ...x.groups[nwGroup] };
return `<div class="cc" data-id="${esc(x.id)}">
<div class="top"><div class="nm">${esc(x.name)}<small>${x.danish ? 'Danish' : 'International'}${x.seasonal ? ' · <span class="tag2">Seasonal return</span>' : ''}</small></div>
<div class="big"><b>${pct(p)}</b><br><span class="cert c${ci}">${cl}</span></div></div>
<div class="rel"><div class="track2"><i style="width:${Math.min(100, 100 * p / pmax)}%"></i></div><span><b>${oneIn(p)}</b> · ${Math.round(p / nwBase)}× an average artist</span></div>
<div class="chs">${x.gs.filter(v => v.p >= 0.01).map(v => `<span style="--c:${GROUP_C[v.group]}">${v.group} ${pct(v.p)}</span>`).join('') || '<span style="--c:var(--line)">no single station stands out</span>'}</div>
${liveLine(g)}
${x.song ? `<div class="note">Playing now: <b>${esc(x.song.title)}</b> (${x.song.plays} plays on DR this week)</div>` : ''}
</div>`;
};
const chart = () => {
if (!bins.length) return '<p class="note">No track record stored yet (`airplay model nextweek`).</p>';
// Zoomed to the range the forecasts use (a single week: mostly under 15%).
const top = Math.min(1, Math.max(0.15, ...bins.map(b => Math.max(b.pred, b.obs) * 1.25)));
const W = 320, H = 240, P = 44, X = v => P + v / top * (W - P - 10), Y = v => H - P - v / top * (H - P - 10);
const maxn = Math.max(...bins.map(b => b.n));
return `<svg viewBox="0 0 ${W} ${H}" width="100%" role="img" aria-label="Predicted against what happened">
<line x1="${X(0)}" y1="${Y(0)}" x2="${X(top)}" y2="${Y(top)}" stroke="var(--line)" stroke-dasharray="4 4"/>
<line x1="${X(0)}" y1="${Y(0)}" x2="${X(top)}" y2="${Y(0)}" stroke="var(--muted)"/><line x1="${X(0)}" y1="${Y(0)}" x2="${X(0)}" y2="${Y(top)}" stroke="var(--muted)"/>
${[0, .25, .5, .75, 1].map(f => f * top).map(v => `<text x="${X(v)}" y="${H - P + 16}" text-anchor="middle">${Math.round(v * 100)}%</text><text x="${P - 6}" y="${Y(v) + 4}" text-anchor="end">${Math.round(v * 100)}%</text>`).join('')}
<text x="${(W + P) / 2}" y="${H - 2}" text-anchor="middle">we predicted</text>
<text x="8" y="${(H - P) / 2}" text-anchor="middle" transform="rotate(-90 8 ${(H - P) / 2})" dy="-2">it happened</text>
${bins.filter(b => b.pred <= top && b.obs <= top).map(b => `<circle cx="${X(b.pred)}" cy="${Y(b.obs)}" r="${3 + 9 * Math.sqrt(b.n / maxn)}" fill="var(--accent)" fill-opacity=".75"><title>${Math.round(b.lo * 100)}-${Math.round(b.hi * 100)}%: predicted ${pct1(b.pred)}, happened ${pct1(b.obs)} (${b.n} forecasts)</title></circle>`).join('')}
</svg>`;
};
$('nw').innerHTML = `
<div class="nw-hero">
<div><div class="eyebrow">DR rotation forecast</div>
<h2>Who DR adds the week of ${fmtLong(d.week)} to ${fmtLong(end)}</h2>
<p class="note">The chance each artist enters rotation on a DR music channel that week: a new song, or plays jumping well above their usual level. Forecast made ${fmtLong(d.made_at.slice(0, 10))} from DR's artist pages up to the week of ${fmtLong(d.origin_week)}; the live lines use every DR play logged since ${fmtLong(plusDays(d.this_monday, -7))}.</p></div>
<div class="nw-kpis">
<div class="kpi"><div>Expected adds on DR</div><b>${Math.round(d.expected)}</b><small>90% range ${Math.round(d.range[0])}-${Math.round(d.range[1])}</small></div>
<div class="kpi"><div>From our top 10</div><b>${top10.toFixed(1)}</b><small>adds expected among the ten strongest candidates</small></div>
<div class="kpi"><div>Track record</div><b>${showcase ? (showcase.obs * 100).toFixed(1) + '%' : '—'}</b><small>${showcase ? `came true when we said ${Math.round(showcase.lo * 100)}-${Math.round(showcase.hi * 100)}% (${Math.round(showcase.n).toLocaleString('en')} forecasts)` : 'not tested yet'}</small></div>
</div>
</div>
<div class="nw-h">Add board: most likely per station</div>
<div class="board">${groups.map(g => `<div class="col" style="--c:${GROUP_C[g]}"><h4>${g}</h4>${(d.boards[g] || []).map(x => `<div class="it" data-id="${esc(x.id)}"><span>${esc(x.name)}</span><b>${pct(x.p)}</b><i style="width:${Math.max(4, x.p * 100)}%"></i></div>`).join('') || '<p class="note">No strong candidates</p>'}</div>`).join('')}</div>
<div class="nw-h">The candidates</div>
<div class="nw-filters">
${[['all', 'All'], ['new', 'New music'], ['seasonal', 'Seasonal returns']].map(([k, l]) => `<button class="pill ${nwFilter === k ? 'on' : ''}" data-f="${k}">${l}</button>`).join('')}
<span style="width:12px"></span>
${['any', ...groups].map(g => `<button class="pill ${nwGroup === g ? 'on' : ''}" data-g="${g}">${g === 'any' ? 'Any station' : g}</button>`).join('')}
</div>
<div class="cand">${list.slice(0, 40).map(card).join('') || '<p class="empty">No candidates above 3%.</p>'}</div>
<div class="nw-h">How sure are we?</div>
<div class="track"><div class="card">${chart()}</div>
<div class="prose note"><p>Each dot is a group of past forecasts made exactly like this one: a 1-week window, ${d.horizon + 1} weeks after the latest complete week of DR data, scored on what DR actually did (walk-forward, ${t.any_origins ? Math.round(t.any_origins) + ' forecast weeks' : 'past year'}, nothing from the future used). On the dashed line the percentages mean what they say. Bigger dots hold more forecasts.</p>
<p>${bins.map(b => `We said ${Math.round(b.lo * 100)}-${Math.round(b.hi * 100)}% (on average ${pct1(b.pred)}): it happened ${pct1(b.obs)} of ${Math.round(b.n).toLocaleString('en')} times`).join(' · ')}. Higher bands have too few past forecasts to show yet.</p>
<p>One week is a narrow window: an average artist on DR's books has about ${(nwBase * 100).toFixed(1)}% chance of being added in any given week, and even the strongest candidates rarely pass 1 in 10. So we grade against that: <b>Top pick</b> 25× an average artist or more · <b>Strong</b> 15-25× · <b>Contender</b> 8-15× · <b>Outside chance</b> below. "1 in 10" means: of ten artists with this chance, about one gets added that week. Adds of old songs (Christmas, classics) are marked <span class="tag2">Seasonal return</span> when we can tell; the forecast itself does not yet separate them.</p>
${t.any_roc ? `<p>Ranking quality on the same test: an artist who got added was ranked above one who did not ${Math.round(t.any_roc * 100)}% of the time (ROC-AUC ${t.any_roc.toFixed(3)}).</p>` : ''}</div></div>`;
document.querySelectorAll('#nw [data-f]').forEach(b => b.onclick = () => { nwFilter = b.dataset.f; renderNext(); });
document.querySelectorAll('#nw [data-g]').forEach(b => b.onclick = () => { nwGroup = b.dataset.g; renderNext(); });
document.querySelectorAll('#nw [data-id]').forEach(el => el.onclick = () => showArtist(el.dataset.id));
}
// ---------- wiring ----------
document.querySelectorAll('nav button').forEach(b => b.addEventListener('click', () => {
document.querySelectorAll('nav button').forEach(x => x.classList.toggle('on', x === b));
showTab(b.dataset.tab);
}));
function showTab(t) {
document.querySelectorAll('nav button').forEach(x => x.classList.toggle('on', x.dataset.tab === t));
['rank', 'next', 'best', 'model'].forEach(k => $('tab-' + k).hidden = k !== t);
if (t === 'next') loadNext();
}
$('h').addEventListener('input', () => { shown = 100; loadRank(); });
$('w').addEventListener('change', () => { shown = 100; loadRank(); });
['ch', 'sort', 'dk'].forEach(id => $(id).addEventListener('change', () => { shown = 100; render(); }));
// ---------- best week ----------
const artistByName = new Map();
let bestId = null;
function fillArtistList(rows) {
if (artistByName.size) return;
const opts = [];
rows.slice().sort((a, b) => a.name.localeCompare(b.name)).forEach(r => { if (!artistByName.has(r.name)) { artistByName.set(r.name, r.id); opts.push(`<option value="${esc(r.name)}">`); } });
$('bw-list').innerHTML = opts.join('');
}
function openBest(id, name) { bestId = id; $('bw-q').value = name; showTab('best'); loadBest(); }
async function loadBest() {
if (!bestId) return;
const w = $('bw-w').value, nmf = $('bw-nmf').value, ch = $('bw-ch').value;
$('bw-out').innerHTML = '<p class="empty">Loading…</p>';
// Dates: from next week, at most 12 months.
const next = windowStart(0);
if (!$('bw-from').value) $('bw-from').value = next;
if ($('bw-from').value < next) $('bw-from').value = next;
const maxTo = new Date($('bw-from').value + 'T00:00:00Z'); maxTo.setUTCFullYear(maxTo.getUTCFullYear() + 1);
if (!$('bw-to').value) { const d = new Date($('bw-from').value + 'T00:00:00Z'); d.setUTCDate(d.getUTCDate() + 7 * 25); $('bw-to').value = d.toISOString().slice(0, 10); }
if ($('bw-to').value > maxTo.toISOString().slice(0, 10)) $('bw-to').value = maxTo.toISOString().slice(0, 10);
if ($('bw-to').value < $('bw-from').value) $('bw-to').value = $('bw-from').value;
$('bw-from').min = next; $('bw-to').min = $('bw-from').value; $('bw-to').max = maxTo.toISOString().slice(0, 10);
const r = await fetch(`${BASE}/api/bestweek?id=${encodeURIComponent(bestId)}&w=${w}&nmf=${nmf}&from=${$('bw-from').value}&to=${$('bw-to').value}`);
if (r.status === 503) { $('bw-out').innerHTML = '<p class="empty">The model is still loading on the server; try again in a minute.</p>'; return; }
const b = await r.json();
if (b.error) { $('bw-out').innerHTML = `<p class="empty">${esc(b.error)}</p>`; return; }
const val = x => x.too_soon ? null : (ch === 'any' ? x.p : x.groups[ch]);
const vals = b.weeks.map(val).filter(v => v != null);
const max = Math.max(...vals), min = Math.min(...vals), avg = vals.reduce((s, v) => s + v, 0) / (vals.length || 1);
const best = b.weeks.find(x => val(x) === max);
// like a fare calendar: green = among the best weeks for this artist, red = among the worst
// Colour only real differences: under 3 percentage points across the calendar, the weeks are equal.
const spread = max - min;
const level = v => { if (v == null || spread < 0.03) return 2; const z = (v - min) / spread; return z >= 0.85 ? 0 : z >= 0.5 ? 1 : z >= 0.2 ? 2 : 3; };
$('bw-out').innerHTML = vals.length ? `
<div class="bw-head"><h2>${esc(b.name)}</h2>
<span>${spread < 0.03 ? `The weeks are nearly equal (within ${Math.max(1, Math.round(spread * 100))} percentage points): about <b>${pct(avg)}</b> chance DR adds a new song within ${w} weeks${ch === 'any' ? '' : ' on ' + ch}, whichever week (outside the "too soon" weeks).` : `Best week: <b>${fmtDate(best.week)}</b> · <b>${pct(max)}</b> chance DR adds a new song within ${w} weeks${ch === 'any' ? '' : ' on ' + ch} (worst ${pct(min)}, average ${pct(avg)}).`}</span></div>
<div class="cal">${b.weeks.map(x => { const v = val(x); return `<div class="day ${x.too_soon ? 'soon' : 'lvl' + level(v)} ${x === best && spread >= 0.03 ? 'best' : ''}" title="Release the week of ${fmtDate(x.week)}">
<div class="d">Week of ${fmtDate(x.week)}</div><div class="v">${x.too_soon ? 'too soon' : pct(v)}</div>${x.christmas ? '<span class="tag" title="Christmas weeks">🎄</span>' : ''}</div>`; }).join('')}</div>
<p class="note">Each tile: if ${esc(b.name)} releases a new song that week, the chance DR puts it into rotation within ${w} weeks. ${b.last_release ? `Their last release: ${fmtDate(b.last_release)}; weeks less than 6 weeks after it are "too soon" (the model only learned from releases with a clear gap).` : ''} The new song's NMF Denmark placement: ${nmf === 'auto' ? `as often as their releases were placed (${pct(b.p_nmf)})` : nmf === 'yes' ? 'placed' : 'not placed'}. What moves the numbers from week to week: time since their last release and last DR add, Christmas, and their NMF history; their current airplay is taken as it is now.</p>`
: `<h2>${esc(b.name)}</h2><p class="empty">No week in this period has an estimate.</p>`;
}
$('bw-q').addEventListener('change', () => { const id = artistByName.get($('bw-q').value); if (id) { bestId = id; loadBest(); } });
['bw-w', 'bw-nmf', 'bw-ch', 'bw-from', 'bw-to'].forEach(id => $(id).addEventListener('change', loadBest));
$('q').addEventListener('input', () => { shown = 100; render(); });
$('more').addEventListener('click', () => { shown += 100; render(); });
$('rows').addEventListener('click', e => { const tr = e.target.closest('tr[data-id]'); if (tr) showArtist(tr.dataset.id); });
$('shade').addEventListener('click', closeDrawer);
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeDrawer(); });
loadMeta().then(() => meta.ready && loadRank());
</script>
</body>
</html>