File size: 12,629 Bytes
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526a765
 
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4343500
 
 
 
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4343500
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4343500
 
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4343500
 
 
aee6411
 
 
 
 
4343500
 
aee6411
 
4343500
 
aee6411
4343500
aee6411
4343500
 
 
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4343500
aee6411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<div class="d3-score-stack"></div>
<style>
  .d3-score-stack {
    width: 100%;
    margin: 10px 0;
    position: relative;
    font-family: system-ui, -apple-system, sans-serif;
  }

  .d3-score-stack svg {
    display: block;
    width: 100%;
    height: auto;
  }

  .d3-score-stack .axes path,
  .d3-score-stack .axes line {
    stroke: var(--axis-color, var(--text-color));
  }

  .d3-score-stack .axes text {
    fill: var(--tick-color, var(--muted-color));
    font-size: 11px;
  }

  .d3-score-stack .grid line {
    stroke: var(--grid-color, rgba(0,0,0,.08));
  }

  .d3-score-stack .axes text.axis-label {
    font-size: 15px;
    font-weight: 500;
    fill: var(--text-color);
  }

  .d3-score-stack .bar-segment {
    cursor: pointer;
    transition: opacity 0.15s ease;
  }

  .d3-score-stack .bar-segment:hover {
    opacity: 0.8;
  }

  .d3-score-stack .model-label {
    font-size: 12px;
    fill: var(--text-color);
  }

  .d3-score-stack .d3-tooltip {
    position: absolute;
    top: 0;
    left: 0;
    transform: translate(-9999px, -9999px);
    pointer-events: none;
    padding: 10px 12px;
    border-radius: 8px;
    font-size: 12px;
    line-height: 1.4;
    border: 1px solid var(--border-color);
    background: var(--surface-bg);
    color: var(--text-color);
    box-shadow: 0 4px 24px rgba(0,0,0,.18);
    opacity: 0;
    transition: opacity 0.12s ease;
    z-index: 10;
  }

  .d3-score-stack .d3-tooltip .model-name {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .d3-score-stack .d3-tooltip .metric {
    display: flex;
    justify-content: space-between;
    gap: 16px;
  }

  .d3-score-stack .d3-tooltip .metric-label {
    color: var(--muted-color);
  }

  .d3-score-stack .d3-tooltip .metric-value {
    font-weight: 500;
  }

  .d3-score-stack .legend {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 16px;
    margin-top: 12px;
    font-size: 12px;
  }

  .d3-score-stack .legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .d3-score-stack .legend-swatch {
    width: 14px;
    height: 14px;
    border-radius: 2px;
  }

  .d3-score-stack .legend-label {
    color: var(--text-color);
  }
</style>
<script>
  (() => {
    const ensureD3 = (cb) => {
      if (window.d3 && typeof window.d3.select === 'function') return cb();
      let s = document.getElementById('d3-cdn-script');
      if (!s) {
        s = document.createElement('script');
        s.id = 'd3-cdn-script';
        s.src = 'https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js';
        document.head.appendChild(s);
      }
      const onReady = () => { if (window.d3 && typeof window.d3.select === 'function') cb(); };
      s.addEventListener('load', onReady, { once: true });
      if (window.d3) onReady();
    };

    const bootstrap = () => {
      const scriptEl = document.currentScript;
      let container = scriptEl ? scriptEl.previousElementSibling : null;
      if (!(container && container.classList && container.classList.contains('d3-score-stack'))) {
        const candidates = Array.from(document.querySelectorAll('.d3-score-stack'))
          .filter((el) => !(el.dataset && el.dataset.mounted === 'true'));
        container = candidates[candidates.length - 1] || null;
      }
      if (!container) return;
      if (container.dataset) {
        if (container.dataset.mounted === 'true') return;
        container.dataset.mounted = 'true';
      }

      // Tooltip setup
      container.style.position = container.style.position || 'relative';
      const tip = document.createElement('div');
      tip.className = 'd3-tooltip';
      container.appendChild(tip);

      // SVG setup
      const svg = d3.select(container).append('svg');
      const gRoot = svg.append('g');

      // Chart groups
      const gGrid = gRoot.append('g').attr('class', 'grid');
      const gAxes = gRoot.append('g').attr('class', 'axes');
      const gBars = gRoot.append('g').attr('class', 'bars');

      // Legend container
      const legendDiv = document.createElement('div');
      legendDiv.className = 'legend';
      container.appendChild(legendDiv);

      // State
      let data = null;
      let width = 800;
      let height = 500;
      const margin = { top: 20, right: 30, bottom: 56, left: 160 };

      // Colors for segments
      const segmentColors = {
        floored: '#afb2c5',   // Gray - floored score
        noStakes: '#34b31e'   // Green - no-stakes gain
      };

      // Scales
      const xScale = d3.scaleLinear();
      const yScale = d3.scaleBand();

      // Data loading
      const DATA_URL = '/data/score_stack.json';

      function updateSize() {
        width = container.clientWidth || 800;
        const barCount = data ? data.models.length : 10;
        height = Math.max(400, barCount * 44 + margin.top + margin.bottom);
        svg.attr('width', width).attr('height', height).attr('viewBox', `0 0 ${width} ${height}`);
        gRoot.attr('transform', `translate(${margin.left},${margin.top})`);
        return {
          innerWidth: width - margin.left - margin.right,
          innerHeight: height - margin.top - margin.bottom
        };
      }

      function showTooltip(event, d, segment) {
        const rect = container.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        let segmentName, segmentValue, description;
        if (segment === 'floored') {
          segmentName = 'Score';
          segmentValue = d.avg_floored_score.toFixed(2);
          description = 'Floored score (negative scores count as 0)';
        } else {
          segmentName = 'No-Stakes Gain';
          segmentValue = '+' + d.no_stakes_delta.toFixed(2);
          description = 'Additional gain without guess penalties';
        }

        tip.innerHTML = `
          <div class="model-name" style="color: ${d.color}">${d.name}</div>
          <div class="metric">
            <span class="metric-label">${segmentName}:</span>
            <span class="metric-value">${segmentValue}</span>
          </div>
          <div style="font-size: 11px; color: var(--muted-color); margin-top: 4px;">${description}</div>
          <hr style="border: none; border-top: 1px solid var(--border-color); margin: 8px 0;">
          <div class="metric">
            <span class="metric-label">Score:</span>
            <span class="metric-value">${d.avg_floored_score.toFixed(2)}</span>
          </div>
          <div class="metric">
            <span class="metric-label">No-Stakes Score:</span>
            <span class="metric-value">${d.avg_no_stakes_score.toFixed(2)}</span>
          </div>
        `;

        const tipWidth = tip.offsetWidth || 200;
        const tipHeight = tip.offsetHeight || 150;
        let tipX = x + 12;
        let tipY = y - tipHeight / 2;

        if (tipX + tipWidth > width) tipX = x - tipWidth - 12;
        if (tipY < 0) tipY = 8;
        if (tipY + tipHeight > height) tipY = height - tipHeight - 8;

        tip.style.transform = `translate(${tipX}px, ${tipY}px)`;
        tip.style.opacity = '1';
      }

      function hideTooltip() {
        tip.style.opacity = '0';
        tip.style.transform = 'translate(-9999px, -9999px)';
      }

      function render() {
        if (!data) return;

        const { innerWidth, innerHeight } = updateSize();

        // Sort models by floored score (descending)
        const models = [...data.models].sort((a, b) => b.avg_floored_score - a.avg_floored_score);

        // Update scales
        const maxScore = d3.max(models, d => d.avg_no_stakes_score);

        xScale
          .domain([0, maxScore + 1])
          .range([0, innerWidth])
          .nice();

        yScale
          .domain(models.map(d => d.name))
          .range([0, innerHeight])
          .padding(0.25);

        // Grid lines
        const xTicks = xScale.ticks(8);

        gGrid.selectAll('.grid-x')
          .data(xTicks)
          .join('line')
          .attr('class', 'grid-x')
          .attr('x1', d => xScale(d))
          .attr('x2', d => xScale(d))
          .attr('y1', 0)
          .attr('y2', innerHeight);

        // Axes
        const tickSize = 6;
        gAxes.selectAll('.x-axis')
          .data([0])
          .join('g')
          .attr('class', 'x-axis')
          .attr('transform', `translate(0,${innerHeight})`)
          .call(d3.axisBottom(xScale).ticks(8).tickSizeInner(-tickSize).tickSizeOuter(0));

        gAxes.selectAll('.y-axis')
          .data([0])
          .join('g')
          .attr('class', 'y-axis')
          .call(d3.axisLeft(yScale).tickSize(0))
          .selectAll('text')
          .attr('class', 'model-label');

        // Axis label
        gAxes.selectAll('.x-label')
          .data([0])
          .join('text')
          .attr('class', 'x-label axis-label')
          .attr('x', innerWidth / 2)
          .attr('y', innerHeight + 44)
          .attr('text-anchor', 'middle')
          .text('Score');

        const barHeight = yScale.bandwidth();

        // Helper to sanitize names for CSS selectors (remove periods, spaces, etc.)
        const toClassName = (name) => name.replace(/[^a-zA-Z0-9]/g, '-');

        // Draw stacked bars for each model
        models.forEach(d => {
          const y = yScale(d.name);
          const safeId = toClassName(d.name);

          // Calculate segment positions
          // Floored score starts from 0
          const flooredStart = 0;
          const flooredEnd = d.avg_floored_score;

          // No-stakes delta starts where floored ends
          const noStakesStart = flooredEnd;
          const noStakesEnd = noStakesStart + d.no_stakes_delta;

          // Floored score segment (base)
          gBars.selectAll(`.bar-floored-${safeId}`)
            .data([d])
            .join('rect')
            .attr('class', `bar-segment bar-floored-${safeId}`)
            .attr('x', xScale(flooredStart))
            .attr('y', y)
            .attr('width', Math.max(0, xScale(flooredEnd) - xScale(flooredStart)))
            .attr('height', barHeight)
            .attr('fill', segmentColors.floored)
            .on('mouseenter', (e) => showTooltip(e, d, 'floored'))
            .on('mousemove', (e) => showTooltip(e, d, 'floored'))
            .on('mouseleave', hideTooltip);

          // No-stakes delta segment (only if positive)
          if (d.no_stakes_delta > 0.01) {
            gBars.selectAll(`.bar-nostakes-${safeId}`)
              .data([d])
              .join('rect')
              .attr('class', `bar-segment bar-nostakes-${safeId}`)
              .attr('x', xScale(noStakesStart))
              .attr('y', y)
              .attr('width', Math.max(0, xScale(noStakesEnd) - xScale(noStakesStart)))
              .attr('height', barHeight)
              .attr('fill', segmentColors.noStakes)
              .attr('opacity', 0.5)
              .on('mouseenter', (e) => showTooltip(e, d, 'noStakes'))
              .on('mousemove', (e) => showTooltip(e, d, 'noStakes'))
              .on('mouseleave', hideTooltip);
          }
        });

        // Update legend
        legendDiv.innerHTML = `
          <div class="legend-item">
            <div class="legend-swatch" style="background: ${segmentColors.floored}"></div>
            <span class="legend-label">Score</span>
          </div>
          <div class="legend-item">
            <div class="legend-swatch" style="background: ${segmentColors.noStakes}"></div>
            <span class="legend-label">No-Stakes Gain</span>
          </div>
        `;
      }

      // Initialize
      fetch(DATA_URL, { cache: 'no-cache' })
        .then(r => r.json())
        .then(json => {
          data = json;
          render();
        })
        .catch(err => {
          const pre = document.createElement('pre');
          pre.style.color = 'red';
          pre.style.padding = '16px';
          pre.textContent = `Error loading data: ${err.message}`;
          container.appendChild(pre);
        });

      // Resize handling
      if (window.ResizeObserver) {
        new ResizeObserver(() => render()).observe(container);
      } else {
        window.addEventListener('resize', render);
      }

      // Theme change handling
      const observer = new MutationObserver(() => render());
      observer.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ['data-theme']
      });
    };

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true });
    } else {
      ensureD3(bootstrap);
    }
  })();
</script>