CoolFace
Apppublic

lerobot/robot-learning-tutorial

sourceHugging Faceupdated 1y agoView on Hugging Face
508likes
d3-line.html459 linesDownload Raw Back to embeds
1<div class="d3-line-simple"></div>2<style>3  .d3-line-simple { position: relative; }4  .d3-line-simple .controls {5    margin-top: 0;6    display: flex;7    gap: 16px;8    align-items: center;9    justify-content: flex-end;10    width: auto;11    flex-wrap: wrap;12  }13  .d3-line-simple .controls label {14    font-size: 12px;15    color: var(--text-color);16    display: flex;17    align-items: center;18    gap: 6px;19    white-space: nowrap;20    font-weight: 700;21  }22  .d3-line-simple .controls select {23    font-size: 12px;24    padding: 8px 28px 8px 10px;25    border: 1px solid var(--border-color);26    border-radius: 8px;27    background-color: var(--surface-bg);28    color: var(--text-color);29    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");30    background-repeat: no-repeat; background-position: right 8px center; background-size: 12px;31    -webkit-appearance: none; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease;32  }33  [data-theme="dark"] .d3-line-simple .controls select {34    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");35  }36  .d3-line-simple .controls select:hover { border-color: var(--primary-color); }37  .d3-line-simple .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; }38  .d3-line-simple .axis-label { fill: var(--text-color); font-size: 12px; font-weight: 700; }39  .d3-line-simple .axes path, .d3-line-simple .axes line { stroke: var(--axis-color); }40  .d3-line-simple .axes text { fill: var(--tick-color); }41  .d3-line-simple .grid line { stroke: var(--grid-color); }42  .d3-line-simple .legend { font-size: 12px; color: var(--text-color);padding-left: 6px; }43  .d3-line-simple .legend .items { display:flex; flex-wrap:wrap; gap:8px 12px; align-items:center; }44  .d3-line-simple .legend .item { display:flex; align-items:center; gap:6px; white-space:nowrap; }45  .d3-line-simple .legend .swatch { width:14px; height:14px; border-radius:3px; border:1px solid var(--border-color); display:inline-block; }46  /* Ghosting on hover */47  .d3-line-simple.hovering .legend-bottom .item.ghost { opacity: .35; }48  .d3-line-simple.hovering .lines path.ghost { opacity: .25; }49  .d3-line-simple.hovering .points circle.ghost { opacity: .25; }50  .d3-line-simple.hovering .areas path.ghost { opacity: .08; }51  .d3-line-simple .chart-header { display:flex; align-items:center; justify-content:space-between; gap:12px; margin: 0 0 8px 0; flex-wrap: wrap; }52  .d3-line-simple .legend-bottom { display:flex; align-items:center; justify-content:flex-start; font-size:12px; color: var(--text-color); }53  .d3-line-simple .legend-bottom .items { display:flex; flex-wrap:wrap; gap:8px 14px; }54  .d3-line-simple .legend-bottom .item { display:inline-flex; align-items:center; gap:6px; white-space:nowrap; }55  .d3-line-simple .legend-bottom .swatch { width:14px; height:14px; border-radius:3px; border:1px solid var(--border-color); display:inline-block; }56  .d3-line-simple .lines path.active { stroke-width: 3; }57  /* Layout tweaks: stack label above select, add legend title above items */58  .d3-line-simple .controls .control-group {59    display: flex;60    flex-direction: column;61    align-items: flex-start;62    gap: 6px;63  }64  .d3-line-simple .legend-bottom {65    flex-direction: column;66    align-items: flex-start;67    gap: 6px;68  }69  .d3-line-simple .legend-bottom .legend-title {70    font-size: 12px;71    font-weight: 700;72    color: var(--text-color);73  }74  /* Tooltip styling aligned with filters-quad */75  .d3-line-simple .d3-tooltip { z-index: var(--z-elevated); backdrop-filter: saturate(1.12) blur(8px); }76  .d3-line-simple .d3-tooltip__inner { display:flex; flex-direction:column; gap:6px; min-width: 220px; }77  .d3-line-simple .d3-tooltip__inner > div:first-child { font-weight: 800; letter-spacing: 0.1px; margin-bottom: 0; }78  .d3-line-simple .d3-tooltip__inner > div:nth-child(2) { font-size: 11px; color: var(--muted-color); display: block; margin-top: -4px; margin-bottom: 2px; letter-spacing: 0.1px; }79  .d3-line-simple .d3-tooltip__inner > div:nth-child(n+3) { padding-top: 6px; border-top: 1px solid var(--border-color); }80  .d3-line-simple .d3-tooltip__color-dot { display:inline-block; width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-color); }81  /* Chart card only around the SVG */82  .d3-line-simple .chart-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; }83  /* Place header below chart and align start */84  .d3-line-simple .chart-header { display:flex; align-items:flex-start; justify-content:flex-start; gap:12px; margin: 8px 0 0 0; flex-wrap: wrap; }85</style>86<script>87  (() => {88    // Pretty label mapping for metric keys (aligned with filters-quad)89    const prettyMetricLabel = (key) => {90      if (!key) return '';91      const table = {92        'ai2d_exact_match': 'AI2D Exact Match',93        'average_rank': 'Average Rank',94      };95      if (table[key]) return table[key];96      const cleaned = String(key).replace(/[_-]+/g, ' ').trim();97      return cleaned.split(/\s+/).map(w => {98        if (/^(ai2d|umap|id|auc|f1)$/i.test(w)) return w.toUpperCase();99        return w.charAt(0).toUpperCase() + w.slice(1);100      }).join(' ');101    };102 103    const ensureD3 = (cb) => {104      if (window.d3 && typeof window.d3.select === 'function') return cb();105      let s = document.getElementById('d3-cdn-script');106      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); }107      const onReady = () => { if (window.d3 && typeof window.d3.select === 'function') cb(); };108      s.addEventListener('load', onReady, { once: true }); if (window.d3) onReady();109    };110 111    const bootstrap = () => {112      const scriptEl = document.currentScript;113      let container = scriptEl ? scriptEl.previousElementSibling : null;114      if (!(container && container.classList && container.classList.contains('d3-line-simple'))){115        const cs = Array.from(document.querySelectorAll('.d3-line-simple')).filter(el => !(el.dataset && el.dataset.mounted === 'true'));116        container = cs[cs.length - 1] || null;117      }118      if (!container) return;119      if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }120 121      // Controls (we will place them in a footer below the chart)122      const controls = document.createElement('div');123      controls.className = 'controls';124      const controlGroup = document.createElement('div');125      controlGroup.className = 'control-group';126      const labelMetric = document.createElement('label');127      labelMetric.textContent = 'Metric';128      const selectMetric = document.createElement('select');129      // Associate label and select with a unique id130      const uniqueId = Math.random().toString(36).slice(2, 9);131      selectMetric.id = `metric-select-${uniqueId}`;132      labelMetric.setAttribute('for', selectMetric.id);133      controlGroup.appendChild(labelMetric);134      controlGroup.appendChild(selectMetric);135      controls.appendChild(controlGroup);136 137      // Tooltip138      container.style.position = container.style.position || 'relative';139      let tip = container.querySelector('.d3-tooltip'); let tipInner;140      if (!tip) {141        tip = document.createElement('div'); tip.className = 'd3-tooltip';142        Object.assign(tip.style, {143          position:'absolute', top:'0px', left:'0px', transform:'translate(-9999px, -9999px)', pointerEvents:'none',144          padding:'8px 10px', borderRadius:'8px', fontSize:'12px', lineHeight:'1.35', border:'1px solid var(--border-color)',145          background:'var(--surface-bg)', color:'var(--text-color)', boxShadow:'0 4px 24px rgba(0,0,0,.18)', opacity:'0', transition:'opacity .12s ease'146        });147        tipInner = document.createElement('div'); tipInner.className = 'd3-tooltip__inner'; tipInner.style.textAlign='left'; tip.appendChild(tipInner); container.appendChild(tip);148      } else { tipInner = tip.querySelector('.d3-tooltip__inner') || tip; }149 150      // Header (legend + controls) placed after the chart151      const header = document.createElement('div'); header.className = 'chart-header';152      const legendBottom = document.createElement('div'); legendBottom.className = 'legend-bottom'; header.appendChild(legendBottom);153      header.appendChild(controls);154 155      // Chart card (SVG)156      const card = document.createElement('div'); card.className = 'chart-card'; container.appendChild(card);157      container.appendChild(header);158      // SVG159      const svg = d3.select(card).append('svg').attr('width','100%').style('display','block');160      const gRoot = svg.append('g');161      const gGrid = gRoot.append('g').attr('class','grid');162      const gAxes = gRoot.append('g').attr('class','axes');163      const gAreas = gRoot.append('g').attr('class','areas');164      const gLines = gRoot.append('g').attr('class','lines');165      const gPoints = gRoot.append('g').attr('class','points');166      // (legend removed from inside SVG)167      const overlay = gRoot.append('rect').attr('fill','transparent').style('cursor','crosshair');168      const hoverLine = gRoot.append('line').attr('stroke-width',1).style('display','none');169 170      // State/data171      let width = 800, height = 480; const margin = { top: 16, right: 32, bottom: 44, left: 56 };172      const xScale = d3.scaleLinear();173      const yScale = d3.scaleLinear();174      const lineGen = d3.line().x(d => xScale(d.step)).y(d => yScale(d.value));175      const dataByMetric = new Map();176      let runOrder = [];177 178      // Colors179      function getRunColors(count){180        try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') return window.ColorPalettes.getColors('categorical', count); } catch(_){}181        return d3.schemeTableau10 ? d3.schemeTableau10.slice(0, count) : ['#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f','#edc948','#b07aa1','#ff9da7','#9c755f','#bab0ab'].slice(0, count);182      }183      // Format helper for thousands (5000 -> 5k, 1500 -> 1.5k)184      function formatK(v){185        const abs = Math.abs(v);186        if (abs >= 1000) {187          const n = v / 1000;188          const s = d3.format('.1f')(n);189          return (s.endsWith('.0') ? s.slice(0, -2) : s) + 'k';190        }191        return d3.format('d')(v);192      }193 194      // CSV: prefer public path, fallback to relative195      // Data file(s) from HtmlEmbed attribute (string or JSON array), else default cascade196      // Find the HtmlEmbed wrapper that carries data-datafiles197      let mountEl = container;198      while (mountEl && !mountEl.getAttribute?.('data-datafiles') && !mountEl.getAttribute?.('data-config')) {199        mountEl = mountEl.parentElement;200      }201      let providedData = null;202      let providedConfig = null;203      try {204        const attr = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-datafiles') : null;205        if (attr && attr.trim()) {206          providedData = attr.trim().startsWith('[') ? JSON.parse(attr) : attr.trim();207        }208      } catch(_) {}209      try {210        const cfg = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-config') : null;211        if (cfg && cfg.trim()) {212          providedConfig = cfg.trim().startsWith('{') ? JSON.parse(cfg) : cfg;213        }214      } catch(_) {}215      const DEFAULT_CSV = '/data/formatting_filters.csv';216      // Normalize: if a provided path has no slash, assume it lives under /data/217      const ensureDataPrefix = (p) => {218        if (typeof p !== 'string' || !p) return p;219        return p.includes('/') ? p : `/data/${p}`;220      };221      const normalizeInput = (inp) => Array.isArray(inp) ? inp.map(ensureDataPrefix) : (typeof inp === 'string' ? [ ensureDataPrefix(inp) ] : null);222      const CSV_PATHS = Array.isArray(providedData)223        ? normalizeInput(providedData)224        : (typeof providedData === 'string' ? normalizeInput(providedData) || [DEFAULT_CSV] : [225            DEFAULT_CSV,226            './assets/data/formatting_filters.csv',227            '../assets/data/formatting_filters.csv',228            '../../assets/data/formatting_filters.csv'229          ]);230      const fetchFirstAvailable = async (paths) => {231        for (const p of paths) { try { const r = await fetch(p, { cache: 'no-cache' }); if (r.ok) return await r.text(); } catch(_){} }232        throw new Error('CSV not found: formatting_filters.csv');233      };234 235      function updateLayout(){236        const axisColor = getComputedStyle(container).getPropertyValue('--axis-color').trim() || 'rgba(0,0,0,0.25)';237        width = container.clientWidth || 800;238        height = Math.max(280, Math.round(width / 3));239        svg.attr('width', width).attr('height', height);240        gRoot.attr('transform', `translate(${margin.left},${margin.top})`);241        const innerWidth = width - margin.left - margin.right;242        const innerHeight = height - margin.top - margin.bottom;243        overlay.attr('x',0).attr('y',0).attr('width', innerWidth).attr('height', innerHeight);244        hoverLine.attr('y1',0).attr('y2', innerHeight).attr('stroke', axisColor);245        return { innerWidth, innerHeight };246      }247 248      function render(metricKey){249        const { innerWidth, innerHeight } = updateLayout();250        const map = dataByMetric.get(metricKey) || {};251        const runs = runOrder;252        // domains253        let minStep = Infinity, maxStep = -Infinity, minV = Infinity, maxV = -Infinity;254        runs.forEach(r => { (map[r]||[]).forEach(pt => { minStep = Math.min(minStep, pt.step); maxStep = Math.max(maxStep, pt.step); minV = Math.min(minV, pt.value); maxV = Math.max(maxV, pt.value); }); });255        if (!isFinite(minStep) || !isFinite(maxStep)) return;256        xScale.domain([minStep, maxStep]).range([0, innerWidth]);257        yScale.domain([minV, maxV]).nice().range([innerHeight, 0]);258 259        // grid260        gGrid.selectAll('*').remove();261        gGrid.selectAll('line').data(yScale.ticks(6)).join('line')262          .attr('x1',0).attr('x2', innerWidth).attr('y1', d=>yScale(d)).attr('y2', d=>yScale(d))263          .attr('stroke','var(--grid-color)').attr('stroke-width',1).attr('shape-rendering','crispEdges');264 265        // axes266        gAxes.selectAll('*').remove();267        gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(xScale).ticks(8).tickFormat(formatK)).call(g=>{ g.selectAll('path, line').attr('stroke','var(--axis-color)'); g.selectAll('text').attr('fill','var(--tick-color)').style('font-size','12px'); });268        gAxes.append('g').call(d3.axisLeft(yScale).ticks(6)).call(g=>{ g.selectAll('path, line').attr('stroke','var(--axis-color)'); g.selectAll('text').attr('fill','var(--tick-color)').style('font-size','12px'); });269        gAxes.append('text').attr('class','axis-label').attr('text-anchor','middle').attr('x', innerWidth/2).attr('y', innerHeight + 38).text('Step');270        gAxes.append('text').attr('class','axis-label').attr('text-anchor','middle').attr('transform', `translate(${-44}, ${innerHeight/2}) rotate(-90)`).text('Value');271 272        // shaded areas (stderr or min/max if provided)273        gAreas.selectAll('*').remove();274        const areaGenClosed = d3.line().x(d=>d[0]).y(d=>d[1]).curve(d3.curveLinearClosed);275        // Colors (needed for both areas and lines)276        const colors = getRunColors(runs.length);277        const seriesForAreas = [];278        runs.forEach((r, i) => {279          const vals = (map[r]||[]).slice().sort((a,b)=>a.step-b.step);280          const withBounds = vals.map(v => {281            let lo = null, hi = null;282            if (v.stderr != null && isFinite(v.stderr) && v.stderr > 0) { lo = v.value - v.stderr; hi = v.value + v.stderr; }283            if (v.min != null && isFinite(v.min)) lo = (lo==null) ? v.min : lo;284            if (v.max != null && isFinite(v.max)) hi = (hi==null) ? v.max : hi;285            return { step: v.step, lo, hi };286          }).filter(v => v.lo != null && v.hi != null && isFinite(v.lo) && isFinite(v.hi));287          if (withBounds.length > 0) {288            seriesForAreas.push({ run: r, color: colors[i % colors.length], bounds: withBounds });289          }290        });291        seriesForAreas.forEach(s => {292          const upper = s.bounds.map(d => [ xScale(d.step), yScale(d.hi) ]);293          const lower = s.bounds.slice().reverse().map(d => [ xScale(d.step), yScale(d.lo) ]);294          const coords = upper.concat(lower);295          gAreas.append('path')296            .attr('class','area')297            .attr('data-run', s.run)298            .attr('d', areaGenClosed(coords))299            .attr('fill', s.color)300            .attr('opacity', 0.15)301            .attr('stroke','none');302        });303 304        // lines305        const series = runs.map((r, i) => ({ run:r, color: colors[i % colors.length], values: (map[r]||[]).slice().sort((a,b)=>a.step-b.step) }));306        const paths = gLines.selectAll('path.run').data(series, d=>d.run);307        const pathsEnter = paths.enter().append('path').attr('class','run').attr('fill','none').attr('stroke-width',2).attr('stroke', d=>d.color).attr('d', d=>lineGen(d.values));308        pathsEnter.merge(paths).transition().duration(200).attr('stroke', d=>d.color).attr('d', d=>lineGen(d.values));309        paths.exit().remove();310 311        // Hover capture paths (wider invisible stroke for easy hover)312        const captures = gLines.selectAll('path.run-hover').data(series, d=>`cap-${d.run}`);313        captures.enter().append('path').attr('class','run-hover').attr('fill','none').attr('stroke','transparent').attr('stroke-width', 12).style('pointer-events','stroke')314          .attr('d', d=>lineGen(d.values))315          .merge(captures)316          .attr('d', d=>lineGen(d.values))317          .on('mouseenter', function(ev, d){318            container.classList.add('hovering');319            // ghost non hovered lines and points320            gLines.selectAll('path.run').classed('ghost', s => s.run !== d.run);321            gPoints.selectAll('circle.pt').classed('ghost', p => p.run !== d.run);322            gAreas.selectAll('path.area').classed('ghost', a => a && a.getAttribute && a.getAttribute('data-run') !== d.run);323            // ghost legend items324            try {325              const legendNode = legendBottom;326              if (legendNode) {327                legendNode.querySelectorAll('.item').forEach(el => {328                  const name = el.getAttribute('data-run');329                  el.classList.toggle('ghost', name !== d.run);330                });331              }332            } catch {}333          })334          .on('mouseleave', function(){335            container.classList.remove('hovering');336            gLines.selectAll('path.run').classed('ghost', false);337            gPoints.selectAll('circle.pt').classed('ghost', false);338            gAreas.selectAll('path.area').classed('ghost', false);339            try { const legendNode = legendBottom; if (legendNode) legendNode.querySelectorAll('.item').forEach(el => el.classList.remove('ghost')); } catch {}340          });341        captures.exit().remove();342 343        // point markers (subtle)344        const allPts = series.flatMap(s => s.values.map(v => ({ run:s.run, color:s.color, step:v.step, value:v.value })));345        const ptsSel = gPoints.selectAll('circle.pt').data(allPts, d=>`${d.run}-${d.step}`);346        ptsSel.enter().append('circle').attr('class','pt').attr('r', 2).attr('fill', d=>d.color).attr('fill-opacity', 0.6)347          .attr('cx', d=>xScale(d.step)).attr('cy', d=>yScale(d.value))348          .merge(ptsSel).transition().duration(150).attr('cx', d=>xScale(d.step)).attr('cy', d=>yScale(d.value));349        ptsSel.exit().remove();350 351        // legend (HTML below, left) with title above items352        legendBottom.innerHTML = `<div class="legend-title">Legend</div><div class="items">${series.map(s => `<span class="item" data-run="${s.run}"><span class="swatch" style="background:${s.color}"></span><span>${s.run}</span></span>`).join('')}</div>`;353        // Legend hover โ†’ ghost lines/points354        try {355          const legendNode = legendBottom;356          legendNode.querySelectorAll('.item').forEach(el => {357            el.addEventListener('mouseenter', () => {358              const run = el.getAttribute('data-run'); if (!run) return;359              container.classList.add('hovering');360              gLines.selectAll('path.run').classed('ghost', s => s.run !== run);361              gPoints.selectAll('circle.pt').classed('ghost', p => p.run !== run);362              gAreas.selectAll('path.area').classed('ghost', a => a && a.getAttribute && a.getAttribute('data-run') !== run);363              legendNode.querySelectorAll('.item').forEach(it => it.classList.toggle('ghost', it.getAttribute('data-run') !== run));364            });365            el.addEventListener('mouseleave', () => {366              container.classList.remove('hovering');367              gLines.selectAll('path.run').classed('ghost', false);368              gPoints.selectAll('circle.pt').classed('ghost', false);369              gAreas.selectAll('path.area').classed('ghost', false);370              legendNode.querySelectorAll('.item').forEach(it => it.classList.remove('ghost'));371            });372          });373        } catch {}374 375        // hover376        function onMove(ev){377          const [mx, my] = d3.pointer(ev, overlay.node());378          const sx = xScale.invert(mx);379          // nearest integer step if steps are integers; else nearest by distance380          const steps = Array.from(new Set(allPts.map(p=>p.step))).sort((a,b)=>a-b);381          const nearest = steps.reduce((best, s) => Math.abs(s - sx) < Math.abs(best - sx) ? s : best, steps[0]);382          const xpx = xScale(nearest);383          hoverLine.style('display', null).attr('x1', xpx).attr('x2', xpx);384          // tooltip content (styled)385          let html = `<div style=\"font-weight:800;letter-spacing:.1px;\">${metricKey}</div><div style=\"font-size:11px;color:var(--muted-color);margin-top:-4px;margin-bottom:2px;\">Step ${formatK(nearest)}</div>`;386          const entries = series.map(s => {387            const m = new Map(s.values.map(v=>[v.step, v.value]));388            const val = m.get(nearest);389            return { run: s.run, color: s.color, val };390          }).filter(e => e.val != null);391          entries.sort((a, b) => a.val - b.val);392          entries.forEach(e => {393            html += `<div style=\"display:flex;align-items:center;gap:6px;white-space:nowrap;\"><span class=\"d3-tooltip__color-dot\" style=\"background:${e.color}\"></span><strong>${e.run}</strong><span style=\"margin-left:auto;\">${(+e.val).toFixed(4)}</span></div>`;394          });395          tipInner.innerHTML = html; tip.style.opacity = '1'; tip.style.transform = `translate(${Math.round(mx + margin.left + 12)}px, ${Math.round(my + margin.top + 12)}px)`;396        }397        function onLeave(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; hoverLine.style('display','none'); }398        overlay.on('mousemove', onMove).on('mouseleave', onLeave);399      }400 401      // load CSV and init402      (async () => {403        try {404          const text = await fetchFirstAvailable(CSV_PATHS);405          const rows = d3.csvParse(text, d => ({406            run:(d.run||'').trim(),407            step:+d.step,408            metric:(d.metric||'').trim(),409            value:+d.value,410            // Optional bounds: stderr or [min,max] or [lower,upper]411            stderr: (d.stderr!=null && d.stderr!=='') ? +d.stderr : null,412            min: (d.min!=null && d.min!=='') ? +d.min : (d.lower!=null && d.lower!=='') ? +d.lower : null,413            max: (d.max!=null && d.max!=='') ? +d.max : (d.upper!=null && d.upper!=='') ? +d.upper : null414          }));415          const metrics = Array.from(new Set(rows.map(r=>r.metric))).sort();416          runOrder = Array.from(new Set(rows.map(r=>r.run))).sort();417          metrics.forEach(m => {418            const map = {}; runOrder.forEach(r => map[r] = []);419            rows.filter(r=>r.metric===m).forEach(r => {420              if (!isNaN(r.step) && !isNaN(r.value)) map[r.run].push({ step:r.step, value:r.value, stderr: r.stderr, min: r.min, max: r.max });421            });422            dataByMetric.set(m, map);423          });424          // populate metric select (pretty labels) or hide if single-file with single metric425          const isSingleFile = !Array.isArray(providedData) && typeof providedData === 'string';426          metrics.forEach(m => { const o = document.createElement('option'); o.value=m; o.textContent=prettyMetricLabel(m); selectMetric.appendChild(o); });427          // default metric selection via config.defaultMetric (match raw key or pretty label, case-insensitive)428          if (metrics.length) {429            let initial = metrics[0];430            const desired = providedConfig && typeof providedConfig === 'object' && providedConfig.defaultMetric ? String(providedConfig.defaultMetric) : null;431            if (desired) {432              const lcDesired = desired.toLowerCase();433              const byKey = metrics.find(m => m.toLowerCase() === lcDesired);434              const byPretty = metrics.find(m => prettyMetricLabel(m).toLowerCase() === lcDesired);435              initial = byKey || byPretty || initial;436            }437            selectMetric.value = initial;438          }439          if (isSingleFile && metrics.length <= 1) {440            controls.style.display = 'none';441          }442 443          render(selectMetric.value);444          selectMetric.addEventListener('change', () => render(selectMetric.value));445          const rerender = () => render(selectMetric.value);446          if (window.ResizeObserver) { const ro = new ResizeObserver(() => rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); }447        } catch (e) {448          const pre = document.createElement('pre'); pre.textContent = 'CSV load error: ' + (e && e.message ? e.message : e);449          pre.style.color = 'var(--danger, #b00020)'; pre.style.fontSize = '12px'; pre.style.whiteSpace = 'pre-wrap'; container.appendChild(pre);450        }451      })();452    };453 454    if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); }455  })();456</script>457 458 459