File size: 31,163 Bytes
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c24ea90
b9e7b9b
 
c24ea90
b9e7b9b
 
 
 
 
c24ea90
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c24ea90
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
c24ea90
b9e7b9b
 
 
 
c24ea90
b9e7b9b
 
 
98780a5
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98780a5
 
 
 
 
 
 
 
 
 
 
 
 
b9e7b9b
98780a5
 
 
b9e7b9b
 
 
 
 
c59bbe1
 
a024e38
 
 
 
b9e7b9b
c59bbe1
 
 
 
a024e38
c59bbe1
b9e7b9b
 
 
 
 
 
 
 
c59bbe1
cb92d91
c59bbe1
b9e7b9b
 
c59bbe1
 
b010293
b9e7b9b
c59bbe1
 
 
 
 
 
 
 
 
 
 
 
 
b010293
cb92d91
b9e7b9b
c59bbe1
cb92d91
b9e7b9b
1d06a79
b9e7b9b
 
 
 
1d06a79
 
 
 
 
99af53b
1d06a79
b9e7b9b
 
 
 
a76e825
b9e7b9b
03cd478
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
 
 
af61be0
 
 
 
 
 
 
 
 
 
db5abc7
af61be0
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
 
 
 
b6281fd
 
b9e7b9b
 
 
 
 
 
 
1d06a79
 
03cd478
 
b9e7b9b
1d06a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b010293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
1d06a79
b9e7b9b
 
 
 
 
 
d5cbadd
 
 
 
 
 
 
 
 
 
 
281e5ea
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
b9e7b9b
d61f156
 
b6281fd
 
d61f156
b6281fd
d61f156
 
b6281fd
cb92d91
b9e7b9b
 
 
d61f156
b9e7b9b
 
 
 
 
 
 
 
 
 
 
b6281fd
281e5ea
 
 
 
 
 
 
 
 
 
b6281fd
 
 
 
 
 
 
281e5ea
b6281fd
 
281e5ea
b6281fd
d61f156
 
 
 
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
b9e7b9b
 
 
cb92d91
b9e7b9b
 
c59bbe1
b9e7b9b
 
 
 
c59bbe1
b9e7b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281e5ea
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
b9e7b9b
 
c59bbe1
 
 
 
 
0e04b08
 
 
c59bbe1
 
0e04b08
 
 
 
 
 
 
c59bbe1
 
 
b6281fd
 
 
 
7aa7e99
b6281fd
 
c59bbe1
 
 
1d06a79
0e04b08
 
 
1d06a79
0e04b08
 
 
a76e825
0e04b08
1d06a79
a76e825
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d06a79
c59bbe1
 
 
1d06a79
c59bbe1
 
 
1d06a79
c59bbe1
 
1d06a79
73c8635
1d06a79
 
 
 
 
 
 
 
 
 
 
 
 
03cd478
1d06a79
 
 
 
 
 
 
 
b010293
 
1d06a79
 
 
b010293
1d06a79
 
b010293
1d06a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
 
 
 
 
 
 
 
b010293
 
 
c59bbe1
af61be0
b010293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59bbe1
 
 
 
 
 
 
b9e7b9b
 
c59bbe1
 
 
 
 
 
a76e825
 
 
 
 
 
 
c59bbe1
 
b010293
 
 
c59bbe1
 
 
 
a76e825
c59bbe1
 
b9e7b9b
c59bbe1
af61be0
c59bbe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9e7b9b
 
 
 
 
 
 
 
 
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
<div class="d3-line" style="width:100%;margin:10px 0;"></div>
<style>
  .d3-line .d3-line__controls select {
    font-size: 12px;
    padding: 8px 28px 8px 10px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background-color: var(--surface-bg);
    color: var(--text-color);
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%230f1115' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 8px center;
    background-size: 12px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    transition: border-color .15s ease, box-shadow .15s ease;
  }
  [data-theme="dark"] .d3-line .d3-line__controls select {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
  }
  .d3-line .d3-line__controls select:hover {
    border-color: var(--primary-color);
  }
  .d3-line .d3-line__controls select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(232,137,171,.25);
    outline: none;
  }
  .d3-line .d3-line__controls label { gap: 8px; }

  /* Range slider themed with --primary-color */
  .d3-line .d3-line__controls input[type="range"] { 
    -webkit-appearance: none; 
    appearance: none; 
    width: 100%; 
    height: 6px; 
    border-radius: 999px; 
    background: var(--border-color);
    outline: none;
  }
  .d3-line .d3-line__controls input[type="range"]::-webkit-slider-runnable-track {
    height: 6px; 
    background: transparent; 
    border-radius: 999px;
  }
  .d3-line .d3-line__controls input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; 
    appearance: none; 
    width: 16px; 
    height: 16px; 
    border-radius: 50%; 
    background: var(--primary-color); 
    border: 2px solid var(--on-primary);
    margin-top: -5px; 
    cursor: pointer;
  }
  .d3-line .d3-line__controls input[type="range"]::-moz-range-track {
    height: 6px; 
    background: transparent; 
    border-radius: 999px;
  }
  .d3-line .d3-line__controls input[type="range"]::-moz-range-thumb {
    width: 16px; 
    height: 16px; 
    border-radius: 50%; 
    background: var(--primary-color); 
    border: 2px solid var(--on-primary);
    cursor: pointer;
  }
  /* Improved line color via CSS */
  .d3-line .lines path.improved { stroke: var(--primary-color); }
</style>
<script>
  (() => {
    const THIS_SCRIPT = document.currentScript;
    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 = THIS_SCRIPT;
      const host = scriptEl && scriptEl.parentElement;
      let container = null;
      if (host && host.querySelector) {
        container = host.querySelector('.d3-line') || host.querySelector('.d3-runline');
      }
      if (!container) {
        let sib = scriptEl && scriptEl.previousElementSibling;
        while (sib && !(sib.classList && (sib.classList.contains('d3-line') || sib.classList.contains('d3-runline')))) {
          sib = sib.previousElementSibling;
        }
        container = sib || document.querySelector('.d3-line, .d3-runline');
      }
      if (!container) return;
      if (container.classList && container.classList.contains('d3-runline') && !container.classList.contains('d3-line')) {
        container.classList.add('d3-line');
      }
      if (container.dataset) {
        if (container.dataset.mounted === 'true') return;
        container.dataset.mounted = 'true';
      }

      // CSV: prefer public path, fallback to relative
      const CSV_PATHS = [
        '/data/remove_ch.csv',
        './assets/data/remove_ch.csv',
        '../assets/data/remove_ch.csv',
        '../../assets/data/remove_ch.csv'
      ];
      const fetchFirstAvailable = async (paths) => {
        for (const p of paths) {
          try { const r = await fetch(p, { cache: 'no-cache' }); if (r.ok) return await r.text(); } catch(e) {}
        }
        throw new Error('CSV not found: remove_ch.csv');
      };

      // Controls UI
      const controls = document.createElement('div');
      controls.className = 'd3-line__controls';
      Object.assign(controls.style, {
        marginTop: '12px',
        display: 'flex',
        gap: '16px',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%'
      });

      const labelMetric = document.createElement('label');
      Object.assign(labelMetric.style, {
        fontSize: '11px', color: 'var(--muted-color)', opacity: 0.8, display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap', padding: '6px 10px', marginLeft: 'auto'
      });
      labelMetric.textContent = 'Metric';
      const selectMetric = document.createElement('select');
      Object.assign(selectMetric.style, { fontSize: '12px' });
      labelMetric.appendChild(selectMetric);

      // Inline legend on the right of the select
      const legendInline = document.createElement('div');
      legendInline.className = 'controls__legend';
      Object.assign(legendInline.style, {
        display: 'flex',
        gap: '8px',
        alignItems: 'center',
        flexWrap: 'nowrap',
        fontSize: '14px',
        marginLeft: '8px'
      });
      controls.appendChild(legendInline);
      controls.appendChild(labelMetric);

      // Create SVG with marker definitions
      const svg = d3.select(container).append('svg')
        .attr('width', '100%')
        .style('display', 'block');

      // Add marker definitions for different shapes
      const defs = svg.append('defs');
      
      // Academic marker shapes
      const markerShapes = ['circle', 'square', 'triangle', 'diamond', 'inverted-triangle'];
      const markerSize = 5;

      // Groups
      const gRoot = svg.append('g');
      const gGrid = gRoot.append('g').attr('class', 'grid');
      const gAxes = gRoot.append('g').attr('class', 'axes');
      const gAreas = gRoot.append('g').attr('class', 'areas');
      const gLines = gRoot.append('g').attr('class', 'lines');
      const gPoints = gRoot.append('g').attr('class', 'points');
      const gHover = gRoot.append('g').attr('class', 'hover');
      const gLegend = gRoot.append('foreignObject').attr('class', 'legend');

      // Tooltip
      container.style.position = container.style.position || 'relative';
      let tip = container.querySelector('.d3-tooltip');
      let tipInner;
      if (!tip) {
        tip = document.createElement('div');
        tip.className = 'd3-tooltip';
        Object.assign(tip.style, {
          position: 'absolute', top: '0px', left: '0px', transform: 'translate(-9999px, -9999px)', pointerEvents: 'none',
          padding: '8px 10px', borderRadius: '8px', fontSize: '12px', lineHeight: '1.35', border: '1px solid var(--border-color)',
          background: 'var(--surface-bg)', color: 'var(--text-color)', boxShadow: '0 4px 24px rgba(0,0,0,.18)', opacity: '0',
          transition: 'opacity .12s ease'
        });
        tipInner = document.createElement('div');
        tipInner.className = 'd3-tooltip__inner';
        tipInner.style.textAlign = 'left';
        tip.appendChild(tipInner);
        container.appendChild(tip);
      } else {
        tipInner = tip.querySelector('.d3-tooltip__inner') || tip;
      }

      // Colors per run
      const primary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#E889AB';
      const pool = [primary, '#4EA5B7', '#E38A42', '#CEC0FA', ...(d3.schemeTableau10||[])];

      // Mapping from metric names to display titles
      const metricTitleMapping = {
        'docvqa_val_anls': 'DocVQA',
        'infovqa_val_anls': 'InfoVQA',
        'mme_total_score': 'MME Total',
        'mmmu_val_mmmu_acc': 'MMMU',
        'mmstar_average': 'MMStar',
        'ocrbench_ocrbench_accuracy': 'OCRBench',
        'scienceqa_exact_match': 'ScienceQA',
        'textvqa_val_exact_match': 'TextVQA',
        'average': 'Average',
        'average_rank': 'Average Rank',
        'ai2d_exact_match': 'AI2D',
        'chartqa_relaxed_overall': 'ChartQA',
        'seedbench_seed_all': 'SeedBench'
      };

      // Function to get display name for metric
      function getMetricDisplayName(metricKey) {
        return metricTitleMapping[metricKey] || metricKey;
      }

      // State and data
      let metricList = [];
      let runList = [];
      let runOrder = [];
      const dataByMetric = new Map(); // metric => { run => [{step,value}] }
      let isRankStrictFlag = false;
      let rankTickMax = 1;

      // Scales and layout
      let width = 800, height = 360;
      let margin = { top: 16, right: 28, bottom: 56, left: 64 };
      let xScale = d3.scaleLinear();
      let yScale = d3.scaleLinear();

      // Line generators - simple linear connections
      const lineGen = d3.line()
        .x((d) => xScale(d.step))
        .y((d) => yScale(d.value));

      // Function to draw different marker shapes
      function drawMarker(selection, shape, size) {
        const s = size / 2;
        switch (shape) {
          case 'circle':
            return selection.append('circle').attr('r', s);
          case 'square':
            return selection.append('rect').attr('x', -s).attr('y', -s).attr('width', size).attr('height', size);
          case 'triangle':
            return selection.append('path').attr('d', `M0,${-s * 1.2} L${s * 1.1},${s * 0.6} L${-s * 1.1},${s * 0.6} Z`);
          case 'diamond':
            return selection.append('path').attr('d', `M0,${-s * 1.2} L${s * 1.1},0 L0,${s * 1.2} L${-s * 1.1},0 Z`);
          case 'inverted-triangle':
            return selection.append('path').attr('d', `M0,${s * 1.2} L${s * 1.1},${-s * 0.6} L${-s * 1.1},${-s * 0.6} Z`);
          default:
            return selection.append('circle').attr('r', s);
        }
      }

      // Small SVG markup for marker shape (used in tooltip)
      function shapeSvgMarkup(shape, color) {
        const size = 9; // visual marker size
        const half = size / 2;
        const cx = 9, cy = 7; // center for 18x14 viewport
        const stroke = color;
        switch (shape) {
          case 'circle':
            return `<svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true"><g transform="translate(${cx},${cy})"><circle r="${half}" fill="${color}" stroke="${stroke}" stroke-width="1"/></g></svg>`;
          case 'square':
            return `<svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true"><g transform="translate(${cx},${cy})"><rect x="${-half}" y="${-half}" width="${size}" height="${size}" fill="${color}" stroke="${stroke}" stroke-width="1"/></g></svg>`;
          case 'triangle':
            return `<svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true"><g transform="translate(${cx},${cy})"><path d="M0,${-half * 1.2} L${half * 1.1},${half * 0.6} L${-half * 1.1},${half * 0.6} Z" fill="${color}" stroke="${stroke}" stroke-width="1"/></g></svg>`;
          case 'diamond':
            return `<svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true"><g transform="translate(${cx},${cy})"><path d="M0,${-half * 1.2} L${half * 1.1},0 L0,${half * 1.2} L${-half * 1.1},0 Z" fill="${color}" stroke="${stroke}" stroke-width="1"/></g></svg>`;
          case 'inverted-triangle':
            return `<svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true"><g transform="translate(${cx},${cy})"><path d="M0,${half * 1.2} L${half * 1.1},${-half * 0.6} L${-half * 1.1},${-half * 0.6} Z" fill="${color}" stroke="${stroke}" stroke-width="1"/></g></svg>`;
          default:
            return `<svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true"><g transform="translate(${cx},${cy})"><circle r="${half}" fill="${color}" stroke="${stroke}" stroke-width="1"/></g></svg>`;
        }
      }

      // Hover elements
      const hoverLine = gHover.append('line').attr('stroke-width', 1);

      const overlay = gHover.append('rect').attr('fill', 'transparent').style('cursor', 'crosshair');

      function updateScales() {
        const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
        const axisColor = isDark ? 'rgba(255,255,255,0.25)' : 'rgba(0,0,0,0.25)';
        const tickColor = isDark ? 'rgba(255,255,255,0.70)' : 'rgba(0,0,0,0.55)';
        const gridColor = isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)';

        width = container.clientWidth || 800;
        height = Math.max(360, Math.round(width / 2.2));
        svg.attr('width', width).attr('height', height);

        const innerWidth = width - margin.left - margin.right;
        const innerHeight = height - margin.top - margin.bottom;
        gRoot.attr('transform', `translate(${margin.left},${margin.top})`);

        // Responsive legend layout like against-baselines-deduplicated
        try {
          const shouldWrapLegend = width < 1300;
          if (legendInline && legendInline.style) {
            legendInline.style.flexWrap = shouldWrapLegend ? 'wrap' : 'nowrap';
            legendInline.style.rowGap = shouldWrapLegend ? '4px' : '';
            legendInline.style.maxWidth = shouldWrapLegend ? Math.max(280, Math.round(width * 0.62)) + 'px' : 'unset';
            legendInline.style.alignItems = shouldWrapLegend ? 'flex-start' : 'center';
          }
        } catch {}

        // Mobile layout: stack legend above select, allow legend to take full width
        try {
          const isMobile = width < 640;
          if (controls && controls.style && labelMetric && labelMetric.style) {
            controls.style.flexDirection = isMobile ? 'column' : 'row';
            controls.style.alignItems = isMobile ? 'flex-start' : 'center';
            labelMetric.style.marginLeft = isMobile ? '0' : 'auto';
            if (legendInline && legendInline.style) {
              legendInline.style.width = isMobile ? '100%' : '';
              legendInline.style.justifyContent = isMobile ? 'flex-start' : '';
            }
          }
        } catch {}

        xScale.range([0, innerWidth]);
        yScale.range([innerHeight, 0]);

        // Compute Y ticks
        let yTicks = [];
        if (isRankStrictFlag) {
          const maxR = Math.max(1, Math.round(rankTickMax));
          for (let v = 1; v <= maxR; v += 1) yTicks.push(v);
        } else {
          // Use D3's tick generator to produce nice floating-point ticks
          yTicks = yScale.ticks(6);
        }

        // Grid (horizontal)
        gGrid.selectAll('*').remove();
        gGrid.selectAll('line')
          .data(yTicks)
          .join('line')
          .attr('x1', 0)
          .attr('x2', innerWidth)
          .attr('y1', (d) => yScale(d))
          .attr('y2', (d) => yScale(d))
          .attr('stroke', gridColor)
          .attr('stroke-width', 1)
          .attr('shape-rendering', 'crispEdges');

        // Axes
        gAxes.selectAll('*').remove();
        let xAxis = d3.axisBottom(xScale).tickSizeOuter(0);
        const isMobileTicks = width < 640;
        const tfMobile = (d) => {
          const abs = Math.abs(d);
          if (abs >= 1000) {
            const v = d / 1000;
            const out = Math.abs(v) >= 10 ? Math.round(v) : +v.toFixed(1);
            return out + 'k';
          }
          return d3.format('d')(d);
        };
        if (isRankStrictFlag) {
          const [dx0, dx1] = xScale.domain();
          const start = Math.ceil(dx0 / 1000) * 1000;
          const end = Math.floor(dx1 / 1000) * 1000;
          const xTicks = [];
          for (let v = start; v <= end; v += 1000) xTicks.push(v);
          if (xTicks.length === 0) xTicks.push(Math.round(dx0));
          xAxis = xAxis.tickValues(xTicks).tickFormat(isMobileTicks ? tfMobile : d3.format('d'));
        } else {
          xAxis = xAxis.ticks(8);
          if (isMobileTicks) xAxis = xAxis.tickFormat(tfMobile);
        }
        const yAxis = d3.axisLeft(yScale)
          .tickValues(yTicks)
          .tickSizeOuter(0)
          .tickFormat(isRankStrictFlag ? d3.format('d') : d3.format('.2f'));
        gAxes.append('g')
          .attr('transform', `translate(0,${innerHeight})`)
          .call(xAxis)
          .call((g) => {
            g.selectAll('path, line').attr('stroke', axisColor);
            g.selectAll('text').attr('fill', tickColor).style('font-size', '12px');
          });
        gAxes.append('g')
          .call(yAxis)
          .call((g) => {
            g.selectAll('path, line').attr('stroke', axisColor);
            g.selectAll('text').attr('fill', tickColor).style('font-size', '12px');
          });

        // Axis labels (X and Y)
        gAxes.append('text')
          .attr('class', 'axis-label axis-label--x')
          .attr('x', innerWidth / 2)
          .attr('y', innerHeight + 44)
          .attr('text-anchor', 'middle')
          .style('font-size', '12px')
          .style('fill', tickColor)
          .text('Step');
        gAxes.append('text')
          .attr('class', 'axis-label axis-label--y')
          .attr('text-anchor', 'middle')
          .attr('transform', `translate(${-44},${innerHeight/2}) rotate(-90)`) 
          .style('font-size', '12px')
          .style('fill', tickColor)
          .text('Value');

        overlay.attr('x', 0).attr('y', 0).attr('width', innerWidth).attr('height', innerHeight);
        hoverLine.attr('y1', 0).attr('y2', innerHeight).attr('stroke', axisColor);

        // Legend placeholder; actual content set in renderMetric
        const legendWidth = Math.min(180, Math.max(120, Math.round(innerWidth * 0.22)));
        const legendHeight = 64;
        gLegend
          .attr('x', innerWidth - legendWidth + 42)
          .attr('y', innerHeight - legendHeight - 12)
          .attr('width', legendWidth)
          .attr('height', legendHeight);
        const legendRoot = gLegend.selectAll('div').data([0]).join('xhtml:div');
        Object.assign(legendRoot.node().style, {
          background: 'transparent',
          border: 'none',
          borderRadius: '0',
          padding: '0',
          fontSize: '12px',
          lineHeight: '1.35',
          color: 'var(--text-color)'
        });

        // Mobile layout: stack legend above select, allow legend to take full width
        try {
          const isMobile = width < 640;
          if (controls && controls.style && labelMetric && labelMetric.style) {
            controls.style.flexDirection = isMobile ? 'column' : 'row';
            controls.style.alignItems = isMobile ? 'flex-start' : 'center';
            labelMetric.style.marginLeft = isMobile ? '0' : 'auto';
            if (legendInline && legendInline.style) {
              legendInline.style.width = isMobile ? '100%' : '';
              legendInline.style.justifyContent = isMobile ? 'flex-start' : '';
            }
          }
        } catch {}

        return { innerWidth, innerHeight };
      }

      function renderMetric(metricKey){
        const map = dataByMetric.get(metricKey) || {};
        const runs = runOrder;
        // Domain
        let minStep = Infinity, maxStep = -Infinity, maxVal = 0, minVal = Infinity;
        const isRank = /rank/i.test(metricKey);
        const isAverage = /average/i.test(metricKey);
        const isRankStrict = isRank && !isAverage;
        runs.forEach(r => {
          const arr = map[r] || [];
          arr.forEach(pt => {
            const val = isRankStrict ? Math.round(pt.value) : pt.value;
            minStep = Math.min(minStep, pt.step);
            maxStep = Math.max(maxStep, pt.step);
            maxVal = Math.max(maxVal, val);
            minVal = Math.min(minVal, val);
          });
        });
        if (!isFinite(minStep) || !isFinite(maxStep)) { return; }
        xScale.domain([minStep, maxStep]);
        if (isRank) {
          rankTickMax = Math.max(1, Math.round(maxVal));
          yScale.domain([rankTickMax, 1]);
        } else {
          yScale.domain([minVal, maxVal]).nice();
        }
        isRankStrictFlag = isRankStrict;

        const { innerWidth, innerHeight } = updateScales();

        // Bind lines and markers
        const series = runs.map((r, i) => ({
          run: r,
          color: pool[i % pool.length],
          marker: markerShapes[i % markerShapes.length],
          values: (map[r]||[])
            .slice()
            .sort((a,b)=>a.step-b.step)
            .map(pt => isRankStrict ? { step: pt.step, value: Math.round(pt.value), stderr: pt.stderr } : pt)
        }));

        // Uncertainty area (± stderr) for non-rank metrics
        gAreas.selectAll('*').remove();
        if (!isRank) {
          series.forEach((s) => {
            const withErr = s.values.filter(v => v && v.stderr != null && isFinite(v.stderr) && v.stderr > 0 && isFinite(v.value));
            if (withErr.length === 0) return;
            const upper = withErr.map(d => [xScale(d.step), yScale(d.value + d.stderr)]);
            const lower = withErr.slice().reverse().map(d => [xScale(d.step), yScale(d.value - d.stderr)]);
            const coords = upper.concat(lower);
            const pathData = d3.line().x(d=>d[0]).y(d=>d[1]).curve(d3.curveLinearClosed)(coords);
            gAreas.append('path')
              .attr('d', pathData)
              .attr('fill', s.color)
              .attr('opacity', 0.15)
              .attr('stroke', 'none');
          });
        }

        // Draw lines
        const paths = gLines.selectAll('path.run-line').data(series, d=>d.run);
        paths.enter().append('path').attr('class','run-line').attr('fill','none').attr('stroke-width',2)
          .attr('stroke', d=>d.color).attr('opacity',0.9)
          .attr('d', d=>lineGen(d.values))
          .merge(paths)
          .transition().duration(200)
          .attr('stroke', d=>d.color)
          .attr('d', d=>lineGen(d.values));
        paths.exit().remove();

        // Draw markers for each data point
        gPoints.selectAll('*').remove();
        series.forEach((s, seriesIndex) => {
          const pointGroup = gPoints.selectAll(`.points-${seriesIndex}`)
            .data(s.values)
            .join('g')
            .attr('class', `points-${seriesIndex}`)
            .attr('transform', d => `translate(${xScale(d.step)},${yScale(d.value)})`);
          
          drawMarker(pointGroup, s.marker, markerSize)
            .attr('fill', s.color)
            .attr('stroke', s.color)
            .attr('stroke-width', 1.5)
            .style('cursor', 'crosshair');
        });

        // Inline legend content with marker shapes
        legendInline.innerHTML = '';
        series.forEach(s => {
          const legendItem = document.createElement('span');
          legendItem.style.cssText = 'display:inline-flex;align-items:center;gap:6px;white-space:nowrap;';
          
          // Create small SVG for marker shape
          const markerSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
          markerSvg.setAttribute('width', '18');
          markerSvg.setAttribute('height', '14');
          markerSvg.style.display = 'inline-block';
          
          const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
          g.setAttribute('transform', 'translate(9,7)');
          
          let shape;
          const size = 9;
          const halfSize = size / 2;
          switch(s.marker) {
            case 'circle':
              shape = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
              shape.setAttribute('r', halfSize);
              break;
            case 'square':
              shape = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
              shape.setAttribute('x', -halfSize);
              shape.setAttribute('y', -halfSize);
              shape.setAttribute('width', size);
              shape.setAttribute('height', size);
              break;
            case 'triangle':
              shape = document.createElementNS('http://www.w3.org/2000/svg', 'path');
              shape.setAttribute('d', `M0,${-halfSize * 1.2} L${halfSize * 1.1},${halfSize * 0.6} L${-halfSize * 1.1},${halfSize * 0.6} Z`);
              break;
            case 'diamond':
              shape = document.createElementNS('http://www.w3.org/2000/svg', 'path');
              shape.setAttribute('d', `M0,${-halfSize * 1.2} L${halfSize * 1.1},0 L0,${halfSize * 1.2} L${-halfSize * 1.1},0 Z`);
              break;
            case 'inverted-triangle':
              shape = document.createElementNS('http://www.w3.org/2000/svg', 'path');
              shape.setAttribute('d', `M0,${halfSize * 1.2} L${halfSize * 1.1},${-halfSize * 0.6} L${-halfSize * 1.1},${-halfSize * 0.6} Z`);
              break;
            default:
              shape = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
              shape.setAttribute('r', halfSize);
          }
          shape.setAttribute('fill', s.color);
          shape.setAttribute('stroke', s.color);
          shape.setAttribute('stroke-width', '1');
          
          g.appendChild(shape);
          markerSvg.appendChild(g);
          
          const label = document.createElement('span');
          label.textContent = s.run;
          
          legendItem.appendChild(markerSvg);
          legendItem.appendChild(label);
          legendInline.appendChild(legendItem);
        });

        // Hover
        const stepSet = new Set(); series.forEach(s=>s.values.forEach(v=>stepSet.add(v.step)));
        const steps = Array.from(stepSet).sort((a,b)=>a-b);
        function onMove(event){
          const [mx, my] = d3.pointer(event, overlay.node());
          const sx = Math.max(steps[0], Math.min(steps[steps.length-1], Math.round(xScale.invert(mx)/1)*1));
          const nearest = steps.reduce((best, s)=> Math.abs(s - xScale.invert(mx)) < Math.abs(best - xScale.invert(mx)) ? s : best, steps[0]);
          const xpx = xScale(nearest);
          const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
          const axisColor = isDark ? 'rgba(255,255,255,0.25)' : 'rgba(0,0,0,0.25)';
          hoverLine.attr('x1', xpx).attr('x2', xpx).style('display', null).attr('stroke', axisColor);
          // Tooltip content
          let html = `<div><strong>${getMetricDisplayName(metricKey)}</strong></div><div><strong>step</strong> ${nearest}</div>`;
          const seriesWithPoint = series
            .map(s => {
              const m = new Map(s.values.map(v=>[v.step, v]));
              const pt = m.get(nearest);
              return { s, pt };
            })
            .filter(d => d.pt && d.pt.value != null);
          // Sort runs at hovered step
          seriesWithPoint.sort((a,b) => {
            if (isRankStrict) return (b.pt.value - a.pt.value); // rank: descendant
            return (a.pt.value - b.pt.value); // normal: ascendant
          });
          seriesWithPoint.forEach(({s, pt}) => {
            const formatVal = (vv) => (isRankStrict ? d3.format('d')(vv) : (+vv).toFixed(4));
            const errTxt = (pt.stderr != null && isFinite(pt.stderr) && pt.stderr > 0) ? ` ± ${formatVal(pt.stderr)}` : '';
            html += `<div style=\"display:flex;align-items:center;gap:6px;white-space:nowrap;\">${shapeSvgMarkup(s.marker, s.color)}<strong>${s.run}</strong> ${formatVal(pt.value)}${errTxt}</div>`;
          });
          tipInner.innerHTML = html;
          const offsetX = 12, offsetY = 12;
          tip.style.opacity = '1'; tip.style.transform = `translate(${Math.round(mx + offsetX + margin.left)}px, ${Math.round(my + offsetY + margin.top)}px)`;
        }
        function onLeave(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; hoverLine.style('display','none'); }
        overlay.on('mousemove', onMove).on('mouseleave', onLeave);
      }

      // (old hover removed; hover is attached in renderMetric)

      // Load CSV and wire controls
      (async () => {
        try {
          const text = await fetchFirstAvailable(CSV_PATHS);
          const rows = d3.csvParse(text, d => ({
            run: (d.run||'').trim(),
            step: +d.step,
            metric: (d.metric||'').trim(),
            value: +d.value,
            stderr: (d.stderr != null && d.stderr !== '') ? +d.stderr : null
          }));
          metricList = Array.from(new Set(rows.map(r=>r.metric))).sort();
          runList = Array.from(new Set(rows.map(r=>r.run))).sort();
          // Prioritize "FineVision" first in legend/order
          const hasFV = runList.includes('FineVision');
          runOrder = hasFV ? ['FineVision', ...runList.filter(r => r !== 'FineVision')] : runList;
          // Build dataByMetric
          metricList.forEach(m => {
            const map = {};
            runList.forEach(r => { map[r] = []; });
            rows.filter(r=>r.metric===m).forEach(r => { if (!isNaN(r.step) && !isNaN(r.value)) map[r.run].push({ step:r.step, value:r.value, stderr:r.stderr }); });
            dataByMetric.set(m, map);
          });

          // Populate metric select (default to average_rank if present)
          metricList.forEach((m)=>{ const o=document.createElement('option'); o.value=m; o.textContent=getMetricDisplayName(m); selectMetric.appendChild(o); });
          const def = metricList.find(m => /average_rank/i.test(m)) || metricList[0];
          if (def) selectMetric.value = def;

          container.appendChild(controls);
          updateScales();
          renderMetric(selectMetric.value);

          selectMetric.addEventListener('change', ()=>{ renderMetric(selectMetric.value); });

          const rerender = () => { renderMetric(selectMetric.value); };
          if (window.ResizeObserver) { const ro = new ResizeObserver(()=>rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); }
        } catch (e) {
          const pre = document.createElement('pre'); pre.textContent = 'CSV load error: ' + (e && e.message ? e.message : e);
          pre.style.color = 'var(--danger, #b00020)'; pre.style.fontSize = '12px'; pre.style.whiteSpace = 'pre-wrap';
          container.appendChild(pre);
        }
      })();
    };

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