thibaud frere commited on
Commit ·
8d0d788
1
Parent(s): 651ae3a
update charts and vibe coding section
Browse filesFiles changed (25)
- app/src/components/HtmlEmbed.astro+14-9
- app/src/content/article.mdx+3
- app/src/content/chapters/components.mdx+40-72
- app/src/content/chapters/vibe-coding-charts.mdxAdded+70
- app/src/content/embeds/banner.html+52-20
- app/src/content/embeds/bar.htmlDeleted-1
- app/src/content/embeds/d3-area-stacked.htmlDeleted-220
- app/src/content/embeds/d3-bar.html+149-43
- app/src/content/embeds/d3-benchmark.htmlAdded+444
- app/src/content/embeds/d3-boxplot.htmlDeleted-251
- app/src/content/embeds/d3-comparison.htmlDeleted-149
- app/src/content/embeds/d3-confusion-matrix.htmlAdded+516
- app/src/content/embeds/d3-line-example.htmlDeleted-456
- app/src/content/embeds/filters-quad.html → app/src/content/embeds/d3-line-quad.htmlRenamed+246-147
- app/src/content/embeds/d3-line.html+387-431
- app/src/content/embeds/d3-matrix.htmlAdded+515
- app/src/content/embeds/d3-neural.html → app/src/content/embeds/d3-neural-network.htmlRenamed+255-79
- app/src/content/embeds/d3-pie.html+83-11
- app/src/content/embeds/d3-scatter.html+51-13
- app/src/content/embeds/heatmap.htmlDeleted-159
- app/src/content/embeds/vibe-code-d3-embeds-directives.md+257-9
- app/src/scripts/color-palettes.js+51-1
- app/src/styles/_variables.css+12
- app/src/styles/components/_card.cssAdded+9
- app/src/styles/global.css+1
1232345611 unmodified lines18192021222324252627262829303150 unmodified lines8283848385868788893 unmodified lines93949593969798991005 unmodified lines106107108109105110111112113114115116112113114117118119120121122---interface Props { src: string; title?: string; desc?: string; frameless?: boolean; align?: 'left' | 'center' | 'right'; id?: string }const { src, title, desc, frameless = false, align = 'left', id } = Astro.props as Props;interface Props { src: string; title?: string; desc?: string; frameless?: boolean; align?: 'left' | 'center' | 'right'; id?: string, data?: string | string[], config?: any }const { src, title, desc, frameless = false, align = 'left', id, data, config } = Astro.props as Props;
// Load all .html embeds under src/content/embeds/** as strings (dev & build)const embeds = (import.meta as any).glob('../content/embeds/**/*.html', { query: '?raw', import: 'default', eager: true }) as Record<string, string>;11 unmodified lines
const html = resolveFragment(src);const mountId = `frag-${Math.random().toString(36).slice(2)}`;const dataAttr = Array.isArray(data) ? JSON.stringify(data) : (typeof data === 'string' ? data : undefined);const configAttr = typeof config === 'string' ? config : (config != null ? JSON.stringify(config) : undefined);---{ html ? ( <figure class="html-embed" id={id}> {title && <figcaption class="html-embed__title" style={`text-align:${align}`}>{title}</figcaption>} <div class={`html-embed__card${frameless ? ' is-frameless' : ''}`}> <div id={mountId} set:html={html} /> <div id={mountId} data-datafiles={dataAttr} data-config={configAttr} set:html={html} /> </div> {desc && <figcaption class="html-embed__desc" style={`text-align:${align}`} set:html={desc}></figcaption>} </figure>50 unmodified lines font-size: 0.95rem; color: var(--text-color); margin: 0; padding: var(--spacing-1); padding: 0; padding-bottom: var(--spacing-1); position: relative; display: block; width: 100%;3 unmodified lines border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; z-index: var(--z-elevated); z-index: calc(var(--z-elevated) + 1); position: relative; } .html-embed__card.is-frameless { background: transparent;5 unmodified lines font-size: 0.9rem; color: var(--muted-color); margin: 0; padding: 0; padding: var(--spacing-1); padding-top: var(--spacing-1); position: relative; z-index: var(--z-elevated); display: block; width: 100%; } /* Plotly – fragments & controls */ .html-embed__card svg text { fill: var(--text-color) !important; } .html-embed__card label { color: var(--text-color) !important; } .plotly-graph-div { width: 100% !important; min-height: 320px; } .html-embed__card svg text { fill: var(--text-color); } .html-embed__card label { color: var(--text-color); } .plotly-graph-div { width: 100%; min-height: 320px; } @media (max-width: 768px) { .plotly-graph-div { min-height: 260px; } } [id^="plot-"] { display: flex; flex-direction: column; align-items: center; gap: 15px; } .plotly_caption { font-style: italic; margin-top: 10px; }28 unmodified lines293031323334355 unmodified lines414243444546474828 unmodified linesimport Markdown from "./chapters/markdown.mdx";import Components from "./chapters/components.mdx";import Greetings from "./chapters/greetings.mdx";import VibeCodingCharts from "./chapters/vibe-coding-charts.mdx";
<Introduction />
5 unmodified lines
<Components />
<VibeCodingCharts />
<BestPractices />
<Greetings />27 unmodified lines28293031323334353637383132332 unmodified lines36373847394041424344454647484950515253176 unmodified lines2302312322332342352362372382392402412422432442452462472482492502512522533 unmodified lines2572582592412602612622633 unmodified lines2672682692702712722732742752762562572582772782792802812822832842852862872882892902911 unmodified line29329429526927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632727 unmodified lines
**Responsive images** automatically generate an optimized `srcset` and `sizes` so the browser downloads the most appropriate file for the current viewport and DPR. You can also request multiple output formats (e.g., **AVIF**, **WebP**, fallback **PNG/JPEG**) and control **lazy loading/decoding** for better **performance**.
| Prop | Required | Description |------------------------|----------|-------------------------------------------------------| `zoomable` | No | Adds a zoomable lightbox (Medium-like). | `downloadable` | No | Adds a download button to fetch the image file. | `loading="lazy"` | No | Lazy loads the image. | `caption` | No | Adds a caption and credit. | `id` | No | Adds an `id` to the outer figure for deep-linking and cross-references.
<ResponsiveImage src={placeholder}2 unmodified lines id="placeholder-image" layout="fixed" alt="A placeholder image alt text" caption={'A placeholder image description <span class="image-credit">From the <a target="_blank" href="https://commons.wikimedia.org/wiki/File:RCA_Indian_Head_Test_Pattern.svg">RCA Indian Head Test Pattern</a></span>'} caption={'A placeholder image description<br/> Credit: <a target="_blank" href="https://commons.wikimedia.org/wiki/File:RCA_Indian_Head_Test_Pattern.svg">RCA Indian Head Test Pattern</a>'}/>
| Prop | Required | Description |------------------------|----------|-------------------------------------------------------| `zoomable` | No | Adds a zoomable lightbox (Medium-like). | `downloadable` | No | Adds a download button to fetch the image file. | `loading="lazy"` | No | Lazy loads the image. | `caption` | No | Adds a caption and credit. | `id` | No | Adds an `id` to the outer figure for deep-linking and cross-references.
<Accordion title="Code example">```mdximport ResponsiveImage from '../components/ResponsiveImage.astro'176 unmodified lines</Accordion>
### Iframes
You can embed external content in your article using **iframes**. For example, **TrackIO**, **Gradio** or even **Github code embeds** can be used this way.
<small className="muted">Gradio embed example</small><div className="card"><iframe src="https://gradio-hello-world.hf.space" width="100%" height="380" frameborder="0"></iframe></div>
<Accordion title="Code example">```mdx<iframe frameborder="0" scrolling="no" style="width:100%; height:292px;" allow="clipboard-write" src="https://emgithub.com/iframe.html?target=https%3A%2F%2Fgithub.com%2Fhuggingface%2Fpicotron%2Fblob%2F1004ae37b87887cde597c9060fb067faa060bafe%2Fsetup.py&style=default&type=code&showBorder=on&showLineNumbers=on"></iframe><iframe src="https://trackio-documentation.hf.space/?project=fake-training-750735&metrics=train_loss,train_accuracy&sidebar=hidden&lang=en" width="100%" height="600" frameborder="0"></iframe><iframe src="https://gradio-hello-world.hf.space" width="100%" height="380" frameborder="0"></iframe>```</Accordion>
### HtmlEmbed
The main purpose of the ```HtmlEmbed``` component is to **embed** a **Plotly** or **D3.js** chart in your article. **Libraries** are already imported in the template.3 unmodified linesFor researchers who want to stay in **Python** while targeting **D3**, the [d3blocks](https://github.com/d3blocks/d3blocks) library lets you create interactive D3 charts with only a few lines of code. In **2025**, **D3** often provides more flexibility and a more web‑native rendering than **Plotly** for custom visualizations.
<HtmlEmbed src="d3-line-example.html" title="This is a chart title" desc="Some chart description" /><HtmlEmbed src="d3-line.html" title="This is a chart title" desc="Figure X: Some chart description<br/>Credit: <a href='https://example.com' target='_blank'>Example</a>" />
| Prop | Required | Description |-------------|----------|----------------------------------------------------------------------------------3 unmodified lines| `frameless` | No | Removes the card background and border for seamless embeds. | `align` | No | Aligns the title/description text. One of `left` (default), `center`, `right`. | `id` | No | Adds an `id` to the outer figure for deep-linking and cross-references. | `data` | No | Path (string) or array of paths (string[]) to data file(s) consumed by the embed. | `config` | No | Optional object for embed options (e.g., `{ defaultMetric: 'average_rank' }`).
<Accordion title="Code example">```mdximport HtmlEmbed from '../components/HtmlEmbed.astro'
<HtmlEmbed src="plotly-line.html" title="Plotly Line" desc="Some chart description" /><HtmlEmbed src="d3-line-example.html" title="D3 Line" desc="Some chart description" /><HtmlEmbed src="d3-line-example.html" id="real-world-examples" title="D3 Line (with id)" desc="Linkable example via #real-world-examples" /><HtmlEmbed src="d3-line.html" title="This is a chart title" desc="Some chart description <br/>Credit: <a href='https://example.com' target='_blank'>Example</a>" />
<HtmlEmbed src="d3-line.html" title="Comparison A vs B" data={[ 'formatting_filters.csv', 'relevance_filters.csv' ]} config={{ defaultMetric: 'average_rank' }}/>```</Accordion>
#### Data
If you need to link your **HTML embeds** to **data files**, there is an **`assets/data`** folder for this.1 unmodified lineYou can fetch them with this address: **`[domain]/data/your-data.ext`**
<Note emoji="⚠️" variant="danger"><b>Be careful</b>, unlike images, <b>data files are not optimized</b> by Astro. You need to optimize them manually.</Note>
#### Vibe coding charts
If you are from the research field, it can be difficult to use **D3.js** charts instead of **Plotly**.Happily, **LLM's** are here to help you! In the `app/src/content/embeds` folder, there is a `vibe-code-d3-embeds-directives.md` file that you can use to vibe code **D3.js** charts.
Inside this file, you will find every directives you need to code your own **HtmlEmbed** proof **D3.js** chart.
#### Real world examples
Here are some examples that were vibe coded to inspire you.
---<HtmlEmbed src="d3-line.html" title="Training curves by metric" desc="Interactive time series across runs. Choose a metric; hover for values." />---<HtmlEmbed src="d3-bar.html" title="D3 Memory usage with recomputation" desc={`Memory usage with recomputation — <a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=activation_recomputation" target="_blank">from the ultrascale playbook</a>`}/>--- <HtmlEmbed src="d3-neural.html" id="neural-network-mnist-like" title="D3 Interactive neural network (MNIST-like)" desc="Visualize activations and class probabilities (0–9)." align="center" />--- <HtmlEmbed src="d3-pie.html" title="D3 Pie charts by category" align="center" frameless />--- <HtmlEmbed src="filters-quad.html" frameless desc={"Figure 7: Comparison across thresholds for all four filters individually: Formatting, Relevance, Visual Dependency, and Image-Question Correspondence <br/> Credit: "+'<a href="https://huggingface.co/spaces/HuggingFaceM4/FineVision" target="_blank">FineVision</a>'} align="center" />
{/* ---<HtmlEmbed src="d3-comparison.html" title="Image similarity: query vs top-k" desc="Compare a query image to top-k matches. Shows rank and similarity." />---<HtmlEmbed src="d3-area-stacked.html" title="Relative metric shares over steps (by run)" desc="Stacked area of normalized metric contributions across training steps. Data: /data/all_ratings_luis.csv" />---<HtmlEmbed src="d3-boxplot.html" title="Metric distribution across runs (box plots)" desc="Per-run distribution for a selected metric (median, quartiles, whiskers, outliers). Data: /data/all_ratings_luis.csv" />*/}--- <HtmlEmbed src="d3-scatter.html" title="2D projection by category" desc={`Dataset visualization via UMAP <br/> Credit: <a href="https://huggingface.co/spaces/HuggingFaceM4/FineVision" target="_blank">FineVision</a>`} frameless align="center" />---
### Iframes
You can embed external content in your article using **iframes**. For example, **TrackIO**, **Gradio** or even **Github code embeds** can be used this way.
<small className="muted">Github code embed</small><iframe frameborder="0" scrolling="no" style="width:100%; height:292px;" allow="clipboard-write" src="https://emgithub.com/iframe.html?target=https%3A%2F%2Fgithub.com%2Fhuggingface%2Fpicotron%2Fblob%2F1004ae37b87887cde597c9060fb067faa060bafe%2Fsetup.py&style=default&type=code&showBorder=on&showLineNumbers=on"></iframe>
<small className="muted">TrackIO embed</small><div className=""><iframe src="https://trackio-documentation.hf.space/?project=fake-training-750735&metrics=train_loss,train_accuracy&sidebar=hidden&lang=en" width="100%" height="660" frameborder="0"></iframe></div>
<small className="muted">Gradio embed</small><div className=""><iframe src="https://gradio-hello-world.hf.space" width="100%" height="380" frameborder="0"></iframe></div>
<Accordion title="Code example">```mdx<iframe frameborder="0" scrolling="no" style="width:100%; height:292px;" allow="clipboard-write" src="https://emgithub.com/iframe.html?target=https%3A%2F%2Fgithub.com%2Fhuggingface%2Fpicotron%2Fblob%2F1004ae37b87887cde597c9060fb067faa060bafe%2Fsetup.py&style=default&type=code&showBorder=on&showLineNumbers=on"></iframe><iframe src="https://trackio-documentation.hf.space/?project=fake-training-750735&metrics=train_loss,train_accuracy&sidebar=hidden&lang=en" width="100%" height="600" frameborder="0"></iframe><iframe src="https://gradio-hello-world.hf.space" width="100%" height="380" frameborder="0"></iframe>```</Accordion>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import HtmlEmbed from '../../components/HtmlEmbed.astro';
## Vibe coding charts
### Prompt
This page explains how to use the directives to author D3 charts as self‑contained HTML fragments.Using claude code works better.
The goal is to make **responsive**, **accessible**, **interactive** and **dark mode ready** charts.
1. Use this ref a a baseprompt: `app/src/content/embeds/vibe-code-d3-embeds-directives.md`.2. Opt: use an already existing chart as a starting point.3. Ask claude to code the chart. Here's a typical prompt:
```markdownI want you to code a new d3 chart named `yourchart`.I have one CSV file called `yourdata.csv` in the data folder.The csv has the following columns: `x`, `y`, `z`.I want you to code a d3 chart that visualizes the data.```
4. Once the chart created, iterate with littles adjustments to make it better.5. And that's it! 🎉
### Real‑world examples
They can be found in the `app/src/content/embeds` folder and you can also use them as a starting point or examples to vibe code with.
<HtmlEmbed title="d3-benchmark: LLM Benchmark" src="d3-benchmark.html" desc={`Figure 1: Grouped bar chart comparing model scores across benchmarks (MMLU, GSM8K, HellaSwag, TruthfulQA, ARC‑C). Each group is a benchmark; colors encode models; values are accuracy/score (higher is better).`} />--- <HtmlEmbed src="d3-line.html" title="d3-line: Average Ranking of Models" desc='Figure 2: Average Ranking of Models trained with internally deduplicated / merged samples. No clear benefit in merging can be seen with respect to model performance.<br/> Credit: <a href="https://huggingface.co/spaces/HuggingFaceM4/FineVision" target="_blank">FineVision</a>' data="internal_deduplication.csv" config={{ defaultMetric: ['average_rank'] }}/>--- <HtmlEmbed src="d3-neural-network.html" id="neural-network-mnist-like" title="d3-neural-network: MNIST-like Neural Network" desc={`Figure 3: Interactive MNIST-like neural network. Draw a digit on the left canvas; activations propagate through hidden layers (node size/opacity reflect activation). The right side displays class probabilities (0–9) with the top class emphasized.`} />--- <HtmlEmbed src="d3-matrix.html" title="d3-matrix: Baseline and Δ (Improved − Baseline)" frameless desc={`<p> Figure 4: Left: baseline matrix (row-normalized, sequential palette). Right: Δ (Improved − Baseline) in percentage points, using a diverging palette centered at 0 to highlight improvements vs degradations.</p>`} />--- <HtmlEmbed title="d3-line-quad: Comparison across thresholds" src="d3-line-quad.html" desc={"Figure 5: Comparison across thresholds for all four filters individually: Formatting, Relevance, Visual Dependency, and Image-Question Correspondence <br/> Credit: "+'<a href="https://huggingface.co/spaces/HuggingFaceM4/FineVision" target="_blank">FineVision</a>'} />---<HtmlEmbed src="d3-bar.html" title="d3-bar: Memory usage with recomputation" desc={`Figure 6: Memory usage with recomputation.<br/>Credits: <a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=activation_recomputation" target="_blank">Ultrascale playbook</a>`}/>--- <HtmlEmbed src="d3-pie.html" title="d3-pie: Pie charts by category" align="center" frameless desc='Figure 7: Comparison across thresholds for all four filters individually: Formatting, Relevance, Visual Dependency, and Image-Question Correspondence <br/> Credit: <a href="https://huggingface.co/spaces/HuggingFaceM4/FineVision" target="_blank">FineVision</a>' /> ---<HtmlEmbed src="d3-scatter.html" title="d3-scatter: 2D projection by category" desc={`Figure 8: Dataset visualization via UMAP <br/> Credit: <a href="https://huggingface.co/spaces/HuggingFaceM4/FineVision" target="_blank">FineVision</a>`} frameless align="center" />---
90 unmodified lines9192939494959697986 unmodified lines10510610710810911011112 unmodified lines12412512612512612712812913013113213313213413513413613713813914014113814214314414514614714814915015118 unmodified lines1701711721731741751641761771781791801811681691701711721821831841851861871881891904 unmodified lines1951961971831981992002012022032042052062075 unmodified lines2132142152162172181962192202212222232242002012022032042252262272282292302312322334 unmodified lines23823924021524124224324424524624724824925090 unmodified lines // Create SVG const svg = d3.select(container).append('svg') .attr('width', '100%') .style('display', 'block'); .style('display', 'block') .style('cursor', 'crosshair');
const render = () => { const width = container.clientWidth || 800;6 unmodified lines // Subtle stroke color depending on theme const isDark = document.documentElement.getAttribute('data-theme') === 'dark'; const strokeColor = isDark ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.12)'; const glowColor = isDark ? 'rgba(255,255,255,0.35)' : 'rgba(0,0,0,0.25)';
// Group for points (no blend mode for better print/PDF visibility)12 unmodified lines left: '0px', transform: 'translate(-9999px, -9999px)', pointerEvents: 'none', padding: '8px 10px', borderRadius: '8px', padding: '10px 12px', borderRadius: '12px', 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)', boxShadow: '0 8px 32px rgba(0,0,0,.28), 0 2px 8px rgba(0,0,0,.12)', opacity: '0', transition: 'opacity .12s ease' transition: 'opacity .12s ease', backdropFilter: 'saturate(1.12) blur(8px)', zIndex: '20' }); tipInner = document.createElement('div'); tipInner.className = 'd3-tooltip__inner'; tipInner.style.textAlign = 'left'; Object.assign(tipInner.style, { textAlign: 'left', display: 'flex', flexDirection: 'column', gap: '6px', minWidth: '220px' }); tip.appendChild(tipInner); container.appendChild(tip); } else {18 unmodified lines .attr('stroke-width', 0.4) .on('mouseenter', function(ev, i) { d3.select(this).raise() .style('filter', `drop-shadow(0 0 8px ${glowColor})`) .transition().duration(120).ease(d3.easeCubicOut) .attr('stroke', isDark ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.85)') .attr('stroke-width', 1.2); .attr('stroke-width', 1.4) .attr('r', (sizesPx[i] / 2) * 1.25) .attr('fill-opacity', 1); const r = Math.sqrt(((X[i] - cx) / a) ** 2 + ((Y[i] - cy) / b) ** 2); const type = i < lenSpiral ? 'spiral' : 'bulge'; const arm = i < lenSpiral ? (armIndices[i] + 1) : null; tipInner.innerHTML = `<div><strong>${labelOf(i)}</strong></div>` + `<div><strong>Type</strong> ${type}${arm ? ` (arm ${arm})` : ''}</div>` + `<div><strong>Size</strong> ${sizesPx[i].toFixed(1)} px</div>` + `<div><strong>X</strong> ${X[i].toFixed(2)} · <strong>Y</strong> ${Y[i].toFixed(2)}</div>` + `<div><strong>r</strong> ${r.toFixed(3)} · <strong>z</strong> ${Zraw[i].toFixed(3)}</div>`; tipInner.innerHTML = `<div style="font-weight:800;letter-spacing:.1px;"><strong>${labelOf(i)}</strong></div>` + `<div style="font-size:11px;color:var(--muted-color);margin-top:-4px;margin-bottom:2px;letter-spacing:.1px;"><strong>Type</strong> ${type}${arm ? ` (Arm ${arm})` : ''}</div>` + `<div style="padding-top:6px;border-top:1px solid var(--border-color);"><strong>Position</strong> X ${X[i].toFixed(2)} · <strong>Y</strong> ${Y[i].toFixed(2)}</div>` + `<div><strong>Distance</strong> Radius ${r.toFixed(3)} · <strong>Z</strong> ${Zraw[i].toFixed(3)}</div>` + `<div><strong>Size</strong> ${sizesPx[i].toFixed(1)} px</div>`; tip.style.opacity = '1'; }) .on('mousemove', (ev, i) => {4 unmodified lines .on('mouseleave', function() { tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; d3.select(this).attr('stroke', strokeColor).attr('stroke-width', 0.4); d3.select(this) .style('filter', null) .transition().duration(120).ease(d3.easeCubicOut) .attr('stroke', strokeColor) .attr('stroke-width', 0.4) .attr('r', (i2) => sizesPx[i2] / 2) .attr('fill-opacity', 0.9); }), (update) => update .attr('cx', (i) => xScale(X[i]))5 unmodified lines .attr('stroke-width', 0.4) .on('mouseenter', function(ev, i) { d3.select(this).raise() .style('filter', `drop-shadow(0 0 8px ${glowColor})`) .transition().duration(120).ease(d3.easeCubicOut) .attr('stroke', isDark ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.85)') .attr('stroke-width', 1.2); .attr('stroke-width', 1.4) .attr('r', (sizesPx[i] / 2) * 1.25) .attr('fill-opacity', 1); const r = Math.sqrt(((X[i] - cx) / a) ** 2 + ((Y[i] - cy) / b) ** 2); const type = i < lenSpiral ? 'spiral' : 'bulge'; const arm = i < lenSpiral ? (armIndices[i] + 1) : null; tipInner.innerHTML = `<div><strong>${labelOf(i)}</strong></div>` + `<div><strong>Type</strong> ${type}${arm ? ` (arm ${arm})` : ''}</div>` + `<div><strong>Size</strong> ${sizesPx[i].toFixed(1)} px</div>` + `<div><strong>X</strong> ${X[i].toFixed(2)} · <strong>Y</strong> ${Y[i].toFixed(2)}</div>` + `<div><strong>r</strong> ${r.toFixed(3)} · <strong>z</strong> ${Zraw[i].toFixed(3)}</div>`; tipInner.innerHTML = `<div style="font-weight:800;letter-spacing:.1px;"><strong>${labelOf(i)}</strong></div>` + `<div style="font-size:11px;color:var(--muted-color);margin-top:-4px;margin-bottom:2px;letter-spacing:.1px;"><strong>Type</strong> ${type}${arm ? ` (Arm ${arm})` : ''}</div>` + `<div style="padding-top:6px;border-top:1px solid var(--border-color);"><strong>Position</strong> X ${X[i].toFixed(2)} · <strong>Y</strong> ${Y[i].toFixed(2)}</div>` + `<div><strong>Distance</strong> Radius ${r.toFixed(3)} · <strong>Z</strong> ${Zraw[i].toFixed(3)}</div>` + `<div><strong>Size</strong> ${sizesPx[i].toFixed(1)} px</div>`; tip.style.opacity = '1'; }) .on('mousemove', (ev, i) => {4 unmodified lines .on('mouseleave', function() { tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; d3.select(this).attr('stroke', strokeColor).attr('stroke-width', 0.4); d3.select(this) .style('filter', null) .transition().duration(120).ease(d3.easeCubicOut) .attr('stroke', strokeColor) .attr('stroke-width', 0.4) .attr('r', (i2) => sizesPx[i2] / 2) .attr('fill-opacity', 0.9); }) ); };1<div> <div id="3e4ed4fe-23b4-4ec1-810e-20d6fce0209b" class="plotly-graph-div" style="height:100%; width:100%;"></div> <script type="text/javascript"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById("3e4ed4fe-23b4-4ec1-810e-20d6fce0209b")) { Plotly.newPlot( "3e4ed4fe-23b4-4ec1-810e-20d6fce0209b", [{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(78, 165, 183)"},"name":"parameters","showlegend":true,"visible":true,"x":["1024","2048","4096","8192"],"y":[4.0,4.0,4.0,4.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(227, 138, 66)"},"name":"gradients","showlegend":true,"visible":true,"x":["1024","2048","4096","8192"],"y":[4.0,4.0,4.0,4.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(232, 137, 171)"},"name":"optimizer","showlegend":true,"visible":true,"x":["1024","2048","4096","8192"],"y":[8.0,8.0,8.0,8.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(206, 192, 250)"},"name":"activations","showlegend":true,"visible":true,"x":["1024","2048","4096","8192"],"y":[3.6,14.4,57.6,230.4],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(78, 165, 183)"},"name":"parameters","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[13.3,13.3,13.3,13.3],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(227, 138, 66)"},"name":"gradients","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[13.3,13.3,13.3,13.3],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(232, 137, 171)"},"name":"optimizer","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[26.6,26.6,26.6,26.6],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(206, 192, 250)"},"name":"activations","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[9.3,37.2,148.8,595.2],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(78, 165, 183)"},"name":"parameters","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[26.0,26.0,26.0,26.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(227, 138, 66)"},"name":"gradients","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[26.0,26.0,26.0,26.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(232, 137, 171)"},"name":"optimizer","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[52.0,52.0,52.0,52.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(206, 192, 250)"},"name":"activations","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[46.2,184.8,739.2,2956.8],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(78, 165, 183)"},"name":"parameters","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[244.0,244.0,244.0,244.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(227, 138, 66)"},"name":"gradients","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[244.0,244.0,244.0,244.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(232, 137, 171)"},"name":"optimizer","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[488.0,488.0,488.0,488.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(206, 192, 250)"},"name":"activations","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[145.7,582.8,2331.2,9324.8],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(78, 165, 183)"},"name":"parameters","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[1520.0,1520.0,1520.0,1520.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(227, 138, 66)"},"name":"gradients","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[1520.0,1520.0,1520.0,1520.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(232, 137, 171)"},"name":"optimizer","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[3040.0,3040.0,3040.0,3040.0],"type":"bar"},{"hovertemplate":"Seq len=%{x}\u003cbr\u003eMem=%{y:.1f}GB\u003cbr\u003e%{data.name}\u003cextra\u003e\u003c\u002fextra\u003e","marker":{"color":"rgb(206, 192, 250)"},"name":"activations","showlegend":true,"visible":false,"x":["1024","2048","4096","8192"],"y":[1519.9,6079.6,24318.4,97273.6],"type":"bar"}], {"template":{"data":{"histogram2dcontour":[{"type":"histogram2dcontour","colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]}],"choropleth":[{"type":"choropleth","colorbar":{"outlinewidth":0,"ticks":""}}],"histogram2d":[{"type":"histogram2d","colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]}],"heatmap":[{"type":"heatmap","colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]}],"heatmapgl":[{"type":"heatmapgl","colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]}],"contourcarpet":[{"type":"contourcarpet","colorbar":{"outlinewidth":0,"ticks":""}}],"contour":[{"type":"contour","colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]}],"surface":[{"type":"surface","colorbar":{"outlinewidth":0,"ticks":""},"colorscale":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]]}],"mesh3d":[{"type":"mesh3d","colorbar":{"outlinewidth":0,"ticks":""}}],"scatter":[{"fillpattern":{"fillmode":"overlay","size":10,"solidity":0.2},"type":"scatter"}],"parcoords":[{"type":"parcoords","line":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"scatterpolargl":[{"type":"scatterpolargl","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"bar":[{"error_x":{"color":"#2a3f5f"},"error_y":{"color":"#2a3f5f"},"marker":{"line":{"color":"#E5ECF6","width":0.5},"pattern":{"fillmode":"overlay","size":10,"solidity":0.2}},"type":"bar"}],"scattergeo":[{"type":"scattergeo","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"scatterpolar":[{"type":"scatterpolar","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"histogram":[{"marker":{"pattern":{"fillmode":"overlay","size":10,"solidity":0.2}},"type":"histogram"}],"scattergl":[{"type":"scattergl","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"scatter3d":[{"type":"scatter3d","line":{"colorbar":{"outlinewidth":0,"ticks":""}},"marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"scattermapbox":[{"type":"scattermapbox","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"scatterternary":[{"type":"scatterternary","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"scattercarpet":[{"type":"scattercarpet","marker":{"colorbar":{"outlinewidth":0,"ticks":""}}}],"carpet":[{"aaxis":{"endlinecolor":"#2a3f5f","gridcolor":"white","linecolor":"white","minorgridcolor":"white","startlinecolor":"#2a3f5f"},"baxis":{"endlinecolor":"#2a3f5f","gridcolor":"white","linecolor":"white","minorgridcolor":"white","startlinecolor":"#2a3f5f"},"type":"carpet"}],"table":[{"cells":{"fill":{"color":"#EBF0F8"},"line":{"color":"white"}},"header":{"fill":{"color":"#C8D4E3"},"line":{"color":"white"}},"type":"table"}],"barpolar":[{"marker":{"line":{"color":"#E5ECF6","width":0.5},"pattern":{"fillmode":"overlay","size":10,"solidity":0.2}},"type":"barpolar"}],"pie":[{"automargin":true,"type":"pie"}]},"layout":{"autotypenumbers":"strict","colorway":["#636efa","#EF553B","#00cc96","#ab63fa","#FFA15A","#19d3f3","#FF6692","#B6E880","#FF97FF","#FECB52"],"font":{"color":"#2a3f5f"},"hovermode":"closest","hoverlabel":{"align":"left"},"paper_bgcolor":"white","plot_bgcolor":"#E5ECF6","polar":{"bgcolor":"#E5ECF6","angularaxis":{"gridcolor":"white","linecolor":"white","ticks":""},"radialaxis":{"gridcolor":"white","linecolor":"white","ticks":""}},"ternary":{"bgcolor":"#E5ECF6","aaxis":{"gridcolor":"white","linecolor":"white","ticks":""},"baxis":{"gridcolor":"white","linecolor":"white","ticks":""},"caxis":{"gridcolor":"white","linecolor":"white","ticks":""}},"coloraxis":{"colorbar":{"outlinewidth":0,"ticks":""}},"colorscale":{"sequential":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"sequentialminus":[[0.0,"#0d0887"],[0.1111111111111111,"#46039f"],[0.2222222222222222,"#7201a8"],[0.3333333333333333,"#9c179e"],[0.4444444444444444,"#bd3786"],[0.5555555555555556,"#d8576b"],[0.6666666666666666,"#ed7953"],[0.7777777777777778,"#fb9f3a"],[0.8888888888888888,"#fdca26"],[1.0,"#f0f921"]],"diverging":[[0,"#8e0152"],[0.1,"#c51b7d"],[0.2,"#de77ae"],[0.3,"#f1b6da"],[0.4,"#fde0ef"],[0.5,"#f7f7f7"],[0.6,"#e6f5d0"],[0.7,"#b8e186"],[0.8,"#7fbc41"],[0.9,"#4d9221"],[1,"#276419"]]},"xaxis":{"gridcolor":"white","linecolor":"white","ticks":"","title":{"standoff":15},"zerolinecolor":"white","automargin":true,"zerolinewidth":2},"yaxis":{"gridcolor":"white","linecolor":"white","ticks":"","title":{"standoff":15},"zerolinecolor":"white","automargin":true,"zerolinewidth":2},"scene":{"xaxis":{"backgroundcolor":"#E5ECF6","gridcolor":"white","linecolor":"white","showbackground":true,"ticks":"","zerolinecolor":"white","gridwidth":2},"yaxis":{"backgroundcolor":"#E5ECF6","gridcolor":"white","linecolor":"white","showbackground":true,"ticks":"","zerolinecolor":"white","gridwidth":2},"zaxis":{"backgroundcolor":"#E5ECF6","gridcolor":"white","linecolor":"white","showbackground":true,"ticks":"","zerolinecolor":"white","gridwidth":2}},"shapedefaults":{"line":{"color":"#2a3f5f"}},"annotationdefaults":{"arrowcolor":"#2a3f5f","arrowhead":0,"arrowwidth":1},"geo":{"bgcolor":"white","landcolor":"#E5ECF6","subunitcolor":"white","showland":true,"showlakes":true,"lakecolor":"white"},"title":{"x":0.05},"mapbox":{"style":"light"}}},"margin":{"l":40,"r":28,"t":20,"b":40},"legend":{"orientation":"h","yanchor":"bottom","y":1.02,"xanchor":"left","x":0},"xaxis":{"title":{"text":"Sequence Length"},"fixedrange":true},"yaxis":{"title":{"text":"Memory (GB)"},"fixedrange":true},"barmode":"stack","autosize":true,"paper_bgcolor":"rgba(0,0,0,0)","plot_bgcolor":"rgba(0,0,0,0)","hovermode":"x unified","updatemenus":[{"active":0,"buttons":[{"args":[{"visible":[true,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false]},{"yaxis":{"range":[0,258.72]}}],"label":"1B","method":"update"},{"args":[{"visible":[false,false,false,false,true,true,true,true,false,false,false,false,false,false,false,false,false,false,false,false]},{"yaxis":{"range":[0,680.8200000000002]}}],"label":"3B","method":"update"},{"args":[{"visible":[false,false,false,false,false,false,false,false,true,true,true,true,false,false,false,false,false,false,false,false]},{"yaxis":{"range":[0,3213.84]}}],"label":"8B","method":"update"},{"args":[{"visible":[false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,false,false,false,false]},{"yaxis":{"range":[0,10815.84]}}],"label":"70B","method":"update"},{"args":[{"visible":[false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true]},{"yaxis":{"range":[0,108521.28000000001]}}],"label":"405B","method":"update"}],"showactive":true,"type":"dropdown","x":1.03,"xanchor":"left","y":0.6,"yanchor":"top"},{"active":0,"buttons":[{"args":[{"y":[[4.0,4.0,4.0,4.0],[4.0,4.0,4.0,4.0],[8.0,8.0,8.0,8.0],[3.6,14.4,57.6,230.4],[13.3,13.3,13.3,13.3],[13.3,13.3,13.3,13.3],[26.6,26.6,26.6,26.6],[9.3,37.2,148.8,595.2],[26.0,26.0,26.0,26.0],[26.0,26.0,26.0,26.0],[52.0,52.0,52.0,52.0],[46.2,184.8,739.2,2956.8],[244.0,244.0,244.0,244.0],[244.0,244.0,244.0,244.0],[488.0,488.0,488.0,488.0],[145.7,582.8,2331.2,9324.8],[1520.0,1520.0,1520.0,1520.0],[1520.0,1520.0,1520.0,1520.0],[3040.0,3040.0,3040.0,3040.0],[1519.9,6079.6,24318.4,97273.6]]},{"yaxis":{"range":[0,108521.28000000001]}}],"label":"None","method":"update"},{"args":[{"y":[[4.0,4.0,4.0,4.0],[4.0,4.0,4.0,4.0],[8.0,8.0,8.0,8.0],[0.9,3.6,14.4,57.6],[13.3,13.3,13.3,13.3],[13.3,13.3,13.3,13.3],[26.6,26.6,26.6,26.6],[2.325,9.3,37.2,148.8],[26.0,26.0,26.0,26.0],[26.0,26.0,26.0,26.0],[52.0,52.0,52.0,52.0],[11.55,46.2,184.8,739.2],[244.0,244.0,244.0,244.0],[244.0,244.0,244.0,244.0],[488.0,488.0,488.0,488.0],[36.425,145.7,582.8,2331.2],[1520.0,1520.0,1520.0,1520.0],[1520.0,1520.0,1520.0,1520.0],[3040.0,3040.0,3040.0,3040.0],[379.975,1519.9,6079.6,24318.4]]},{"yaxis":{"range":[0,31918.320000000003]}}],"label":"selective","method":"update"},{"args":[{"y":[[4.0,4.0,4.0,4.0],[4.0,4.0,4.0,4.0],[8.0,8.0,8.0,8.0],[0.225,0.9,3.6,14.4],[13.3,13.3,13.3,13.3],[13.3,13.3,13.3,13.3],[26.6,26.6,26.6,26.6],[0.58125,2.325,9.3,37.2],[26.0,26.0,26.0,26.0],[26.0,26.0,26.0,26.0],[52.0,52.0,52.0,52.0],[2.8875,11.55,46.2,184.8],[244.0,244.0,244.0,244.0],[244.0,244.0,244.0,244.0],[488.0,488.0,488.0,488.0],[9.10625,36.425,145.7,582.8],[1520.0,1520.0,1520.0,1520.0],[1520.0,1520.0,1520.0,1520.0],[3040.0,3040.0,3040.0,3040.0],[94.99375,379.975,1519.9,6079.6]]},{"yaxis":{"range":[0,12767.580000000002]}}],"label":"full","method":"update"}],"showactive":true,"type":"dropdown","x":1.03,"xanchor":"left","y":0.4,"yanchor":"top"}],"annotations":[{"showarrow":false,"text":"Model Size:","x":1.03,"xanchor":"left","xref":"paper","y":0.6,"yanchor":"bottom","yref":"paper"},{"showarrow":false,"text":"Recomputation:","x":1.03,"xanchor":"left","xref":"paper","y":0.4,"yanchor":"bottom","yref":"paper"}]}, {"displayModeBar": false, "responsive": true, "scrollZoom": false} ) }; </script> </div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220<div class="d3-area-stacked" style="width:100%;margin:10px 0;"></div><style> .d3-area-stacked .controls { margin-top: 12px; display: flex; gap: 16px; align-items: center; flex-wrap: wrap; } .d3-area-stacked .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; } .d3-area-stacked .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-area-stacked .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-area-stacked .controls select:hover { border-color: var(--primary-color); } .d3-area-stacked .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; } .d3-area-stacked .legend { font-size: 12px; line-height: 1.35; 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-area-stacked'))){ const cs = Array.from(document.querySelectorAll('.d3-area-stacked')).filter(el => !(el.dataset && el.dataset.mounted==='true')); container = cs[cs.length-1] || null; } if (!container) return; if (container.dataset){ if (container.dataset.mounted==='true') return; container.dataset.mounted='true'; }
// 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; }
// Controls const controls = document.createElement('div'); controls.className='controls'; const labelRun = document.createElement('label'); labelRun.textContent='Run'; const selRun = document.createElement('select'); labelRun.appendChild(selRun); const labelSmooth = document.createElement('label'); labelSmooth.textContent='Smoothing'; const selSmooth = document.createElement('select'); ['none','monotone','basis'].forEach((s)=>{ const o=document.createElement('option'); o.value=s; o.textContent=s; selSmooth.appendChild(o); }); labelSmooth.appendChild(selSmooth);
// SVG const svg = d3.select(container).append('svg').attr('width','100%').style('display','block'); 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 gLegend = gRoot.append('foreignObject').attr('class','legend');
// State & scales let width=800,height=360; const margin={top:16,right:28,bottom:56,left:64}; const x=d3.scaleLinear(); const y=d3.scaleLinear(); const color=d3.scaleOrdinal().range(['var(--primary-color)','rgb(78, 165, 183)','rgb(227, 138, 66)','rgb(206, 192, 250)']);
// Data (real): relative contributions of selected metrics over steps for a run const metricsToUse = ['ai2d_exact_match','docvqa_val_anls','textvqa_val_exact_match','chartqa_relaxed_overall']; let categories = metricsToUse.slice(); let allRows = []; let currentRun = null; let stacked = [];
async function fetchFirstAvailable(paths){ for (const p of paths){ try { const res = await fetch(p, { cache:'no-cache' }); if (res.ok) return await res.text(); } catch(e){} } throw new Error('Failed to load area data'); }
function computeStackForRun(runName){ const rows = allRows.filter(r=>r.run===runName && metricsToUse.includes(r.metric)); const byStep = d3.rollup(rows, v=>{ const m = new Map(); v.forEach(r=>{ m.set(r.metric, +r.value); }); const obj = {}; metricsToUse.forEach(k=>{ obj[k] = m.get(k) ?? 0; }); // Normalize to shares const sum = metricsToUse.reduce((acc,k)=>acc + Math.max(0, obj[k]), 0) || 1; metricsToUse.forEach(k=>{ obj[k] = Math.max(0, obj[k]) / sum; }); return obj; }, r=>+r.step); const steps = Array.from(byStep.keys()).sort((a,b)=>a-b); const series = categories.map(cat => steps.map(step => ({ x: step, y: byStep.get(step)[cat] }))); stacked = d3.stack().keys(d3.range(categories.length)).value((d, key)=>d[key].y)(d3.transpose(series)); return steps; }
function renderLegend(innerWidth){ const legendWidth=160, legendHeight=84; gLegend.attr('x', innerWidth-legendWidth).attr('y', 0).attr('width', legendWidth).attr('height', legendHeight); const root = gLegend.selectAll('div').data([0]).join('xhtml:div'); root.html(` <div style="display:flex;flex-direction:column;gap:6px;align-items:flex-end;"> ${categories.map((c,i)=>`<div style=\"display:flex;align-items:center;gap:8px;\"><span style=\"width:18px;height:10px;background:${color(c)};border-radius:2px;display:inline-block\"></span><span>${c}</span></div>`).join('')} </div> `); }
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(260, Math.round(width/3)); 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})`);
const yMax = stacked.length ? d3.max(stacked[stacked.length-1], (d) => d[1]) : 1; const xMin = stacked.length ? d3.min(stacked[0], d=>d.data[0].x) : 0; const xMax = stacked.length ? d3.max(stacked[0], d=>d.data[d.data.length-1].x) : 1; x.domain([xMin, xMax]).range([0, innerWidth]).nice(); y.domain([0, yMax]).range([innerHeight, 0]).nice();
// Grid gGrid.selectAll('*').remove(); gGrid.selectAll('line.grid-y').data(y.ticks(5)).join('line') .attr('class','grid-y').attr('x1',0).attr('x2',innerWidth).attr('y1',d=>y(d)).attr('y2',d=>y(d)) .attr('stroke', gridColor).attr('stroke-width',1).attr('shape-rendering','crispEdges');
// Axes gAxes.selectAll('*').remove(); gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x).ticks(6)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); gAxes.append('g').call(d3.axisLeft(y).ticks(5)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); 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(${-48},${innerHeight/2}) rotate(-90)`).style('font-size','12px').style('fill', tickColor).text('Value');
renderLegend(innerWidth); return { innerWidth, innerHeight }; }
function draw(){ const { innerWidth, innerHeight } = updateScales();
const curve = selSmooth.value==='monotone' ? d3.curveMonotoneX : selSmooth.value==='basis' ? d3.curveBasis : d3.curveLinear; const area = d3.area().curve(curve).x((d,i)=>x(d.data[i].x)).y0(d=>y(d[0])).y1(d=>y(d[1]));
const layers = gAreas.selectAll('path.layer').data(stacked); layers.enter().append('path').attr('class','layer') .attr('fill', (d,i)=>color(categories[i])) .attr('opacity', 0.9) .on('mouseenter', function(ev, d){ const i = stacked.indexOf(d); d3.select(this).attr('opacity', 1); tipInner.innerHTML = `<div><strong>${categories[i]}</strong></div>`; tip.style.opacity = '1'; }) .on('mousemove', function(ev){ const [mx,my]=d3.pointer(ev, container); const ox=12, oy=12; tip.style.transform = `translate(${Math.round(mx+ox)}px, ${Math.round(my+oy)}px)`; }) .on('mouseleave', function(){ d3.select(this).attr('opacity', 0.9); tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; }) .merge(layers) .transition().duration(180) .attr('d', d=>area(d)); layers.exit().remove(); }
container.appendChild(controls); controls.appendChild(labelRun); controls.appendChild(labelSmooth); selSmooth.addEventListener('change', ()=>draw());
(async () => { try { const csvText = await fetchFirstAvailable([ '/data/all_ratings_luis.csv', '/data/against_baselines.csv', '/data/ss_vs_s1.csv', './assets/data/all_ratings_luis.csv', '../assets/data/all_ratings_luis.csv', '/data/all_ratings_luis.csv' ]); allRows = d3.csvParse(csvText, d=>({ run: d.run, step: +d.step, metric: d.metric, value: +d.value })); const runs = Array.from(new Set(allRows.map(r=>r.run))).filter(Boolean); runs.forEach(r=>{ const o=document.createElement('option'); o.value=r; o.textContent=r; selRun.appendChild(o); }); currentRun = runs[0]; selRun.value = currentRun; selRun.addEventListener('change', (e)=>{ currentRun = e.target.value; draw(); }); color.domain(categories); computeStackForRun(currentRun); draw(); } catch (e) { const pre = document.createElement('pre'); pre.style.color = 'crimson'; pre.textContent = 'Failed to load area data.'; container.appendChild(pre); } })();
const rerender = () => { draw(); }; if (window.ResizeObserver) { const ro = new ResizeObserver(()=>rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); } };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
112343456789101112131415161718192092122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656615 unmodified lines8283843132333435368586878822 unmodified lines11111211311411511667117118119120701211227273123124125126127128129130131132133134135136137138139781401411429 unmodified lines152153154941551561571581591601611621631641651661671681691701711721 unmodified line1741751761021031041051061071081091101771781791801811821831841851861871881891901911921931941951961971141151161171181981992004 unmodified lines2052062071292082092102111331342122132142151371382162172181402192202212222232242251472262272282292 unmodified lines23223323423523623723823928 unmodified lines2682692701901912712722732742752762772782792802812822832842852862872881952892902912922932942952962972982993003013023031973043053065 unmodified lines312313314209210315316317318319<div class="d3-bar" style="width:100%;margin:10px 0;"></div><div class="d3-bar" ></div><style> .d3-bar .controls { margin-top: 12px; display: flex; gap: 16px; align-items: center; flex-wrap: wrap; } .d3-bar .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; } /* Theme-driven axis/tick/grid variables */ .d3-bar { --axis-color: rgba(0,0,0,0.25); --tick-color: rgba(0,0,0,0.55); --grid-color: rgba(0,0,0,0.05); } [data-theme="dark"] .d3-bar { --axis-color: rgba(255,255,255,0.25); --tick-color: rgba(255,255,255,0.70); --grid-color: rgba(255,255,255,0.08); } .d3-bar .controls { margin-top: 0; display: flex; gap: 16px; align-items: center; justify-content: flex-end; flex-wrap: wrap; } .d3-bar .controls .control-group { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; } .d3-bar .controls label { font-size: 12px; color: var(--text-color); font-weight: 700; } .d3-bar .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-bar .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-bar .controls select:hover { border-color: var(--primary-color); } .d3-bar .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; } .d3-bar .legend { font-size: 12px; line-height: 1.35; color: var(--text-color); } /* Header (legend + controls) placed after chart */ .d3-bar .chart-header { display: flex; align-items: flex-start; justify-content: flex-start; gap: 12px; margin: 8px 0 0 0; flex-wrap: wrap; } .d3-bar .legend-bottom { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; font-size: 12px; color: var(--text-color); } .d3-bar .legend-bottom .legend-title { font-size: 12px; font-weight: 700; color: var(--text-color); } .d3-bar .legend-bottom .items { display: flex; flex-wrap: wrap; gap: 8px 14px; } .d3-bar .legend-bottom .item { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } .d3-bar .legend-bottom .swatch { width: 14px; height: 14px; border-radius: 3px; border: 1px solid var(--border-color); display: inline-block; } .d3-bar.hovering .legend-bottom .item.ghost { opacity: .35; } .d3-bar.hovering .bars path.ghost { opacity: .35; } .d3-bar .axis-label { fill: var(--text-color); font-size: 12px; font-weight: 700; } /* Apply axis/tick/grid purely via CSS */ .d3-bar .axes path, .d3-bar .axes line { stroke: var(--axis-color); } .d3-bar .axes text { fill: var(--tick-color); } .d3-bar .grid line { stroke: var(--grid-color); } /* Tooltip improvements */ .d3-bar .d3-tooltip { z-index: var(--z-tooltip); backdrop-filter: saturate(1.12) blur(8px); } /* Hover/transition styling for bars and legend */ .d3-bar .bars path.bar { transition: opacity .12s ease, stroke .12s ease, stroke-width .12s ease; } .d3-bar .bars path.bar.highlight { stroke: none; stroke-width: 0; } .d3-bar.hovering .bars path.ghost { opacity: .25; } .d3-bar .legend-bottom .item.hovered { color: inherit; } .d3-bar .legend-bottom .item.hovered .swatch { border-color: var(--border-color); } .d3-bar .d3-tooltip .swatch { width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-color); display: inline-block; margin-right: 6px; vertical-align: -2px; } /* Chart card wrapper */ .d3-bar .chart-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; } /* Layout adjustments to give controls more space */ .d3-bar .chart-header { padding-left: 8px; padding-right: 8px; gap: 20px; } .d3-bar .controls { justify-content: flex-start; min-width: 320px; } .d3-bar .controls .control-group { min-width: 150px; } .d3-bar .controls select { font-size: 13px; min-width: 160px; }</style><script> (() => {15 unmodified lines // Data, matching bar.py const seqLabels = ["1024","2048","4096","8192"]; const seqScale = [1,2,4,8]; const components = [ { key: 'parameters', color: 'rgb(78, 165, 183)' }, { key: 'gradients', color: 'rgb(227, 138, 66)' }, { key: 'optimizer', color: 'var(--primary-color)' }, { key: 'activations', color: 'rgb(206, 192, 250)' }, ]; const componentKeys = ['parameters','gradients','optimizer','activations']; const modelSizes = ["1B","3B","8B","70B","405B"]; const paramsMem = { "1B":4.0, "3B":13.3, "8B":26.0, "70B":244.0, "405B":1520.0 }; const actCoeff = { "1B":3.6, "3B":9.3, "8B":46.2, "70B":145.7, "405B":1519.9 };22 unmodified lines // Controls const controls = document.createElement('div'); controls.className = 'controls'; const groupSize = document.createElement('div'); groupSize.className = 'control-group'; const labelSize = document.createElement('label'); labelSize.textContent = 'Model Size'; const selSize = document.createElement('select'); modelSizes.forEach((s) => { const o = document.createElement('option'); o.value = s; o.textContent = s; selSize.appendChild(o); }); labelSize.appendChild(selSize); groupSize.appendChild(labelSize); groupSize.appendChild(selSize); const groupRecomp = document.createElement('div'); groupRecomp.className = 'control-group'; const labelRecomp = document.createElement('label'); labelRecomp.textContent = 'Recomputation'; const selRecomp = document.createElement('select'); recomputeModes.forEach((m) => { const o = document.createElement('option'); o.value = m; o.textContent = m; selRecomp.appendChild(o); }); labelRecomp.appendChild(selRecomp); groupRecomp.appendChild(labelRecomp); groupRecomp.appendChild(selRecomp);
// SVG scaffolding const svg = d3.select(container).append('svg').attr('width','100%').style('display','block'); // Header (legend + controls) to be placed after chart const header = document.createElement('div'); header.className = 'chart-header'; const legendBottom = document.createElement('div'); legendBottom.className = 'legend-bottom'; const legendTitle = document.createElement('div'); legendTitle.className = 'legend-title'; legendTitle.textContent = 'Legend'; const legendItems = document.createElement('div'); legendItems.className = 'items'; legendBottom.appendChild(legendTitle); legendBottom.appendChild(legendItems); header.appendChild(legendBottom); header.appendChild(controls); // SVG scaffolding inside a card wrapper const card = document.createElement('div'); card.className = 'chart-card'; container.appendChild(card); // Place header after the chart card container.appendChild(header); const svg = d3.select(card).append('svg').attr('width','100%').style('display','block'); const gRoot = svg.append('g'); const gGrid = gRoot.append('g').attr('class','grid'); const gAxes = gRoot.append('g').attr('class','axes'); const gBars = gRoot.append('g').attr('class','bars'); const gLegend = gRoot.append('foreignObject').attr('class','legend');
// Tooltip container.style.position = container.style.position || 'relative';9 unmodified lines let width=800, height=360; const margin = { top: 16, right: 28, bottom: 56, left: 64 }; const x0 = d3.scaleBand().paddingInner(0.25).paddingOuter(0.1); // groups (seq) const y = d3.scaleLinear(); const colorOf = (key) => components.find((c)=>c.key===key).color; function getCategoricalColors(count){ try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') { return window.ColorPalettes.getColors('categorical', count); } } catch(_) {} const primary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#E889AB'; const tableau = (window.d3 && window.d3.schemeTableau10) ? window.d3.schemeTableau10 : ['#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f','#edc948','#b07aa1','#ff9da7','#9c755f','#bab0ab']; const pool = [primary, ...tableau]; const arr = []; for (let i=0;i<count;i++){ arr.push(pool[i % pool.length]); } return arr; } const palette = getCategoricalColors(componentKeys.length); const colorMap = new Map(componentKeys.map((k,i)=>[k, palette[i]])); const colorOf = (key) => colorMap.get(key) || 'var(--primary-color)';
function yMax(sizeKey, mode){ const s = Y[mode][sizeKey];1 unmodified line return max*1.05; }
function renderLegend(innerWidth, innerHeight){ const legendWidth = 160, legendHeight = 84; gLegend.attr('x', 15).attr('y', -3).attr('width', legendWidth).attr('height', legendHeight); const root = gLegend.selectAll('div').data([0]).join('xhtml:div'); root.html(` <div style="display:flex;flex-direction:column;gap:6px;"> ${components.map(c => `<div style="display:flex;align-items:center;gap:8px;"><span style="width:18px;height:10px;background:${c.color};border-radius:2px;display:inline-block"></span><span>${c.key}</span></div>`).join('')} </div> `); function renderLegend(){ legendItems.innerHTML = componentKeys.map((key, i) => { const color = palette[i]; return `<span class="item" data-key="${key}"><span class=\"swatch\" style=\"background:${color}\"></span><span>${key}</span></span>`; }).join(''); legendItems.querySelectorAll('.item').forEach((el) => { el.addEventListener('mouseenter', () => { const k = el.getAttribute('data-key'); if (!k) return; container.classList.add('hovering'); gBars.selectAll('path.bar').classed('ghost', d => d && d.key !== k); legendItems.querySelectorAll('.item').forEach(it => it.classList.toggle('ghost', it.getAttribute('data-key') !== k)); }); el.addEventListener('mouseleave', () => { container.classList.remove('hovering'); gBars.selectAll('path.bar').classed('ghost', false); legendItems.querySelectorAll('.item').forEach(it => it.classList.remove('ghost')); }); }); }
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(260, Math.round(width/3)); 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})`);
4 unmodified lines gGrid.selectAll('*').remove(); gGrid.selectAll('line').data(y.ticks(6)).join('line') .attr('x1', 0).attr('x2', innerWidth).attr('y1', (d)=>y(d)).attr('y2', (d)=>y(d)) .attr('stroke', gridColor).attr('stroke-width', 1).attr('shape-rendering', 'crispEdges'); .attr('stroke', 'var(--grid-color)').attr('stroke-width', 1).attr('shape-rendering', 'crispEdges');
// Axes gAxes.selectAll('*').remove(); gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x0)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); gAxes.append('g').call(d3.axisLeft(y).ticks(6).tickFormat(d3.format('~f'))).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x0)).call((g)=>{ g.selectAll('path, line').attr('stroke', 'var(--axis-color)'); g.selectAll('text').attr('fill', 'var(--tick-color)').style('font-size','12px'); }); gAxes.append('g').call(d3.axisLeft(y).ticks(6).tickFormat(d3.format('~f'))).call((g)=>{ g.selectAll('path, line').attr('stroke', 'var(--axis-color)'); g.selectAll('text').attr('fill', 'var(--tick-color)').style('font-size','12px'); });
// Axis labels 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('Sequence Length'); gAxes.append('text').attr('class','axis-label axis-label--y').attr('text-anchor','middle').attr('transform', `translate(${-52},${innerHeight/2}) rotate(-90)`).style('font-size','12px').style('fill', tickColor).text('Memory (GB)'); gAxes.append('text').attr('class','axis-label axis-label--x').attr('x', innerWidth/2).attr('y', innerHeight + 44).attr('text-anchor','middle').text('Sequence Length'); gAxes.append('text').attr('class','axis-label axis-label--y').attr('text-anchor','middle').attr('transform', `translate(${-52},${innerHeight/2}) rotate(-90)`).text('Memory (GB)');
renderLegend(innerWidth, innerHeight); renderLegend();
return { innerWidth, innerHeight }; }
function drawBars(){ const stacks = Y[currentMode][currentSize]; const series = components.map((c)=>({ key: c.key, color: c.color, values: stacks[c.key] })); const series = componentKeys.map((key, i)=>({ key, color: palette[i], values: stacks[key] })); // Stack values const stacked = seqLabels.map((label, i) => { let acc = 0; const items = [];2 unmodified lines items.push({ key: s.key, color: s.color, i, y0, y1, xLabel: label, value: s.values[i], isBottom: idx === 0, isTop: idx === series.length - 1 }); acc = y1; }); const total = acc; items.forEach(it => { it.total = total; }); return { label, items }; });
28 unmodified lines .attr('d', (d)=> roundedPath(0, y(d.y1), bandWidth, Math.max(0.5, y(d.y0) - y(d.y1)), d.isTop, d.isBottom)) .attr('fill', (d)=>d.color) .on('mouseenter', function(ev, d){ d3.select(this).attr('stroke', 'rgba(0,0,0,0.85)').attr('stroke-width', 1); tipInner.innerHTML = `<div><strong>${d.key}</strong></div><div><strong>Seq</strong> ${d.xLabel}</div><div><strong>Mem</strong> ${d.value.toFixed(1)} GB</div>`; container.classList.add('hovering'); gBars.selectAll('path.bar').classed('ghost', (dd) => !(dd && dd.key === d.key)); const pct = d.total > 0 ? (d.value / d.total * 100) : 0; tipInner.innerHTML = ` <div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;"> <span class="swatch" style="background:${d.color}"></span> <strong>${d.key}</strong> </div> <div><strong>Seq</strong> ${d.xLabel}</div> <div><strong>Mem</strong> ${d.value.toFixed(1)} GB <span style="opacity:.7">(${pct.toFixed(0)}%)</span></div> <div style="opacity:.7"><strong>Total</strong> ${d.total.toFixed(1)} GB</div> `; tip.style.opacity = '1'; const li = legendItems.querySelector(`.item[data-key="${d.key}"]`); if (li) li.classList.add('hovered'); legendItems.querySelectorAll('.item').forEach(it => it.classList.toggle('ghost', it.getAttribute('data-key') !== d.key)); }) .on('mousemove', function(ev, d){ const [mx, my] = d3.pointer(ev, container); const offsetX = 12, offsetY = 12; tip.style.transform = `translate(${Math.round(mx+offsetX)}px, ${Math.round(my+offsetY)}px)`; const [mx, my] = d3.pointer(ev, container); const offsetX = 12, offsetY = 12; const maxX = (container.clientWidth || 0) - (tip.offsetWidth + 6); const maxY = (container.clientHeight || 0) - (tip.offsetHeight + 6); const tx = Math.max(0, Math.min(mx + offsetX, maxX)); const ty = Math.max(0, Math.min(my + offsetY, maxY)); tip.style.transform = `translate(${Math.round(tx)}px, ${Math.round(ty)}px)`; }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; container.classList.remove('hovering'); gBars.selectAll('path.bar').classed('ghost', false).classed('highlight', false); legendItems.querySelectorAll('.item').forEach(it => { it.classList.remove('hovered'); it.classList.remove('ghost'); }); }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(this).attr('stroke','none'); }) .merge(bars) .transition().duration(200) .attr('d', (d)=> roundedPath(0, y(d.y1), bandWidth, Math.max(0.5, y(d.y0) - y(d.y1)), d.isTop, d.isBottom))5 unmodified lines
// Boot update(); container.appendChild(controls); controls.appendChild(labelSize); controls.appendChild(labelRecomp); // controls already appended to footer; populate control groups controls.appendChild(groupSize); controls.appendChild(groupRecomp); selSize.addEventListener('change', (e)=>{ currentSize = e.target.value; update(); }); selRecomp.addEventListener('change', (e)=>{ currentMode = e.target.value; update(); });
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444<div class="d3-benchmark"></div><style> .d3-benchmark { position: relative; --axis-color: rgba(0,0,0,0.25); --tick-color: rgba(0,0,0,0.55); --grid-color: rgba(0,0,0,0.05); } [data-theme="dark"] .d3-benchmark { --axis-color: rgba(255,255,255,0.25); --tick-color: rgba(255,255,255,0.70); --grid-color: rgba(255,255,255,0.08); } .d3-benchmark .controls { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; } .d3-benchmark .controls label { font-size: 12px; color: var(--muted-color); } .d3-benchmark .controls select { appearance: none; -webkit-appearance: none; -moz-appearance: none; border: 1px solid var(--border-color); border-radius: 8px; padding: 6px 28px 6px 10px; background-color: var(--surface-bg); color: var(--text-color); font-size: 13px; line-height: 1.2; background-image: url("data:image/svg+xml,%3Csvg width='12' height='8' viewBox='0 0 12 8' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1.41 1.59L6 6.17l4.59-4.58L12 3 6 9 0 3z' fill='%23999'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 8px center; } .d3-benchmark .controls select:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 2px; } .d3-benchmark .legend { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin: 8px 0 0 0; } .d3-benchmark .legend .legend-title { font-size: 12px; font-weight: 700; color: var(--text-color); } .d3-benchmark .legend .items { display: flex; flex-wrap: wrap; gap: 8px 14px; } .d3-benchmark .legend .item { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted-color); cursor: pointer; } .d3-benchmark .legend .swatch { width: 14px; height: 14px; border-radius: 3px; border: 1px solid var(--border-color); } .d3-benchmark .ghost { opacity: .25; } .d3-benchmark .d3-tooltip { position: absolute; top: 0px; left: 0px; transform: translate(-9999px, -9999px); pointer-events: none; padding: 8px 10px; border-radius: 8px; font-size: 12px; line-height: 1.35; 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 .12s ease; text-align: left; } .d3-benchmark .chart-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; }</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-benchmark'))){ const cs = Array.from(document.querySelectorAll('.d3-benchmark')).filter(el => !(el.dataset && el.dataset.mounted==='true')); container = cs[cs.length-1] || null; } if (!container) return; if (container.dataset) { if (container.dataset.mounted==='true') return; container.dataset.mounted='true'; }
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'; tipInner = document.createElement('div'); tipInner.className = 'd3-tooltip__inner'; tip.appendChild(tipInner); container.appendChild(tip); } else { tipInner = tip.querySelector('.d3-tooltip__inner') || tip; }
// header below chart const header = document.createElement('div'); header.className = 'chart-header';
const makeLegend = (series, colorBySeries) => { let legend = header.querySelector('.legend'); if (!legend) { legend = document.createElement('div'); legend.className = 'legend'; header.appendChild(legend); } // Ensure title let title = legend.querySelector('.legend-title'); if (!title) { title = document.createElement('div'); title.className = 'legend-title'; title.textContent = 'Legend'; legend.appendChild(title); } // Ensure items container let items = legend.querySelector('.items'); if (!items) { items = document.createElement('div'); items.className = 'items'; legend.appendChild(items); } items.innerHTML = ''; series.forEach(name => { const item = document.createElement('div'); item.className = 'item'; const sw = document.createElement('span'); sw.className = 'swatch'; sw.style.background = colorBySeries(name); const txt = document.createElement('span'); txt.textContent = name; item.appendChild(sw); item.appendChild(txt); items.appendChild(item); item.addEventListener('mouseenter', () => { state.highlightModel = name; updateHighlight(); }); item.addEventListener('mouseleave', () => { state.highlightModel = null; updateHighlight(); }); }); };
// SVG scaffolding inside a card wrapper, then header appended after const card = document.createElement('div'); card.className = 'chart-card'; container.appendChild(card); container.appendChild(header); const svg = d3.select(card).append('svg').attr('width','100%').style('display','block'); const gRoot = svg.append('g');
// No controls (fixed scale mode)
// Public-first data loading with inline fallback const fetchFirstAvailable = async (paths) => { for (const p of paths) { try { const res = await fetch(p, { cache:'no-cache' }); if (!res.ok) throw new Error('HTTP '+res.status); const text = await res.text(); // Try JSON first; if CSV, parse with d3.csvParse try { return JSON.parse(text); } catch(e) {} if (window.d3 && d3.csvParse) { return d3.csvParse(text); } } catch (e) { /* keep trying */ } } return null; };
// Inline fallback dataset (scores in % where applicable) const inlineData = [ { benchmark:'MMLU', model:'GPT-4o', score: 88 }, { benchmark:'MMLU', model:'Llama 3 70B', score: 80 }, { benchmark:'MMLU', model:'Mixtral 8x7B',score: 73 }, { benchmark:'MMLU', model:'Gemma 2 27B', score: 76 }, { benchmark:'GSM8K', model:'GPT-4o', score: 94 }, { benchmark:'GSM8K', model:'Llama 3 70B', score: 83 }, { benchmark:'GSM8K', model:'Mixtral 8x7B',score: 79 }, { benchmark:'GSM8K', model:'Gemma 2 27B', score: 81 }, { benchmark:'HellaSwag', model:'GPT-4o', score: 95 }, { benchmark:'HellaSwag', model:'Llama 3 70B', score: 89 }, { benchmark:'HellaSwag', model:'Mixtral 8x7B',score: 86 }, { benchmark:'HellaSwag', model:'Gemma 2 27B', score: 87 }, { benchmark:'TruthfulQA', model:'GPT-4o', score: 64 }, { benchmark:'TruthfulQA', model:'Llama 3 70B', score: 56 }, { benchmark:'TruthfulQA', model:'Mixtral 8x7B',score: 51 }, { benchmark:'TruthfulQA', model:'Gemma 2 27B', score: 53 }, { benchmark:'ARC-C', model:'GPT-4o', score: 79 }, { benchmark:'ARC-C', model:'Llama 3 70B', score: 72 }, { benchmark:'ARC-C', model:'Mixtral 8x7B',score: 68 }, { benchmark:'ARC-C', model:'Gemma 2 27B', score: 70 } ];
const state = { data: inlineData, colorsByModel: null, highlightModel: null, };
const margin = { top: 12, right: 28, bottom: 24, left: 56 }; let width = 800, height = 360; const x0 = d3.scaleBand().paddingInner(0.2).paddingOuter(0.05); // group: benchmark const x1 = d3.scaleBand().padding(0.12); // series: model per benchmark const y = d3.scaleLinear(); const xAxis = d3.axisBottom(x0).tickSizeOuter(0); const yAxis = d3.axisLeft(y).ticks(6).tickSizeOuter(0); const yTopPadding = 2; // avoid bars touching top at max
function getPrimaryColor(){ try { if (window.ColorPalettes && typeof window.ColorPalettes.getPrimary === 'function') return window.ColorPalettes.getPrimary(); } catch(e) {} return getComputedStyle(document.documentElement).getPropertyValue('--primary-color') || '#6D4AFF'; } function getCategoricalColors(n){ try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') return window.ColorPalettes.getColors('categorical', n); } catch(e) {} // Fallback: generate hues around the primary color (simple fallback) const base = getPrimaryColor(); const colors = []; for (let i=0;i<n;i++) { const hue = Math.round((360/n)*i); colors.push(`hsl(${hue}, 60%, 55%)`); } return colors; }
function computeSeriesColors(models){ const palette = getCategoricalColors(models.length); const map = new Map(models.map((m, i) => [m, palette[i % palette.length]])); return (model) => map.get(model) || getPrimaryColor(); }
function getModels(data){ return Array.from(new Set(data.map(d => d.model))); } function getBenchmarks(data){ return Array.from(new Set(data.map(d => d.benchmark))); }
function updateSize(){ width = container.clientWidth || 800; height = Math.max(240, Math.round(width / 3.4)); svg.attr('width', width).attr('height', height); gRoot.attr('transform', `translate(${margin.left},${margin.top})`); return { innerWidth: width - margin.left - margin.right, innerHeight: height - margin.top - margin.bottom }; }
function showTip(html, x, y){ tip.style.transform = `translate(${x + 12}px, ${y + 12}px)`; tip.style.opacity = '1'; const inner = tip.querySelector('.d3-tooltip__inner') || tip; inner.innerHTML = html; } function hideTip(){ tip.style.opacity = '0'; tip.style.transform = 'translate(-9999px, -9999px)'; }
function updateHighlight(){ const model = state.highlightModel; const bars = gRoot.selectAll('rect.bar'); const labels = gRoot.selectAll('text.value'); if (model) { bars.classed('ghost', d => d.model !== model); labels.classed('ghost', d => d.model !== model); const items = container.querySelectorAll('.legend .item'); items.forEach((el) => { const name = el.textContent.trim(); if (name !== model) el.classList.add('ghost'); else el.classList.remove('ghost'); }); } else { bars.classed('ghost', false); labels.classed('ghost', false); container.querySelectorAll('.legend .item').forEach(el => el.classList.remove('ghost')); } }
function render(){ const { innerWidth, innerHeight } = updateSize(); const models = getModels(state.data); if (!state.colorsByModel) state.colorsByModel = computeSeriesColors(models); makeLegend(models, state.colorsByModel);
x0.domain(getBenchmarks(state.data)).range([0, innerWidth]); x1.domain(models).range([0, x0.bandwidth()]);
const yMaxRaw = 100; const yMax = yMaxRaw + yTopPadding; y.domain([0, yMax]).range([innerHeight, 0]).nice();
// Axes (standardized colors) gRoot .selectAll('.axis-x') .data([0]) .join('g') .attr('class','axis-x') .attr('transform',`translate(0,${innerHeight})`) .call(xAxis) .call(g => { g.selectAll('path, line').attr('stroke', 'var(--axis-color)'); g.selectAll('text').attr('fill', 'var(--tick-color)').style('font-size','12px'); }); gRoot .selectAll('.axis-y') .data([0]) .join('g') .attr('class','axis-y') .call(yAxis) .call(g => { g.selectAll('path, line').attr('stroke', 'var(--axis-color)'); g.selectAll('text').attr('fill', 'var(--tick-color)').style('font-size','12px'); });
// Gridlines (y) standardized color gRoot .selectAll('.grid-y') .data([0]) .join('g') .attr('class','grid-y') .call(d3.axisLeft(y).ticks(6).tickSize(-innerWidth).tickFormat('')) .call(g => g.select('.domain').remove()) .call(g => g.selectAll('.tick line').attr('stroke','var(--grid-color)').attr('stroke-opacity',1)) .call(g => g.selectAll('.tick').filter((d, i, nodes) => i === nodes.length - 1).select('line').attr('stroke-opacity', 0));
// Groups per benchmark const groups = gRoot.selectAll('.group').data(getBenchmarks(state.data), d => d); const groupsEnter = groups.enter().append('g').attr('class','group'); groupsEnter.merge(groups).attr('transform', d => `translate(${x0(d)},0)`); groups.exit().remove();
// Bars per model const nested = d3.group(state.data, d => d.benchmark); groupsEnter.each(function(bench){ d3.select(this).selectAll('rect.bar').data([]).join('rect'); }); const allGroups = gRoot.selectAll('.group'); allGroups.each(function(bench){ const dataForBench = nested.get(bench) || []; const bars = d3.select(this).selectAll('rect.bar').data(models.map(m => ({ bench, model:m, score:(dataForBench.find(dd=>dd.model===m)||{score:0}).score })) , d => d.model); bars.join( enter => enter.append('rect') .attr('class','bar') .attr('x', d => x1(d.model)) .attr('y', innerHeight) .attr('width', x1.bandwidth()) .attr('height', 0) .attr('fill', d => state.colorsByModel(d.model)) .on('mouseenter', (event, d) => { state.highlightModel = d.model; updateHighlight(); }) .on('mousemove', (event, d) => { const [mx, my] = d3.pointer(event, container); showTip(`<strong>${d.model}</strong><br/>${d.bench}: <strong>${d.score}</strong>`, mx, my); }) .on('mouseleave', () => { hideTip(); state.highlightModel = null; updateHighlight(); }) .transition().duration(160) .attr('y', d => y(d.score)) .attr('height', d => Math.max(0, innerHeight - y(d.score))), update => update .on('mouseenter', (event, d) => { state.highlightModel = d.model; updateHighlight(); }) .on('mousemove', (event, d) => { const [mx, my] = d3.pointer(event, container); showTip(`<strong>${d.model}</strong><br/>${d.bench}: <strong>${d.score}</strong>`, mx, my); }) .on('mouseleave', () => { hideTip(); state.highlightModel = null; updateHighlight(); }) .transition().duration(160) .attr('x', d => x1(d.model)) .attr('y', d => y(d.score)) .attr('width', x1.bandwidth()) .attr('height', d => Math.max(0, innerHeight - y(d.score))) .attr('fill', d => state.colorsByModel(d.model)), exit => exit.transition().duration(120).attr('y', innerHeight).attr('height', 0).remove() );
// Value labels centered above bars (small, darker) const labels = d3.select(this).selectAll('text.value').data(models.map(m => ({ bench, model:m, score:(dataForBench.find(dd=>dd.model===m)||{score:0}).score })) , d => d.model); labels.join( enter => enter.append('text') .attr('class','value') .attr('x', d => x1(d.model) + x1.bandwidth()/2) .attr('y', d => y(d.score) - 4) .attr('text-anchor','middle') .attr('fill','var(--text-color)') .attr('opacity',0.9) .attr('font-size',10) .text(d => d.score), update => update .transition().duration(160) .attr('x', d => x1(d.model) + x1.bandwidth()/2) .attr('y', d => y(d.score) - 4) .text(d => d.score), exit => exit.remove() ); });
// Axis labels gRoot.selectAll('.y-label').data([0]).join('text').attr('class','y-label') .attr('transform', `rotate(-90)`) .attr('x', -innerHeight / 2) .attr('y', -margin.left + 24) .attr('text-anchor','middle') .attr('fill','var(--text-color)') .attr('font-size',12) .attr('font-weight',700) .text('score'); }
// Initial render + resize handling render(); const rerender = () => render(); if (window.ResizeObserver) { const ro = new ResizeObserver(() => rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); }
// Attempt to load external data (public-first). Expect either JSON array with {benchmark, model, score} (async () => { const maybe = await fetchFirstAvailable([ '/data/llm_benchmarks.json', './assets/data/llm_benchmarks.json', '../assets/data/llm_benchmarks.json' ]); if (Array.isArray(maybe) && maybe.length && maybe[0].benchmark && maybe[0].model && (typeof maybe[0].score === 'number')) { state.data = maybe; state.colorsByModel = null; // recompute in case of different model set render(); } else if (maybe && maybe.columns) { // CSV parsed via d3.csvParse -> convert fields const parsed = maybe.map(r => ({ benchmark: r.benchmark, model: r.model, score: +r.score })); if (parsed.length) { state.data = parsed; state.colorsByModel = null; render(); } } })().catch(() => { // Graceful failure: inline fallback already rendered }); };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251<div class="d3-boxplot" style="width:100%;margin:10px 0;"></div><style> .d3-boxplot .controls { margin-top: 12px; display: flex; gap: 16px; align-items: center; flex-wrap: wrap; } .d3-boxplot .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; } .d3-boxplot .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-boxplot .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-boxplot .controls select:hover { border-color: var(--primary-color); } .d3-boxplot .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; } .d3-boxplot .legend { font-size: 12px; line-height: 1.35; 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-boxplot'))){ const cs = Array.from(document.querySelectorAll('.d3-boxplot')).filter(el => !(el.dataset && el.dataset.mounted==='true')); container = cs[cs.length-1] || null; } if (!container) return; if (container.dataset){ if (container.dataset.mounted==='true') return; container.dataset.mounted='true'; }
// 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; }
// Controls const controls = document.createElement('div'); controls.className='controls'; const labelMetric = document.createElement('label'); labelMetric.textContent='Metric'; const selMetric = document.createElement('select'); labelMetric.appendChild(selMetric);
// SVG const svg = d3.select(container).append('svg').attr('width','100%').style('display','block'); const gRoot = svg.append('g'); const gGrid = gRoot.append('g').attr('class','grid'); const gAxes = gRoot.append('g').attr('class','axes'); const gBoxes = gRoot.append('g').attr('class','boxes');
// State & scales let width=800,height=360; const margin={top:16,right:28,bottom:56,left:64}; const x=d3.scaleBand().padding(0.4); const y=d3.scaleLinear(); const color=d3.scaleOrdinal().range(['var(--primary-color)','rgb(78, 165, 183)','rgb(227, 138, 66)','rgb(206, 192, 250)']);
// Data (real): distribution of a chosen metric across runs let allRows = []; let groups = []; let currentMetric = null; let stats = [];
async function fetchFirstAvailable(paths){ for (const p of paths){ try { const res = await fetch(p, { cache:'no-cache' }); if (res.ok) return await res.text(); } catch(e){} } throw new Error('Failed to load boxplot data'); }
function computeStatsForMetric(metric){ const byRun = d3.rollup(allRows.filter(r=>r.metric===metric), v=> v.map(r=>+r.value).filter(Number.isFinite), r=>r.run); groups = Array.from(byRun.keys()); const result = groups.map((g)=>{ const data = (byRun.get(g) || []).slice().sort((a,b)=>a-b); if (!data.length) return { key:g, q1:NaN, med:NaN, q3:NaN, min:NaN, max:NaN, outliers:[] }; const q1 = d3.quantile(data, 0.25); const med = d3.quantile(data, 0.5); const q3 = d3.quantile(data, 0.75); const iqr = q3 - q1; const lo = q1 - 1.5*iqr; const hi = q3 + 1.5*iqr; const min = d3.min(data.filter(v=>v>=lo)); const max = d3.max(data.filter(v=>v<=hi)); const outliers = data.filter(v=>v<lo || v>hi); return { key:g, q1, med, q3, iqr, min, max, outliers }; }); return result; }
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(260, Math.round(width/3)); 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})`);
x.domain(groups).range([0, innerWidth]); const yMin = Math.floor(d3.min(stats, d=>d.min ?? 0))-0; const yMax = Math.ceil(d3.max(stats, d=>d.max ?? 1))+0; y.domain([yMin, yMax]).range([innerHeight,0]).nice();
// Grid gGrid.selectAll('*').remove(); gGrid.selectAll('line.grid-y').data(y.ticks(6)).join('line') .attr('class','grid-y').attr('x1',0).attr('x2',innerWidth).attr('y1',d=>y(d)).attr('y2',d=>y(d)) .attr('stroke', gridColor).attr('stroke-width',1).attr('shape-rendering','crispEdges');
// Axes gAxes.selectAll('*').remove(); gAxes.append('g').attr('transform', `translate(0,${innerHeight})`).call(d3.axisBottom(x)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); gAxes.append('g').call(d3.axisLeft(y).ticks(6)).call((g)=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','12px'); }); 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('Group'); gAxes.append('text').attr('class','axis-label axis-label--y').attr('text-anchor','middle').attr('transform', `translate(${-48},${innerHeight/2}) rotate(-90)`).style('font-size','12px').style('fill', tickColor).text('Value');
return { innerWidth, innerHeight }; }
function draw(){ const { innerWidth, innerHeight } = updateScales(); const bw = Math.max(10, x.bandwidth());
// Boxes const groupsSel = gBoxes.selectAll('g.bp').data(stats, d=>d.key); const gEnter = groupsSel.enter().append('g').attr('class','bp').attr('transform', d=>`translate(${x(d.key)},0)`); const merged = gEnter.merge(groupsSel).attr('transform', d=>`translate(${x(d.key)},0)`); groupsSel.exit().remove();
// Box rect (Q1-Q3) const box = merged.selectAll('rect.box').data(d=>[d]); box.enter().append('rect').attr('class','box') .attr('x', 0).attr('width', bw) .attr('y', d=>y(d.q3)).attr('height', d=>Math.max(0.5, y(d.q1) - y(d.q3))) .attr('fill','var(--surface-bg)') .attr('stroke', 'var(--primary-color)') .attr('rx', 4).attr('ry', 4) .merge(box) .transition().duration(180) .attr('y', d=>y(d.q3)).attr('height', d=>Math.max(0.5, y(d.q1) - y(d.q3))); box.exit().remove();
// Median line const med = merged.selectAll('line.med').data(d=>[d]); med.enter().append('line').attr('class','med') .attr('x1', 0).attr('x2', bw) .attr('y1', d=>y(d.med)).attr('y2', d=>y(d.med)) .attr('stroke','var(--primary-color)').attr('stroke-width',2) .merge(med) .transition().duration(180) .attr('y1', d=>y(d.med)).attr('y2', d=>y(d.med)); med.exit().remove();
// Whiskers const whisker = merged.selectAll('line.whisk').data(d=>[d]); whisker.enter().append('line').attr('class','whisk') .attr('x1', bw/2).attr('x2', bw/2) .attr('y1', d=>y(d.min)).attr('y2', d=>y(d.max)) .attr('stroke','var(--border-color)') .merge(whisker) .transition().duration(180) .attr('y1', d=>y(d.min)).attr('y2', d=>y(d.max)); whisker.exit().remove();
// Whisker caps const caps = merged.selectAll('g.caps').data(d=>[d]); const capsEnter = caps.enter().append('g').attr('class','caps'); capsEnter.append('line').attr('class','cap cap--min').attr('x1',0).attr('x2',bw).attr('y1',d=>y(d.min)).attr('y2',d=>y(d.min)).attr('stroke','var(--border-color)'); capsEnter.append('line').attr('class','cap cap--max').attr('x1',0).attr('x2',bw).attr('y1',d=>y(d.max)).attr('y2',d=>y(d.max)).attr('stroke','var(--border-color)'); caps.merge(capsEnter).select('.cap--min').transition().duration(180).attr('y1',d=>y(d.min)).attr('y2',d=>y(d.min)); caps.merge(capsEnter).select('.cap--max').transition().duration(180).attr('y1',d=>y(d.max)).attr('y2',d=>y(d.max)); caps.exit().remove();
// Outliers const outs = merged.selectAll('circle.out').data(d=>d.outliers.map(v=>({key:d.key, v}))); outs.enter().append('circle').attr('class','out') .attr('cx', bw/2).attr('cy', d=>y(d.v)).attr('r', 2.5) .attr('fill', 'var(--primary-color)') .on('mouseenter', function(ev, d){ tipInner.innerHTML = `<div><strong>${d.key}</strong> outlier: ${d.v.toFixed(2)}</div>`; tip.style.opacity='1'; d3.select(this).attr('r',3.2); }) .on('mousemove', function(ev){ const [mx,my]=d3.pointer(ev, container); const ox=12, oy=12; tip.style.transform = `translate(${Math.round(mx+ox)}px, ${Math.round(my+oy)}px)`; }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(this).attr('r',2.5); }) .merge(outs) .transition().duration(180) .attr('cy', d=>y(d.v)); outs.exit().remove(); }
container.appendChild(controls); controls.appendChild(labelMetric);
(async () => { try { const csvText = await fetchFirstAvailable([ '/data/all_ratings_luis.csv', '/data/against_baselines.csv', '/data/ss_vs_s1.csv', './assets/data/all_ratings_luis.csv', '../assets/data/all_ratings_luis.csv' ]); allRows = d3.csvParse(csvText, d=>({ run: d.run, step: +d.step, metric: d.metric, value: +d.value })); const metrics = Array.from(new Set(allRows.map(r=>r.metric))).filter(Boolean).slice(0, 20); metrics.forEach(m=>{ const o=document.createElement('option'); o.value=m; o.textContent=m; selMetric.appendChild(o); }); currentMetric = metrics.includes('textvqa_val_exact_match') ? 'textvqa_val_exact_match' : metrics[0]; selMetric.value = currentMetric; selMetric.addEventListener('change', (e)=>{ currentMetric = e.target.value; stats = computeStatsForMetric(currentMetric); draw(); }); stats = computeStatsForMetric(currentMetric); draw(); } catch (e) { const pre = document.createElement('pre'); pre.style.color = 'crimson'; pre.textContent = 'Failed to load boxplot data.'; container.appendChild(pre); } })();
const rerender = () => { draw(); }; if (window.ResizeObserver) { const ro = new ResizeObserver(()=>rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); } };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149<div class="image-comparison" style="width:100%;margin:10px 0;"></div><style> .image-comparison { position: relative; } .image-comparison .controls { display:flex; align-items:center; gap:16px; justify-content:center; flex-wrap:wrap; margin:14px 0; } .image-comparison .controls label { font-size:14px; color: var(--text-color); display:flex; align-items:center; justify-content:center; gap:10px; font-weight:600; } .image-comparison .controls select { font-size: 14px; padding: 8px 32px 8px 12px; border: 1px solid var(--border-color); border-radius: 10px; 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; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; box-shadow: 0 1px 2px rgba(0,0,0,.04); } [data-theme="dark"] .image-comparison .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"); } .image-comparison .controls select:hover { border-color: var(--primary-color); } .image-comparison .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; }
/* Responsive: empiler label et select proprement sur petits écrans */ @media (max-width: 520px) { .image-comparison .controls label { flex-direction: column; gap: 6px; } }
.image-comparison .grid { display:grid; grid-template-columns: repeat(4, 1fr); gap: 12px; width:100%; align-items: start; } /* Large → 4 colonnes; Medium → 2 colonnes; Mobile → 1 colonne */ @media (max-width: 1100px) { .image-comparison .grid { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 680px) { .image-comparison .grid { grid-template-columns: 1fr; } }
.image-comparison .card { position: relative; border:1px solid var(--border-color); border-radius:10px; overflow:hidden; background: var(--surface-bg); display:flex; flex-direction:column; } .image-comparison .card .media { position: relative; width:100%; height: 200px; background: var(--surface-2, var(--surface-bg)); display:block; } .image-comparison .card .media img { width:100%; height:100%; object-fit: contain; display:block; } .image-comparison .badge { position:absolute; top:8px; left:8px; font-size:11px; padding:3px 6px; border-radius:6px; background: var(--surface-bg); color: var(--text-color); border:1px solid var(--border-color); } .image-comparison .meta { padding:8px 10px; border-top:1px solid var(--border-color); font-size:12px; display:flex; height: 55px; align-items:start; justify-content:space-between; gap:8px; } .image-comparison .meta .label { color: var(--muted-color); } .image-comparison .meta .value { font-weight:600; }</style><script> (() => { const THIS_SCRIPT = document.currentScript; const bootstrap = () => { const scriptEl = THIS_SCRIPT; const host = scriptEl && scriptEl.parentElement; let container = null; if (host && host.querySelector) { container = host.querySelector('.image-comparison'); } if (!container) { let sib = scriptEl && scriptEl.previousElementSibling; while (sib && !(sib.classList && sib.classList.contains('image-comparison'))) { sib = sib.previousElementSibling; } container = sib || document.querySelector('.image-comparison'); } if (!container) return; if (container.dataset && container.dataset.mounted === 'true') return; if (container.dataset) container.dataset.mounted = 'true';
// Known filenames in /public/data/comparison const FILES = { '1': { query: 'id_1_query.png', 1: 'id_1_rank_1_sim_1.000.png', 2: 'id_1_rank_2_sim_0.165.png', 3: 'id_1_rank_3_sim_0.143.png' }, '2': { query: 'id_2_query.png', 1: 'id_2_rank_1_sim_1.000.png', 2: 'id_2_rank_2_sim_0.978.png', 3: 'id_2_rank_3_sim_0.975.png' }, '3': { query: 'id_3_query.png', 1: 'id_3_rank_1_sim_0.936.png', 2: 'id_3_rank_2_sim_0.686.png', 3: 'id_3_rank_3_sim_0.676.png' }, };
// Images served from [domain]/public/data/comparison/*.png → path is /data/comparison/ const CANDIDATE_BASES = [ '/data/comparison/' ];
const resolveBase = (candidates, filename) => new Promise((resolve) => { let idx = 0; const tryNext = () => { if (idx >= candidates.length) return resolve(candidates[0]); const img = new Image(); img.onload = () => resolve(candidates[idx]); img.onerror = () => { idx += 1; tryNext(); }; img.src = candidates[idx] + filename; }; tryNext(); });
// Controls const controls = document.createElement('div'); controls.className = 'controls'; const label = document.createElement('label'); label.textContent = 'Example'; const select = document.createElement('select'); const EXAMPLE_LABELS = { '1': 'Photo', '2': 'Chart', '3': 'Drawing' }; ['1','2','3'].forEach((id)=>{ const o=document.createElement('option'); o.value=id; o.textContent=EXAMPLE_LABELS[id]; select.appendChild(o); }); label.appendChild(select); controls.appendChild(label); container.appendChild(controls);
// Grid const grid = document.createElement('div'); grid.className = 'grid'; container.appendChild(grid);
let basePath = CANDIDATE_BASES[0];
const parseInfo = (filename) => { const rankMatch = filename.match(/rank_(\d+)/i); const rank = rankMatch ? rankMatch[1] : ''; const simMatch = filename.match(/sim_([0-9.]+)/i); const sim = simMatch ? simMatch[1] : ''; return { rank, sim }; };
const formatSim = (val) => { if (val == null || val === '') return '—'; return String(val).replace(/\.$/, ''); };
const render = (id) => { const files = FILES[id]; if (!files) return; const ordered = [files.query, files[1], files[2], files[3]]; // query, then matches 1, 2, 3 grid.innerHTML = ''; ordered.forEach((fname, idx) => { const { sim } = parseInfo(fname); const isQuery = idx === 0; const card = document.createElement('div'); card.className = 'card'; const media = document.createElement('div'); media.className = 'media'; const img = document.createElement('img'); img.alt = `example ${id} ${isQuery ? 'query' : `match ${idx}`}`; img.loading = 'lazy'; img.src = basePath + fname; media.appendChild(img); const meta = document.createElement('div'); meta.className = 'meta'; if (isQuery) { const label = document.createElement('span'); label.className = 'value'; label.textContent = 'Query'; meta.appendChild(label); } else { const content = document.createElement('span'); content.innerHTML = `<span class="value">Match ${idx}</span><br><span class="label">Similarity: ${formatSim(sim)}</span>`; meta.appendChild(content); } card.appendChild(media); card.appendChild(meta); grid.appendChild(card); }); };
(async () => { // Resolve a working base then initial render basePath = await resolveBase(CANDIDATE_BASES, FILES['1'].query); render('1'); })();
select.addEventListener('change', () => render(select.value)); };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', bootstrap, { once: true }); } else { bootstrap(); } })();</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516<div class="d3-confusion-matrix" ></div><style> .d3-confusion-matrix { position: relative; } .d3-confusion-matrix .panels { display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 4px; } .d3-confusion-matrix .panel { flex: 1 1 320px; min-width: 280px; } .d3-confusion-matrix .panel__title { color: var(--text-color); font-size: 12px; line-height: 1.35; margin: 0 0 6px 0; font-weight: 600; } .d3-confusion-matrix .axis-label { fill: var(--text-color); font-size: 11px; font-weight: 700; } .d3-confusion-matrix .cell-border { stroke: var(--border-color); stroke-width: 1px; fill: none; } .d3-confusion-matrix .cell-text { fill: var(--muted-color); font-size: 11px; pointer-events: none; } .d3-confusion-matrix .chart-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; }</style><script> (() => { // Load D3 from CDN once 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-confusion-matrix'))){ const cs = Array.from(document.querySelectorAll('.d3-confusion-matrix')).filter(el => !(el.dataset && el.dataset.mounted === 'true')); container = cs[cs.length - 1] || null; } if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Tooltip (HTML, single instance inside container) 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; }
// Panels container (two side-by-side matrices) const panels = document.createElement('div'); panels.className = 'panels'; const panelA = document.createElement('div'); panelA.className = 'panel'; const titleA = document.createElement('div'); titleA.className = 'panel__title'; titleA.textContent = 'Baseline (row-normalized %)'; panelA.appendChild(titleA); const mountA = document.createElement('div'); panelA.appendChild(mountA); const panelB = document.createElement('div'); panelB.className = 'panel'; const titleB = document.createElement('div'); titleB.className = 'panel__title'; titleB.textContent = 'Delta (Improved − Baseline, pp)'; panelB.appendChild(titleB); const mountB = document.createElement('div'); panelB.appendChild(mountB); panels.appendChild(panelA); panels.appendChild(panelB); container.appendChild(panels);
// SVG scaffolding const cardA = document.createElement('div'); cardA.className = 'chart-card'; mountA.appendChild(cardA); const svgA = d3.select(cardA).append('svg').attr('width', '100%').style('display', 'block'); const gRootA = svgA.append('g'); const gCellsA = gRootA.append('g'); const gAxesA = gRootA.append('g'); const cardB = document.createElement('div'); cardB.className = 'chart-card'; mountB.appendChild(cardB); const svgB = d3.select(cardB).append('svg').attr('width', '100%').style('display', 'block'); const gRootB = svgB.append('g'); const gCellsB = gRootB.append('g'); const gAxesB = gRootB.append('g');
// Demo data (two distinct 10x10 confusion matrices: Baseline vs Improved) // Rows: actual, Columns: predicted const classes = ['0','1','2','3','4','5','6','7','8','9']; const matrixA = [ [90, 2, 1, 0, 0, 0, 1, 0, 5, 1], [ 3, 85, 5, 1, 0, 1, 2, 1, 1, 1], [ 1, 6, 70, 10, 4, 4, 1, 1, 1, 2], [ 0, 1, 8, 65, 10, 10, 2, 1, 1, 2], [ 0, 0, 2, 6, 83, 3, 1, 1, 3, 1], [ 0, 1, 2, 12, 4, 70, 5, 2, 2, 2], [ 1, 2, 1, 0, 1, 2, 88, 1, 3, 1], [ 0, 1, 1, 1, 1, 1, 2, 90, 1, 2], [ 6, 2, 2, 4, 6, 3, 3, 2, 70, 2], [ 1, 1, 1, 1, 2, 1, 1, 2, 1, 89] ]; const matrixB = [ [94, 1, 0, 0, 0, 0, 1, 0, 3, 1], [ 2, 90, 3, 1, 0, 0, 1, 1, 1, 1], [ 1, 4, 78, 7, 3, 3, 1, 1, 1, 1], [ 0, 1, 5, 74, 7, 8, 1, 1, 1, 2], [ 0, 0, 1, 4, 88, 2, 1, 1, 2, 1], [ 0, 1, 1, 9, 3, 78, 3, 1, 2, 2], [ 1, 1, 1, 0, 1, 1, 91, 1, 2, 1], [ 0, 1, 1, 1, 1, 1, 1, 92, 1, 1], [ 4, 1, 1, 3, 4, 2, 2, 2, 79, 2], [ 1, 1, 1, 1, 2, 1, 1, 1, 1, 90] ];
// Colors: sequential palette via window.ColorPalettes with graceful fallback const getSequentialColors = (count) => { try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') { return window.ColorPalettes.getColors('sequential', count); } } catch (_) {} // Fallback: generate a monochrome scale using the primary color with varying opacity const arr = []; for (let i = 0; i < count; i++) arr.push('var(--primary-color)'); return arr; };
const palette = getSequentialColors(13); const getDivergingColors = (count) => { try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') { return window.ColorPalettes.getColors('diverging', count); } } catch (_) {} const steps = Math.max(3, count|0); const arr = []; for (let i = 0; i < steps; i++) { const t = i / (steps - 1); const pct = Math.round(t * 100); arr.push(`color-mix(in srgb, #D64545 ${100-pct}%, #3A7BD5 ${pct}%)`); } return arr; };
let width = 800; let height = 480; const margin = { top: 36, right: 24, bottom: 26, left: 56 };
function updateSize() { const isDark = document.documentElement.getAttribute('data-theme') === 'dark'; width = container.clientWidth || 800; const gap = 16; // matches CSS .panels gap const minPanel = 320; const nCols = (width >= (minPanel * 2 + gap)) ? 2 : 1; const panelWidth = nCols === 2 ? Math.max(minPanel, Math.floor((width - gap) / 2)) : Math.max(minPanel, width); const base = Math.max(minPanel, Math.round(panelWidth * 0.92)); height = base; // Responsive SVG: width 100%, height auto, preserve aspect via viewBox svgA .attr('viewBox', `0 0 ${panelWidth} ${height}`) .attr('preserveAspectRatio', 'xMidYMid meet') .style('width', '100%') .style('height', 'auto'); svgB .attr('viewBox', `0 0 ${panelWidth} ${height}`) .attr('preserveAspectRatio', 'xMidYMid meet') .style('width', '100%') .style('height', 'auto'); gRootA.attr('transform', `translate(${margin.left},${margin.top})`); gRootB.attr('transform', `translate(${margin.left},${margin.top})`); const innerWidth = panelWidth - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; return { innerWidth, innerHeight, isDark }; }
function computeValues(normalization, matrix) { const n = classes.length; const totalsByRow = matrix.map(row => row.reduce((a, b) => a + b, 0)); const flat = []; let minV = Infinity, maxV = -Infinity; for (let r = 0; r < n; r++) { for (let c = 0; c < n; c++) { const count = matrix[r][c]; const value = normalization === 'row' ? (totalsByRow[r] ? count / totalsByRow[r] : 0) : count; if (value < minV) minV = value; if (value > maxV) maxV = value; flat.push({ r, c, count, value }); } } return { data: flat, minV, maxV }; }
function getColorScale(values, minV, maxV) { // If ColorPalettes is available, use quantiles to enhance visual variation across the distribution const hasPalette = !(palette.length === 0); if (hasPalette && (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function')) { const scale = d3.scaleQuantile().domain(values).range(palette); return (v) => scale(v); } // Fallback: primary color with opacity mapped to normalized value const norm = d3.scaleLinear().domain([minV, maxV]).range([0.08, 0.9]).clamp(true); return (v) => `color-mix(in oklab, var(--primary-color) ${Math.round(norm(v) * 100)}%, var(--surface-bg))`; }
// (no local contrast function — use ColorPalettes.getTextStyleForBackground)
// Compute a fixed readable text color from a CSS rgb()/rgba() string function chooseFixedReadableTextOnBg(bgCss){ try { const m = String(bgCss||'').match(/rgba?\(([^)]+)\)/); if (!m) return '#0e1116'; const parts = m[1].split(',').map(s => parseFloat(s.trim())); const [r, g, b] = parts; // sRGB → relative luminance const srgb = [r, g, b].map(v => Math.max(0, Math.min(255, v)) / 255); const linear = srgb.map(c => (c <= 0.03928 ? c/12.92 : Math.pow((c + 0.055)/1.055, 2.4))); const L = 0.2126*linear[0] + 0.7152*linear[1] + 0.0722*linear[2]; // Threshold ~ 0.5 for readability; darker BG → white text, else near-black return L < 0.5 ? '#ffffff' : '#0e1116'; } catch(_) { return '#0e1116'; } }
function render() { const { innerWidth, innerHeight } = updateSize(); const n = classes.length; const gridSize = Math.min(innerWidth, innerHeight); const cellSize = gridSize / n;
const x = d3.scaleBand().domain(d3.range(n)).range([0, gridSize]).paddingInner(0.06); const y = d3.scaleBand().domain(d3.range(n)).range([0, gridSize]).paddingInner(0.06);
// Panel A: Baseline (row-normalized) const dataA = computeValues('row', matrixA); const colorA = getColorScale(dataA.data.map(d => d.value), dataA.minV, dataA.maxV);
gCellsA.selectAll('rect.cell-bg') .data([0]) .join('rect') .attr('class', 'cell-bg') .attr('x', 0) .attr('y', 0) .attr('width', gridSize) .attr('height', gridSize) .attr('fill', 'none') .attr('stroke', 'var(--border-color)') .attr('stroke-width', 1);
const cellsA = gCellsA.selectAll('g.cell') .data(dataA.data, d => `${d.r}-${d.c}-A`);
const cellsEnterA = cellsA.enter() .append('g') .attr('class', 'cell');
cellsEnterA.append('rect') .attr('rx', 2) .attr('ry', 2) .on('mousemove', (event, d) => { const [px, py] = d3.pointer(event, container); tipInner.innerHTML = `<strong>${classes[d.r]}</strong> → <strong>${classes[d.c]}</strong><br/>${(d.value * 100).toFixed(1)}% (${d.count})`; tip.style.transform = `translate(${px + 10}px, ${py + 10}px)`; tip.style.opacity = '1'; }) .on('mouseleave', () => { tip.style.opacity = '0'; });
cellsEnterA.append('text') .attr('class', 'cell-text') .attr('text-anchor', 'middle') .attr('dominant-baseline', 'middle');
const cellsMergedA = cellsEnterA.merge(cellsA);
cellsMergedA.select('rect') .attr('x', d => x(d.c)) .attr('y', d => y(d.r)) .attr('width', Math.max(1, x.bandwidth())) .attr('height', Math.max(1, y.bandwidth())) .attr('fill', d => colorA(d.value));
cellsMergedA.select('text') .attr('x', d => x(d.c) + x.bandwidth() / 2) .attr('y', d => y(d.r) + y.bandwidth() / 2) .text(d => `${Math.round(d.value * 100)}`) .style('fill', function(d){ try { const rect = this && this.parentNode ? this.parentNode.querySelector('rect') : null; const bg = rect ? getComputedStyle(rect).fill : colorA(d.value); return chooseFixedReadableTextOnBg(bg); } catch (_) { return '#0e1116'; } });
cellsA.exit().remove();
gAxesA.selectAll('*').remove();
gAxesA.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', (_, i) => x(i) + x.bandwidth() / 2) .attr('y', -8) .text(d => d);
gAxesA.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'end') .attr('x', -8) .attr('y', (_, i) => y(i) + y.bandwidth() / 2) .attr('dominant-baseline', 'middle') .text(d => d);
gAxesA.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', gridSize / 2) .attr('y', innerHeight + 20) .text('Predicted');
gAxesA.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('transform', `translate(${-40}, ${gridSize / 2}) rotate(-90)`) .text('Actual');
// Panel B: Delta (Improved − Baseline), row-normalized differences in percentage points const dataB = computeValues('row', matrixB); const diverging = getDivergingColors(13); // Build delta values aligned to A's ordering const mapA = new Map(dataA.data.map(d => [d.r + '-' + d.c, d.value])); const delta = dataB.data.map(d => ({ r: d.r, c: d.c, count: d.count, value: (d.value - (mapA.get(d.r + '-' + d.c) || 0)) })); // Symmetric domain around 0 (in proportions), express later as pp in labels const maxAbsDelta = Math.max(0.01, d3.max(delta, d => Math.abs(d.value)) || 0.01); const colorB = d3.scaleQuantize().domain([-maxAbsDelta, maxAbsDelta]).range(diverging);
gCellsB.selectAll('rect.cell-bg') .data([0]) .join('rect') .attr('class', 'cell-bg') .attr('x', 0) .attr('y', 0) .attr('width', gridSize) .attr('height', gridSize) .attr('fill', 'none') .attr('stroke', 'var(--border-color)') .attr('stroke-width', 1);
const cellsB = gCellsB.selectAll('g.cell') .data(dataB.data, d => `${d.r}-${d.c}-B`);
const cellsEnterB = cellsB.enter() .append('g') .attr('class', 'cell');
cellsEnterB.append('rect') .attr('rx', 2) .attr('ry', 2) .on('mousemove', (event, d) => { const [px, py] = d3.pointer(event, container); const a = dataA.data.find(x => x.r===d.r && x.c===d.c); const b = dataB.data.find(x => x.r===d.r && x.c===d.c); const dv = ((b ? b.value : 0) - (a ? a.value : 0)) * 100; tipInner.innerHTML = `<strong>${classes[d.r]}</strong> → <strong>${classes[d.c]}</strong>` + `<br/>baseline ${(a ? a.value*100 : 0).toFixed(1)}%` + `<br/>improved ${(b ? b.value*100 : 0).toFixed(1)}%` + `<br/>delta ${dv.toFixed(1)} pp`; tip.style.transform = `translate(${px + 10}px, ${py + 10}px)`; tip.style.opacity = '1'; }) .on('mouseleave', () => { tip.style.opacity = '0'; });
cellsEnterB.append('text') .attr('class', 'cell-text') .attr('text-anchor', 'middle') .attr('dominant-baseline', 'middle');
const cellsMergedB = cellsEnterB.merge(cellsB);
cellsMergedB.select('rect') .attr('x', d => x(d.c)) .attr('y', d => y(d.r)) .attr('width', Math.max(1, x.bandwidth())) .attr('height', Math.max(1, y.bandwidth())) .attr('fill', d => colorB(delta.find(x => x.r===d.r && x.c===d.c).value));
cellsMergedB.select('text') .attr('x', d => x(d.c) + x.bandwidth() / 2) .attr('y', d => y(d.r) + y.bandwidth() / 2) .text(d => { const dv = delta.find(x => x.r===d.r && x.c===d.c).value; return `${Math.round(dv * 100)}`; }) .style('fill', function(d){ try { const rect = this && this.parentNode ? this.parentNode.querySelector('rect') : null; const dv = delta.find(x => x.r===d.r && x.c===d.c).value; const bg = rect ? getComputedStyle(rect).fill : colorB(dv); return chooseFixedReadableTextOnBg(bg); } catch (_) { return '#0e1116'; } });
cellsB.exit().remove();
gAxesB.selectAll('*').remove();
gAxesB.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', (_, i) => x(i) + x.bandwidth() / 2) .attr('y', -8) .text(d => d);
gAxesB.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'end') .attr('x', -8) .attr('y', (_, i) => y(i) + y.bandwidth() / 2) .attr('dominant-baseline', 'middle') .text(d => d);
gAxesB.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', gridSize / 2) .attr('y', innerHeight + 20) .text('Predicted');
gAxesB.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('transform', `translate(${-40}, ${gridSize / 2}) rotate(-90)`) .text('Actual'); }
// Initial render + resize handling render(); const rerender = () => render(); if (window.ResizeObserver) { const ro = new ResizeObserver(() => rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); } };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456<div class="d3-line-example" style="width:100%;margin:10px 0;"></div><style> .d3-line-example .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-example .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-example .d3-line__controls select:hover { border-color: var(--primary-color); } .d3-line-example .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-example .d3-line__controls label { gap: 8px; }
/* Range slider themed with --primary-color */ .d3-line-example .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-example .d3-line__controls input[type="range"]::-webkit-slider-runnable-track { height: 6px; background: transparent; border-radius: 999px; } .d3-line-example .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-example .d3-line__controls input[type="range"]::-moz-range-track { height: 6px; background: transparent; border-radius: 999px; } .d3-line-example .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-example .lines path.improved { stroke: var(--primary-color); }
/* Responsive: stack controls on small screens */ @media (max-width: 640px) { .d3-line-example .d3-line__controls { flex-wrap: wrap; } .d3-line-example .d3-line__controls label { flex: 1 1 100% !important; width: 100%; } }</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;
const getLocalPrev = () => { if (!scriptEl) return null; let el = scriptEl.previousElementSibling; while (el && !(el.classList && el.classList.contains('d3-line-example'))) { el = el.previousElementSibling; } return el || null; };
const localTarget = getLocalPrev(); const targets = localTarget ? [localTarget] : Array.from(document.querySelectorAll('.d3-line-example')) .filter((el) => !(el.dataset && el.dataset.mounted === 'true'));
targets.forEach((container) => { if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Dataset params matching the Plotly version const datasets = [ { name: 'CIFAR-10', base: { ymin:0.10, ymax:0.90, k:10.0, x0:0.55 }, aug: { ymin:0.15, ymax:0.96, k:12.0, x0:0.40 }, target: 0.97 }, { name: 'CIFAR-100', base: { ymin:0.05, ymax:0.70, k: 9.5, x0:0.60 }, aug: { ymin:0.08, ymax:0.80, k:11.0, x0:0.45 }, target: 0.85 }, { name: 'ImageNet-1K', base: { ymin:0.02, ymax:0.68, k: 8.5, x0:0.65 }, aug: { ymin:0.04, ymax:0.75, k: 9.5, x0:0.50 }, target: 0.82 }, ];
// Controls UI const controls = document.createElement('div'); controls.className = 'd3-line__controls'; Object.assign(controls.style, { marginTop: '12px', display: 'flex', gap: '16px', alignItems: 'center' });
const labelDs = document.createElement('label'); Object.assign(labelDs.style, { fontSize: '12px', color: 'rgba(0,0,0,.65)', display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap', padding: '6px 10px' }); labelDs.textContent = 'Dataset'; const selectDs = document.createElement('select'); Object.assign(selectDs.style, { fontSize: '12px' }); datasets.forEach((d, i) => { const o = document.createElement('option'); o.value = String(i); o.textContent = d.name; selectDs.appendChild(o); }); labelDs.appendChild(selectDs);
const labelAlpha = document.createElement('label'); Object.assign(labelAlpha.style, { fontSize: '12px', color: 'rgba(0,0,0,.65)', display: 'flex', alignItems: 'center', gap: '10px', flex: '1', padding: '6px 10px' }); labelAlpha.appendChild(document.createTextNode('Augmentation α')); const slider = document.createElement('input'); slider.type = 'range'; slider.min = '0'; slider.max = '1'; slider.step = '0.01'; slider.value = '0.70'; Object.assign(slider.style, { flex: '1' }); const alphaVal = document.createElement('span'); alphaVal.className = 'alpha-value'; alphaVal.textContent = slider.value; labelAlpha.appendChild(slider); labelAlpha.appendChild(alphaVal);
controls.appendChild(labelDs); controls.appendChild(labelAlpha);
// Create SVG const svg = d3.select(container).append('svg') .attr('width', '100%') .style('display', 'block');
// Groups const gRoot = svg.append('g'); const gGrid = gRoot.append('g').attr('class', 'grid'); const gAxes = gRoot.append('g').attr('class', 'axes'); const gLines = gRoot.append('g').attr('class', 'lines'); 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 const colorBase = '#64748b'; // slate-500 const colorImproved = 'var(--primary-color)'; const colorTarget = '#4b5563'; // gray-600 const legendBgLight = 'rgba(255,255,255,0.85)'; const legendBgDark = 'rgba(17,17,23,0.85)';
// Data and helpers const N = 240; const xs = Array.from({ length: N }, (_, i) => i / (N - 1)); const logistic = (x, { ymin, ymax, k, x0 }) => ymin + (ymax - ymin) / (1 + Math.exp(-k * (x - x0))); const blend = (l, e, a) => (1 - a) * l + a * e;
let datasetIndex = 0; let alpha = parseFloat(slider.value) || 0.7;
let yBase = []; let yAug = []; let yImp = []; let yTgt = [];
function computeCurves() { const d = datasets[datasetIndex]; yBase = xs.map((x) => logistic(x, d.base)); yAug = xs.map((x) => logistic(x, d.aug)); yTgt = xs.map(() => d.target); yImp = yBase.map((v, i) => blend(v, yAug[i], alpha)); }
// 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();
// Paths const lineGen = d3.line() .curve(d3.curveCatmullRom.alpha(0.6)) .x((d, i) => xScale(xs[i])) .y((d) => yScale(d));
const pathBase = gLines.append('path').attr('fill', 'none').attr('stroke', colorBase).attr('stroke-width', 2); const pathImp = gLines.append('path').attr('class', 'improved').attr('fill', 'none').style('stroke', 'var(--primary-color)').attr('stroke-width', 2); const pathTgt = gLines.append('path').attr('fill', 'none').attr('stroke', colorTarget).attr('stroke-width', 2).attr('stroke-dasharray', '6,6');
// Hover elements const hoverLine = gHover.append('line').attr('stroke-width', 1); const hoverDotB = gHover.append('circle').attr('r', 3.5).attr('fill', colorBase).attr('stroke', '#fff').attr('stroke-width', 1); const hoverDotI = gHover.append('circle').attr('class', 'improved').attr('r', 3.5).style('fill', 'var(--primary-color)').attr('stroke', '#fff').attr('stroke-width', 1); const hoverDotT = gHover.append('circle').attr('r', 3.5).attr('fill', colorTarget).attr('stroke', '#fff').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(260, Math.round(width / 3)); 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})`);
xScale.domain([0, 1]).range([0, innerWidth]); yScale.domain([0, 1]).range([innerHeight, 0]);
// Grid (horizontal) gGrid.selectAll('*').remove(); const yTicks = yScale.ticks(6); 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(); const xAxis = d3.axisBottom(xScale).ticks(8).tickSizeOuter(0); const yAxis = d3.axisLeft(yScale).ticks(6).tickSizeOuter(0).tickFormat(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('Epoch'); gAxes.append('text') .attr('class', 'axis-label axis-label--y') .attr('text-anchor', 'middle') .attr('transform', `translate(${-52},${innerHeight/2}) rotate(-90)`) .style('font-size', '12px') .style('fill', tickColor) .text('Accuracy');
overlay.attr('x', 0).attr('y', 0).attr('width', innerWidth).attr('height', innerHeight); hoverLine.attr('y1', 0).attr('y2', innerHeight).attr('stroke', axisColor);
// Legend inside plot (bottom-right), no background/border/shadow 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)' }); legendRoot.html(` <div style="display:flex;flex-direction:column;gap:6px;"> <div style="display:flex;align-items:center;gap:8px;"> <span style="width:18px;height:3px;background:${colorBase};border-radius:2px;display:inline-block"></span> <span>Baseline</span> </div> <div style="display:flex;align-items:center;gap:8px;"> <span style="width:18px;height:3px;background:${colorImproved};border-radius:2px;display:inline-block"></span> <span>Improved</span> </div> <div style="display:flex;align-items:center;gap:8px;"> <span style="width:18px;height:0;border-top:2px dashed ${colorTarget};display:inline-block"></span> <span>Target</span> </div> </div> `); }
function updatePaths() { pathBase.transition().duration(200).attr('d', lineGen(yBase)); pathImp.transition().duration(200).attr('d', lineGen(yImp)); pathTgt.transition().duration(200).attr('d', lineGen(yTgt)); }
function updateAlpha(a) { alpha = a; alphaVal.textContent = a.toFixed(2); yImp = yBase.map((v, i) => blend(v, yAug[i], alpha)); pathImp.transition().duration(80).attr('d', lineGen(yImp)); }
function applyDataset() { computeCurves(); updatePaths(); }
// Hover interactions function onMove(event) { const [mx, my] = d3.pointer(event, overlay.node()); const xi = Math.max(0, Math.min(N - 1, Math.round(xScale.invert(mx) * (N - 1)))); const xpx = xScale(xs[xi]); const yb = yBase[xi], yi = yImp[xi], yt = yTgt[xi]; hoverLine.attr('x1', xpx).attr('x2', xpx).style('display', null); hoverDotB.attr('cx', xpx).attr('cy', yScale(yb)).style('display', null); hoverDotI.attr('cx', xpx).attr('cy', yScale(yi)).style('display', null); hoverDotT.attr('cx', xpx).attr('cy', yScale(yt)).style('display', null);
// Tooltip content const ds = datasets[datasetIndex].name; tipInner.innerHTML = `<div><strong>${ds}</strong></div>` + `<div><strong>x</strong> ${xs[xi].toFixed(2)}</div>` + `<div><span style="display:inline-block;width:10px;height:10px;background:${colorBase};border-radius:50%;margin-right:6px;"></span><strong>Baseline</strong> ${yb.toFixed(3)}</div>` + `<div><span style="display:inline-block;width:10px;height:10px;background:${colorImproved};border-radius:50%;margin-right:6px;"></span><strong>Improved</strong> ${yi.toFixed(3)}</div>` + `<div><span style="display:inline-block;width:10px;height:10px;background:${colorTarget};border-radius:50%;margin-right:6px;"></span><strong>Target</strong> ${yt.toFixed(3)}</div>`; 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'); hoverDotB.style('display', 'none'); hoverDotI.style('display', 'none'); hoverDotT.style('display', 'none'); }
overlay.on('mousemove', onMove).on('mouseleave', onLeave);
// Init + controls wiring computeCurves(); updateScales(); updatePaths();
// Attach controls after SVG for consistency with Plotly fragment container.appendChild(controls);
selectDs.addEventListener('change', (e) => { datasetIndex = parseInt(e.target.value) || 0; applyDataset(); }); slider.addEventListener('input', (e) => { const a = parseFloat(e.target.value) || 0; updateAlpha(a); });
// Resize handling const render = () => { updateScales(); updatePaths(); }; if (window.ResizeObserver) { const ro = new ResizeObserver(() => render()); ro.observe(container); } else { window.addEventListener('resize', render); } render(); }); };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
1234123456789101112131415161718192021222324252627282930313233131415161718192021222324252637383940272829303132331 unmodified line35363748383940414253434445464748496061626350515253545565565758596960616263646575666768697080717273741 unmodified line76777888798081829283848586879788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418541 unmodified lines22722822914723023123223338 unmodified lines27227327419219319419519619719819920020120220320420520620720820921021121221321421521621721821922027527627727827928028128228328428528628728828929029129222722822929329429529629729812 unmodified lines3113123132483143153163173182532542552562572582592602612623193202642653213223233243253263273282723293303313324 unmodified lines33733833928334034134234334434528929029129229329434634734824 unmodified lines3733743753253763773783795 unmodified lines38538638733738838939039139239339439539639739839940034234334440140240340440540640740840941041141241341441541641741834734834935035135235335435535635735835941942042142242342442542642742842943043143243343443543643743843944036644144244336937044444544644737344844945045145245345441 unmodified lines4964974984214995005015022 unmodified lines5055065075085095105115125135145154325165175185195204375215225235245255264435275285295305315325335345 unmodified lines54054154245845946046146246346446554354454554654754854955055155255355413 unmodified lines5685695704855715724874884895735745755765775783 unmodified lines5825835844995005015025035045055065075085095855865115125875885895905915925935945955965975985996006016026036046056066076086096106116126134 unmodified lines618619620621622<div class="filters-quad" style="width:100%;margin:10px 0;"> <div class="filters-quad__controls" aria-label="Global chart controls"></div> <div class="filters-quad__legend" aria-label="Global legend"></div> <div class="filters-quad__grid"><div class="line-quad"> <div class="line-quad__grid"> <div class="quad-cell" data-title="Formatting Filter" data-csv="/data/formatting_filters.csv"></div> <div class="quad-cell" data-title="Relevance Filter" data-csv="/data/relevance_filters.csv"></div> <div class="quad-cell" data-title="Visual Dependency Filter" data-csv="/data/visual_dependency_filters.csv"></div> <div class="quad-cell" data-title="Image Correspondence Filter" data-csv="/data/image_correspondence_filters.csv"></div> </div> <noscript>JavaScript is required to render these charts.</noscript>
</div><style> .filters-quad { position: relative; } .filters-quad__grid { display:grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; } @media (max-width: 980px) { .filters-quad__grid { grid-template-columns: 1fr; } }
.filters-quad__controls { display:flex; align-items:center; justify-content:center; gap:12px; margin: 6px 0 12px 0; flex-wrap:wrap; } .filters-quad__controls label { font-size:14px; color: var(--text-color); font-weight:600; display:flex; align-items:center; gap:8px; } .filters-quad__controls select { font-size: 14px; padding: 8px 32px 8px 12px; border: 1px solid var(--border-color); border-radius: 10px; 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; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; } [data-theme="dark"] .filters-quad__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"); } .filters-quad__controls select:hover { border-color: var(--primary-color); } .filters-quad__controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; }
.filters-quad__legend { display:flex; align-items:center; justify-content:center; gap:12px; flex-wrap:wrap; font-size:12px; color: var(--text-color); margin: 2px 0 10px 0; } .filters-quad__legend .item { display:inline-flex; align-items:center; gap:6px; white-space:nowrap; } .filters-quad__legend .swatch { width:10px; height:10px; border-radius:50%; display:inline-block; } .line-quad { position: relative; } /* Axis/tick/grid use global variables from _variables.css */ /* Apply axis/tick/grid purely via CSS */ .line-quad .axes path, .line-quad .axes line { stroke: var(--axis-color); } .line-quad .axes text { fill: var(--tick-color); } .line-quad .grid line { stroke: var(--grid-color); } .line-quad__grid { display:grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; } @media (max-width: 980px) { .line-quad__grid { grid-template-columns: 1fr; } }
.quad-cell { border:1px solid var(--border-color); border-radius:10px; background: var(--surface-bg); display:flex; flex-direction:column; position: relative; } /* Stacking order to ensure hover/tooltip overlays are not hidden by neighbors */ .filters-quad__grid .quad-cell:nth-child(1) { z-index: 4; } /* top-left */ .filters-quad__grid .quad-cell:nth-child(3) { z-index: 3; } /* bottom-left */ .filters-quad__grid .quad-cell:nth-child(2) { z-index: 2; } /* top-right */ .filters-quad__grid .quad-cell:nth-child(4) { z-index: 1; } /* bottom-right */ .line-quad__grid .quad-cell:nth-child(1) { z-index: 4; } /* top-left */ .line-quad__grid .quad-cell:nth-child(3) { z-index: 3; } /* bottom-left */ .line-quad__grid .quad-cell:nth-child(2) { z-index: 2; } /* top-right */ .line-quad__grid .quad-cell:nth-child(4) { z-index: 1; } /* bottom-right */ .quad-cell .cell-header { padding:8px 10px; border-bottom:1px solid var(--border-color); display:flex; align-items:center; justify-content:space-between; gap:8px; } .quad-cell .cell-title { font-size: 13px; font-weight: 700; color: var(--text-color); } .quad-cell .cell-controls { display:flex; align-items:center; gap:12px; }1 unmodified line .quad-cell select { font-size: 12px; padding: 6px 28px 6px 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-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='1' 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; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; } [data-theme="dark"] .quad-cell 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"); 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='1' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); } .quad-cell select:hover { border-color: var(--primary-color); } .quad-cell select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; } .quad-cell .cell-body { position: relative; } .quad-cell .cell-body { width:100%; overflow:hidden; } .quad-cell .cell-body svg { max-width:100%; height:auto; } .quad-cell .legend { font-size: 12px; line-height: 1.35; color: var(--text-color); } .quad-cell .legend .items { display:flex; flex-wrap:wrap; gap:8px 12px; align-items:center; justify-content:flex-end; } .quad-cell .legend .item { display:flex; align-items:center; gap:6px; white-space:nowrap; } .quad-cell .legend .swatch { width:10px; height:10px; border-radius:50%; display:inline-block; } .line-quad.hovering .lines path.ghost { opacity: .25; } .line-quad.hovering .points circle.ghost { opacity: .25; } .line-quad.hovering .areas path.ghost { opacity: .08; } .line-quad.hovering .legend-bottom .item.ghost { opacity: .35; } /* Tooltip refined styling */ .filters-quad .d3-tooltip { .line-quad .d3-tooltip { z-index: 20; backdrop-filter: saturate(1.12) blur(8px); } .filters-quad .d3-tooltip__inner { .line-quad .d3-tooltip__inner { display: flex; flex-direction: column; gap: 6px; min-width: 220px; } .filters-quad .d3-tooltip__inner > div:first-child { .line-quad .d3-tooltip__inner > div:first-child { font-weight: 800; letter-spacing: 0.1px; margin-bottom: 0; } .filters-quad .d3-tooltip__inner > div:nth-child(2) { .line-quad .d3-tooltip__inner > div:nth-child(2) { font-size: 11px; color: var(--muted-color); display: block;1 unmodified line margin-bottom: 2px; letter-spacing: 0.1px; } .filters-quad .d3-tooltip__inner > div:nth-child(n+3) { .line-quad .d3-tooltip__inner > div:nth-child(n+3) { padding-top: 6px; border-top: 1px solid var(--border-color); } .filters-quad .d3-tooltip__inner svg { .line-quad .d3-tooltip__inner svg { display: inline-block; vertical-align: middle; margin-right: 2px; } .filters-quad .d3-tooltip__inner strong { .line-quad .d3-tooltip__inner strong { margin-right: 6px; } .line-quad .d3-tooltip__color-dot { display: inline-block; width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-color); } /* Header layout (like d3-line-simple) */ .line-quad__header { display: flex; align-items: flex-start; justify-content: flex-start; gap: 12px; margin: 8px 0 0 0; flex-wrap: wrap; } .line-quad__header .legend-bottom { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; font-size: 12px; color: var(--text-color); } .line-quad__header .legend-bottom .legend-title { font-size: 12px; font-weight: 700; color: var(--text-color); } .line-quad__header .legend-bottom .items { display: flex; flex-wrap: wrap; gap: 8px 14px; } .line-quad__header .legend-bottom .item { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } .line-quad__header .legend-bottom .swatch { width: 14px; height: 14px; border-radius: 3px; border: 1px solid var(--border-color); display: inline-block; } .line-quad .controls { margin-top: 0; display: flex; gap: 16px; align-items: center; justify-content: flex-end; width: auto; flex-wrap: wrap; } .line-quad .controls .control-group { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; } .line-quad .controls label { font-size: 12px; color: var(--text-color); display: flex; align-items: center; gap: 6px; white-space: nowrap; font-weight: 700; } .line-quad .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='1' 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; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; } [data-theme="dark"] .line-quad .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='1' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E"); } .line-quad .controls select:hover { border-color: var(--primary-color); } .line-quad .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; }</style><script> (() => {41 unmodified lines 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').style('display','none'); // Removed per-cell legend; using global footer legend
// Tooltip cell.style.position = cell.style.position || 'relative';38 unmodified lines // Colors and markers (match original embeds) const primary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#E889AB'; const pool = [primary, '#4EA5B7', '#E38A42', '#CEC0FA', ...(d3.schemeTableau10||[])]; const markerShapes = ['circle', 'square', 'triangle', 'diamond', 'inverted-triangle']; const markerSize = 6; 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); } } // Inline SVG for tooltip shapes function markerSVG(shape, color) { const size = 12; const s = size / 2; const stroke = color; if (shape === 'circle') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><circle r="5" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'square') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><rect x="-5" y="-5" width="10" height="10" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'triangle') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><path d="M0,-6 L5,3 L-5,3 Z" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'diamond') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><path d="M0,-6 L6,0 L0,6 L-6,0 Z" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'inverted-triangle') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><path d="M0,6 L5,-3 L-5,-3 Z" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><circle r="5" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; } // Shapes supprimés: on n'utilise que la couleur // Ready signal for async load completion let readyResolve = null; const ready = new Promise((res)=> { readyResolve = res; });
// Shared formatter for thousands: 5000 -> 5k, 1500 -> 1.5k (trim .0) const formatK = (v) => { const abs = Math.abs(v); if (abs >= 1000) { const n = v / 1000; const s = d3.format('.1f')(n); return (s.endsWith('.0') ? s.slice(0, -2) : s) + 'k'; } return d3.format('d')(v); };
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)'; const axisColor = 'var(--axis-color)'; const tickColor = 'var(--tick-color)'; const gridColor = 'var(--grid-color)';
const rect = cell.getBoundingClientRect(); width = Math.max(1, Math.round(rect && rect.width ? rect.width : (cell.clientWidth || 800)));12 unmodified lines 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'); .attr('stroke', gridColor).attr('stroke-width',1).attr('shape-rendering','crispEdges');
// Axes gAxes.selectAll('*').remove(); let xAxis = d3.axisBottom(xScale).tickSizeOuter(0); xAxis = xAxis.ticks(8); const fmtK = (v) => { const abs = Math.abs(v); if (abs >= 1000) { const n = v / 1000; const s = d3.format('.1f')(n); return (s.endsWith('.0') ? s.slice(0, -2) : s) + 'k'; } return d3.format('d')(v); }; xAxis = xAxis.tickFormat(fmtK); xAxis = xAxis.tickFormat(formatK); 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','11px'); }); gAxes.append('g').call(yAxis).call(g=>{ g.selectAll('path, line').attr('stroke',axisColor); g.selectAll('text').attr('fill',tickColor).style('font-size','11px'); }); 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','11px'); }); gAxes.append('g').call(yAxis).call(g=>{ g.selectAll('path, line').attr('stroke', axisColor); g.selectAll('text').attr('fill', tickColor).style('font-size','11px'); });
// Axis labels gAxes.append('text') .attr('class', 'x-axis-label') .attr('x', innerWidth / 2) .attr('y', innerHeight + Math.max(20, Math.min(36, margin.bottom - 10))) .attr('fill', tickColor) .attr('fill', 'var(--text-color)') .attr('text-anchor', 'middle') .style('font-size', '12px') .style('font-weight', '700')4 unmodified lines .attr('transform', 'rotate(-90)') .attr('x', -innerHeight / 2) .attr('y', -Math.max(16, Math.min(28, margin.left - 8) + 10)) .attr('fill', tickColor) .attr('fill', 'var(--text-color)') .attr('text-anchor', 'middle') .style('font-size', '12px') .style('font-weight', '700') .text(axisLabelY);
// Legend box (top-right) // Per-cell legend hidden; global legend is used const legendWidth = 0, legendHeight = 0; gLegend.attr('x', 0).attr('y', 0).attr('width', legendWidth).attr('height', legendHeight); const legendRoot = gLegend.selectAll('div').data([0]).join('xhtml:div'); Object.assign(legendRoot.node().style, { width:'0px', height:'0px', display:'none' }); return { innerWidth, innerHeight, tickColor }; }
24 unmodified lines axisLabelY = isRankStrict ? 'Rank' : prettyMetricLabel(metricKey); const { innerWidth, innerHeight } = updateScales();
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) })); const series = runs.map((r, i) => ({ run:r, color: pool[i % pool.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) }));
// zones ± stderr (métriques non rank) gAreas.selectAll('*').remove();5 unmodified lines 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'); gAreas.append('path') .attr('class','area') .attr('data-run', s.run) .attr('d', pathData) .attr('fill', s.color) .attr('opacity', 0) .attr('stroke', 'none') .transition().duration(450).ease(d3.easeCubicOut) .attr('opacity', 0.15); }); }
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('opacity',0.9) .attr('stroke', d=>d.color).attr('d', d=>lineGen(d.values)) .merge(paths).attr('stroke', d=>d.color).attr('d', d=>lineGen(d.values)); paths.enter() .append('path') .attr('class','run-line') .attr('data-run', d=>d.run) .attr('fill','none') .attr('stroke-width', 1) .attr('opacity',0) .attr('stroke', d=>d.color) .attr('d', d=>lineGen(d.values)) .transition().duration(450).ease(d3.easeCubicOut) .attr('opacity',0.9); paths .transition().duration(450).ease(d3.easeCubicOut) .attr('stroke', d=>d.color) .attr('opacity',0.9) .attr('d', d=>lineGen(d.values)); paths.exit().remove();
gPoints.selectAll('*').remove(); series.forEach((s, idx) => { const pointGroup = gPoints.selectAll(`.points-${idx}`) .data(s.values) .join('g') .attr('class', `points-${idx}`) .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'); }); // Draw light point markers at each data sample (subtle) const allPoints = series.flatMap(s => s.values.map(v => ({ run:s.run, color:s.color, step:v.step, value:v.value }))); const ptsSel = gPoints.selectAll('circle.pt').data(allPoints, d=> `${d.run}-${d.step}`); ptsSel.enter().append('circle').attr('class','pt') .attr('data-run', d=>d.run) .attr('r', 2) .attr('fill', d=>d.color) .attr('fill-opacity', 0.6) .attr('stroke', 'none') .attr('cx', d=>xScale(d.step)) .attr('cy', d=>yScale(d.value)) .merge(ptsSel) .transition().duration(180) .attr('cx', d=>xScale(d.step)) .attr('cy', d=>yScale(d.value)); ptsSel.exit().remove();
// No per-cell legend content (handled globally)
// Hover gHover.selectAll('*').remove(); const overlay = gHover.append('rect').attr('fill','transparent').style('cursor','crosshair').attr('x',0).attr('y',0).attr('width', innerWidth).attr('height', innerHeight); const hoverLine = gHover.append('line').attr('stroke','rgba(0,0,0,0.25)').attr('stroke-width',1).attr('y1',0).attr('y2',innerHeight).style('display','none'); const hoverLine = gHover.append('line').style('stroke','var(--text-color)').attr('stroke-opacity', 0.25).attr('stroke-width',1).attr('y1',0).attr('y2',innerHeight).style('display','none'); 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(ev){ if (hideTipTimer) { clearTimeout(hideTipTimer); hideTipTimer = null; } const [mx,my]=d3.pointer(ev, overlay.node()); 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); hoverLine.attr('x1',xpx).attr('x2',xpx).style('display',null); let html = `<div><strong>${titleText}</strong></div><div><strong>step</strong> ${nearest}</div>`; const entries = series.map(s=>{ const map = new Map(s.values.map(v=>[v.step, v])); const pt = map.get(nearest); return { run:s.run, color:s.color, marker:s.marker, pt }; }).filter(e => e.pt && e.pt.value!=null); let html = `<div><strong>${titleText}</strong></div><div><strong>step</strong> ${formatK(nearest)}</div>`; const entries = series.map(s=>{ const map = new Map(s.values.map(v=>[v.step, v])); const pt = map.get(nearest); return { run:s.run, color:s.color, pt }; }).filter(e => e.pt && e.pt.value!=null); entries.sort((a,b)=> (a.pt.value - b.pt.value)); const fmt = (vv)=> (isRankStrictFlag? d3.format('d')(vv) : (+vv).toFixed(4)); entries.forEach(e => { const err = (e.pt.stderr!=null && isFinite(e.pt.stderr) && e.pt.stderr>0) ? ` ± ${fmt(e.pt.stderr)}` : ''; html += `<div style="display:flex;align-items:center;gap:6px;white-space:nowrap;">${markerSVG(e.marker, e.color)}<strong>${e.run}</strong> ${fmt(e.pt.value)}${err}</div>`; }); entries.forEach(e => { const err = (e.pt.stderr!=null && isFinite(e.pt.stderr) && e.pt.stderr>0) ? ` ± ${fmt(e.pt.stderr)}` : ''; html += `<div style="display:flex;align-items:center;gap:8px;white-space:nowrap;"><span class=\"d3-tooltip__color-dot\" style=\"background:${e.color}\"></span><strong>${e.run}</strong><span style=\"margin-left:auto;text-align:right;\">${fmt(e.pt.value)}${err}</span></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(){ hideTipTimer = setTimeout(()=>{ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; hoverLine.style('display','none'); }, 100); } overlay.on('mousemove', onMove).on('mouseleave', onLeave);41 unmodified lines const isRank = /rank/i.test(key); const isAverage = /average/i.test(key); const isRankStrict = isRank && !isAverage; runs.forEach(r => { (map[r]||[]).forEach(pt => { const v = isRankStrict ? Math.round(pt.value) : pt.value; minStep=Math.min(minStep,pt.step); maxStep=Math.max(maxStep,pt.step); maxVal=Math.max(maxVal,v); minVal=Math.min(minVal,v); }); }); const rankMax = isRank ? Math.max(1, Math.round(maxVal)) : null; return { isRank, isRankStrict, min: minVal, max: maxVal, rankMax }; return { isRank, isRankStrict, min: maxVal === 0 && minVal === Infinity ? null : minVal, max: maxVal, rankMax }; }, setSharedY: (cfg) => { sharedYConfig = cfg || null; if (metricList && metricList.length) { /* re-render last metric if possible */ const current = cfg && cfg.key ? cfg.key : null; const m = current || metricList[0]; renderMetric(m); } } };2 unmodified lines const bootstrap = () => { const scriptEl = THIS_SCRIPT; let host = null; // Build header (legend + controls) and append after grid const header = document.createElement('div'); header.className = 'line-quad__header'; const legend = document.createElement('div'); legend.className = 'legend-bottom'; legend.innerHTML = '<div class="legend-title">Legend</div><div class="items"></div>'; const controls = document.createElement('div'); controls.className = 'controls'; controls.innerHTML = '<div class="control-group"><label>Metric</label><select></select></div>'; header.appendChild(legend); header.appendChild(controls); // Try finding within parent (fragment mount is inside parent) if (scriptEl && scriptEl.parentElement && scriptEl.parentElement.querySelector) { host = scriptEl.parentElement.querySelector('.filters-quad'); host = scriptEl.parentElement.querySelector('.line-quad'); } // Fallback: scan previous siblings if (!host) { let sib = scriptEl && scriptEl.previousElementSibling; while (sib && !(sib.classList && sib.classList.contains('filters-quad'))) { while (sib && !(sib.classList && sib.classList.contains('line-quad'))) { sib = sib.previousElementSibling; } host = sib || null; } // Last resort: global query if (!host) { host = document.querySelector('.filters-quad'); } if (!host) { host = document.querySelector('.line-quad'); } if (!host) return; if (host.dataset && host.dataset.mounted === 'true') return; if (host.dataset) host.dataset.mounted = 'true'; const cells = host.querySelectorAll('.quad-cell'); if (!cells.length) return; host.appendChild(header); const instances = Array.from(cells).map(cell => initRunLine(cell));
(async () => {5 unmodified lines if (!metrics.length) { metrics = lists[0] || []; } const def = (metrics.includes('ai2d_exact_match') ? 'ai2d_exact_match' : (metrics.find(m => /average_rank/i.test(m)) || metrics[0] || ''));
let ctrl = host.querySelector('.filters-quad__controls'); if (!ctrl) { ctrl = document.createElement('div'); ctrl.className = 'filters-quad__controls'; host.insertBefore(ctrl, host.firstChild); } ctrl.innerHTML = ''; const label = document.createElement('label'); label.textContent = 'Metric'; const select = document.createElement('select'); metrics.forEach(m => { const o=document.createElement('option'); o.value=m; o.textContent=prettyMetricLabel(m); select.appendChild(o); }); if (def) select.value = def; label.appendChild(select); ctrl.appendChild(label); // Wire header controls (select under "Metric" label) const headerEl = host.querySelector('.line-quad__header'); if (headerEl && !headerEl.isConnected) host.appendChild(header); const select = (headerEl || header).querySelector('.controls select'); if (select) { select.innerHTML = ''; metrics.forEach(m => { const o=document.createElement('option'); o.value=m; o.textContent=prettyMetricLabel(m); select.appendChild(o); }); if (def) select.value = def; }
const computeAndApplySharedY = (metric) => { try {13 unmodified lines
const applyAll = (v) => { computeAndApplySharedY(v); instances.forEach(i => i && typeof i.setMetric === 'function' && i.setMetric(v)); }; if (def) applyAll(def); select.addEventListener('change', () => applyAll(select.value)); if (select) select.addEventListener('change', () => applyAll(select.value));
// Légende globale (couleurs + formes, alignée avec les marqueurs des séries) const legendHost = host.querySelector('.filters-quad__legend'); if (legendHost) { // Global legend (in header, colors only) const legendItemsHost = (headerEl || header).querySelector('.legend-bottom .items'); if (legendItemsHost) { try { const f = '/data/formatting_filters.csv'; const r = await fetch(f, { cache:'no-cache' });3 unmodified lines const runList = Array.from(new Set(rows.map(row => String(row.run||'').trim()).filter(Boolean))); const primary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#E889AB'; const pool = [primary, '#4EA5B7', '#E38A42', '#CEC0FA', ...((window.d3 && window.d3.schemeTableau10) ? window.d3.schemeTableau10 : ['#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f','#edc948','#b07aa1','#ff9da7','#9c755f','#bab0ab'])]; const markerShapes = ['circle', 'square', 'triangle', 'diamond', 'inverted-triangle']; const shapeSVG = (shape, color) => { const size = 12; const s = size/2; const stroke = color; if (shape === 'circle') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><circle r="5" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'square') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><rect x="-5" y="-5" width="10" height="10" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'triangle') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><path d="M0,-6 L5,3 L-5,3 Z" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'diamond') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><path d="M0,-6 L6,0 L0,6 L-6,0 Z" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; if (shape === 'inverted-triangle') return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><path d="M0,6 L5,-3 L-5,-3 Z" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; return `<svg width="12" height="12" viewBox="-6 -6 12 12" aria-hidden="true"><circle r="5" fill="${color}" stroke="${stroke}" stroke-width="1" /></svg>`; }; legendHost.innerHTML = runList.map((name, i)=> { legendItemsHost.innerHTML = runList.map((name, i)=> { const color = pool[i % pool.length]; const shape = markerShapes[i % markerShapes.length]; return `<span class="item">${shapeSVG(shape, color)}<span>${name}</span></span>`; return `<span class="item" data-run="${name}"><span class=\"swatch\" style=\"background:${color}\"></span><span>${name}</span></span>`; }).join(''); // Legend hover ghosting across all cells legendItemsHost.querySelectorAll('.item').forEach(el => { el.addEventListener('mouseenter', () => { const run = el.getAttribute('data-run'); if (!run) return; host.classList.add('hovering'); host.querySelectorAll('.quad-cell').forEach(cell => { cell.querySelectorAll('.lines path.run-line').forEach(p => p.classList.toggle('ghost', p.getAttribute('data-run') !== run)); cell.querySelectorAll('.points circle.pt').forEach(c => c.classList.toggle('ghost', c.getAttribute('data-run') !== run)); cell.querySelectorAll('.areas path.area').forEach(a => a.classList.toggle('ghost', a.getAttribute('data-run') !== run)); }); legendItemsHost.querySelectorAll('.item').forEach(it => it.classList.toggle('ghost', it.getAttribute('data-run') !== run)); }); el.addEventListener('mouseleave', () => { host.classList.remove('hovering'); host.querySelectorAll('.quad-cell').forEach(cell => { cell.querySelectorAll('.lines path.run-line').forEach(p => p.classList.remove('ghost')); cell.querySelectorAll('.points circle.pt').forEach(c => c.classList.remove('ghost')); cell.querySelectorAll('.areas path.area').forEach(a => a.classList.remove('ghost')); }); legendItemsHost.querySelectorAll('.item').forEach(it => it.classList.remove('ghost')); }); }); } } catch {} }4 unmodified lines })();</script>
112334567891011121314151617181920212223242526272829303132333435361 unmodified line3839401112131415161718414243204445462324252627282930313233343536373839404142434445464748495051525354555657474849505152535455565758596061626364656667686970717273745960616275767778796465666768697080818283847273858687888990919293949596979899100101102103104105106107108109110111112113114115116808182838485117118878811912012112212393949596979899100101124125126127128103104105106107108109110129112113114115116117118119120121122123124125126127128129130131131132133133134135136137138139140141142134135136137144145146138139149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178140141142143144145146147148149182183150151185186152153188189190191154155156157193194195196197198199200201202203204205206207208158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187210211212213214215216217218219220221222223224225226227228188230231232233234235236237238239240241242243244245246247248249250251252253254189190191192193194195196197198199200201202203204258259260261262205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248265249250267268269270251252253273274275276277278279280281282283284285286254255256257258288259260261262263264265266267268269270271290291292293294295296297298299272273274275301276277303304305306307308309310311312313314315316317318319320321278279280281282283284285286287288289290291292293294295296297298299300323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378301380381382383384385386387388389390391392393394395396397398399400302303304305306307308309310311312313402403404405406407408409410411412314414415416417418419420421422423424425426427428429430431432315316317318319320321435436437438439440441442443444445446447322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393449450451452394395396397398454455456457458399400401402403404405460461462406407408409410411468469470412413414415474475476477478479480481482416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453486487488489490491492493494495496497498454455456457458459501502460461462463464507508509465466467468<div class="d3-line" style="width:100%;margin:10px 0;"></div><div class="d3-line-simple"></div><style> .d3-line .d3-line__controls select { .d3-line-simple { position: relative; } /* Theme-driven axis/tick/grid variables */ .d3-line-simple { --axis-color: rgba(0,0,0,0.25); --tick-color: rgba(0,0,0,0.55); --grid-color: rgba(0,0,0,0.05); } [data-theme="dark"] .d3-line-simple { --axis-color: rgba(255,255,255,0.25); --tick-color: rgba(255,255,255,0.70); --grid-color: rgba(255,255,255,0.08); } .d3-line-simple .controls { margin-top: 0; display: flex; gap: 16px; align-items: center; justify-content: flex-end; width: auto; flex-wrap: wrap; } .d3-line-simple .controls label { font-size: 12px; color: var(--text-color); display: flex; align-items: center; gap: 6px; white-space: nowrap; font-weight: 700; } .d3-line-simple .controls select { font-size: 12px; padding: 8px 28px 8px 10px; border: 1px solid var(--border-color);1 unmodified line 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; background-repeat: no-repeat; background-position: right 8px center; background-size: 12px; -webkit-appearance: none; appearance: none; cursor: pointer; transition: border-color .15s ease, box-shadow .15s ease; } [data-theme="dark"] .d3-line .d3-line__controls select { [data-theme="dark"] .d3-line-simple .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-simple .controls select:hover { border-color: var(--primary-color); } .d3-line-simple .controls select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(232,137,171,.25); outline: none; } .d3-line-simple .axis-label { fill: var(--text-color); font-size: 12px; font-weight: 700; } .d3-line-simple .axes path, .d3-line-simple .axes line { stroke: var(--axis-color); } .d3-line-simple .axes text { fill: var(--tick-color); } .d3-line-simple .grid line { stroke: var(--grid-color); } .d3-line-simple .legend { font-size: 12px; color: var(--text-color);padding-left: 6px; } .d3-line-simple .legend .items { display:flex; flex-wrap:wrap; gap:8px 12px; align-items:center; } .d3-line-simple .legend .item { display:flex; align-items:center; gap:6px; white-space:nowrap; } .d3-line-simple .legend .swatch { width:14px; height:14px; border-radius:3px; border:1px solid var(--border-color); display:inline-block; } /* Ghosting on hover */ .d3-line-simple.hovering .legend-bottom .item.ghost { opacity: .35; } .d3-line-simple.hovering .lines path.ghost { opacity: .25; } .d3-line-simple.hovering .points circle.ghost { opacity: .25; } .d3-line-simple.hovering .areas path.ghost { opacity: .08; } .d3-line-simple .chart-header { display:flex; align-items:center; justify-content:space-between; gap:12px; margin: 0 0 8px 0; flex-wrap: wrap; } .d3-line-simple .legend-bottom { display:flex; align-items:center; justify-content:flex-start; font-size:12px; color: var(--text-color); } .d3-line-simple .legend-bottom .items { display:flex; flex-wrap:wrap; gap:8px 14px; } .d3-line-simple .legend-bottom .item { display:inline-flex; align-items:center; gap:6px; white-space:nowrap; } .d3-line-simple .legend-bottom .swatch { width:14px; height:14px; border-radius:3px; border:1px solid var(--border-color); display:inline-block; } .d3-line-simple .lines path.active { stroke-width: 3; } /* Layout tweaks: stack label above select, add legend title above items */ .d3-line-simple .controls .control-group { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; } .d3-line .d3-line__controls input[type="range"]::-moz-range-track { height: 6px; background: transparent; border-radius: 999px; .d3-line-simple .legend-bottom { flex-direction: column; align-items: flex-start; gap: 6px; } .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; .d3-line-simple .legend-bottom .legend-title { font-size: 12px; font-weight: 700; color: var(--text-color); } /* Improved line color via CSS */ .d3-line .lines path.improved { stroke: var(--primary-color); } /* Tooltip styling aligned with filters-quad */ .d3-line-simple .d3-tooltip { z-index: var(--z-elevated); backdrop-filter: saturate(1.12) blur(8px); } .d3-line-simple .d3-tooltip__inner { display:flex; flex-direction:column; gap:6px; min-width: 220px; } .d3-line-simple .d3-tooltip__inner > div:first-child { font-weight: 800; letter-spacing: 0.1px; margin-bottom: 0; } .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; } .d3-line-simple .d3-tooltip__inner > div:nth-child(n+3) { padding-top: 6px; border-top: 1px solid var(--border-color); } .d3-line-simple .d3-tooltip__color-dot { display:inline-block; width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-color); } /* Chart card only around the SVG */ .d3-line-simple .chart-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; } /* Place header below chart and align start */ .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; }</style><script> (() => { // Pretty label mapping for metric keys (aligned with filters-quad) const prettyMetricLabel = (key) => { if (!key) return ''; const table = { 'ai2d_exact_match': 'AI2D Exact Match', 'average_rank': 'Average Rank', }; if (table[key]) return table[key]; const cleaned = String(key).replace(/[_-]+/g, ' ').trim(); return cleaned.split(/\s+/).map(w => { if (/^(ai2d|umap|id|auc|f1)$/i.test(w)) return w.toUpperCase(); return w.charAt(0).toUpperCase() + w.slice(1); }).join(' '); };
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); } 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(); s.addEventListener('load', onReady, { once: true }); if (window.d3) onReady(); };
const bootstrap = () => { const scriptEl = document.currentScript; let container = null;
// Prefer the closest previous sibling with class .d3-line (local instance) if (scriptEl) { let el = scriptEl.previousElementSibling; while (el && !(el.classList && el.classList.contains('d3-line'))) { el = el.previousElementSibling; } if (el) container = el; let container = scriptEl ? scriptEl.previousElementSibling : null; if (!(container && container.classList && container.classList.contains('d3-line-simple'))){ const cs = Array.from(document.querySelectorAll('.d3-line-simple')).filter(el => !(el.dataset && el.dataset.mounted === 'true')); container = cs[cs.length - 1] || null; }
// Fallback: pick the last unmounted .d3-line in the document if (!container) { const candidates = Array.from(document.querySelectorAll('.d3-line')) .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'; }
// CSV: prefer public path, fallback to relative const CSV_PATHS = [ '/data/against_baselines.csv', './assets/data/against_baselines.csv', '../assets/data/against_baselines.csv', '../../assets/data/against_baselines.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: against_baselines.csv'); }; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Controls UI // Controls (we will place them in a footer below the chart) 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%' });
controls.className = 'controls'; const controlGroup = document.createElement('div'); controlGroup.className = 'control-group'; const labelMetric = document.createElement('label'); Object.assign(labelMetric.style, { fontSize: '12px', color: 'var(--muted-color)', 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: '11px', marginLeft: '8px' }); controls.appendChild(legendInline); controls.appendChild(labelMetric);
// Create SVG const svg = d3.select(container).append('svg') .attr('width', '100%') .style('display', 'block');
// Groups const gRoot = svg.append('g'); const gGrid = gRoot.append('g').attr('class', 'grid'); const gAxes = gRoot.append('g').attr('class', 'axes'); 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'); // Associate label and select with a unique id const uniqueId = Math.random().toString(36).slice(2, 9); selectMetric.id = `metric-select-${uniqueId}`; labelMetric.setAttribute('for', selectMetric.id); controlGroup.appendChild(labelMetric); controlGroup.appendChild(selectMetric); controls.appendChild(controlGroup);
// Tooltip container.style.position = container.style.position || 'relative'; let tip = container.querySelector('.d3-tooltip'); let tipInner; let tip = container.querySelector('.d3-tooltip'); let tipInner; if (!tip) { tip = document.createElement('div'); tip.className = 'd3-tooltip'; 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' 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||[])];
// State and data let metricList = []; let runList = []; 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; }
// Header (legend + controls) placed after the chart const header = document.createElement('div'); header.className = 'chart-header'; const legendBottom = document.createElement('div'); legendBottom.className = 'legend-bottom'; header.appendChild(legendBottom); header.appendChild(controls);
// Chart card (SVG) const card = document.createElement('div'); card.className = 'chart-card'; container.appendChild(card); container.appendChild(header); // SVG const svg = d3.select(card).append('svg').attr('width','100%').style('display','block'); 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'); // (legend removed from inside SVG) const overlay = gRoot.append('rect').attr('fill','transparent').style('cursor','crosshair'); const hoverLine = gRoot.append('line').attr('stroke-width',1).style('display','none');
// State/data let width = 800, height = 480; const margin = { top: 16, right: 32, bottom: 44, left: 56 }; const xScale = d3.scaleLinear(); const yScale = d3.scaleLinear(); const lineGen = d3.line().x(d => xScale(d.step)).y(d => yScale(d.value)); const dataByMetric = new Map(); 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 const lineGenSmooth = d3.line() .curve(d3.curveCatmullRom.alpha(0.05)) .x((d) => xScale(d.step)) .y((d) => yScale(d.value)); const lineGenStep = d3.line() .curve(d3.curveStepAfter) .x((d) => xScale(d.step)) .y((d) => yScale(d.value));
// Hover elements const hoverLine = gHover.append('line').attr('stroke-width', 1);
const overlay = gHover.append('rect').attr('fill', 'transparent').style('cursor', 'crosshair');
// Responsive layout for controls and inline legend function applyResponsiveLayout(containerWidth) { const isNarrow = containerWidth <= 600; if (isNarrow) { controls.style.flexWrap = 'wrap'; controls.style.alignItems = 'flex-start'; controls.style.justifyContent = 'flex-start'; legendInline.style.flexWrap = 'wrap'; legendInline.style.rowGap = '4px'; labelMetric.style.marginLeft = '0'; labelMetric.style.flexBasis = '100%'; labelMetric.style.width = '100%'; } else { controls.style.flexWrap = 'nowrap'; controls.style.alignItems = 'center'; controls.style.justifyContent = 'space-between'; legendInline.style.flexWrap = 'nowrap'; labelMetric.style.marginLeft = 'auto'; labelMetric.style.flexBasis = 'auto'; labelMetric.style.width = 'auto'; // Colors function getRunColors(count){ try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') return window.ColorPalettes.getColors('categorical', count); } catch(_){} return d3.schemeTableau10 ? d3.schemeTableau10.slice(0, count) : ['#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f','#edc948','#b07aa1','#ff9da7','#9c755f','#bab0ab'].slice(0, count); } // Format helper for thousands (5000 -> 5k, 1500 -> 1.5k) function formatK(v){ const abs = Math.abs(v); if (abs >= 1000) { const n = v / 1000; const s = d3.format('.1f')(n); return (s.endsWith('.0') ? s.slice(0, -2) : s) + 'k'; } return d3.format('d')(v); }
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)'; // CSV: prefer public path, fallback to relative // Data file(s) from HtmlEmbed attribute (string or JSON array), else default cascade // Find the HtmlEmbed wrapper that carries data-datafiles let mountEl = container; while (mountEl && !mountEl.getAttribute?.('data-datafiles') && !mountEl.getAttribute?.('data-config')) { mountEl = mountEl.parentElement; } let providedData = null; let providedConfig = null; try { const attr = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-datafiles') : null; if (attr && attr.trim()) { providedData = attr.trim().startsWith('[') ? JSON.parse(attr) : attr.trim(); } } catch(_) {} try { const cfg = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-config') : null; if (cfg && cfg.trim()) { providedConfig = cfg.trim().startsWith('{') ? JSON.parse(cfg) : cfg; } } catch(_) {} const DEFAULT_CSV = '/data/formatting_filters.csv'; // Normalize: if a provided path has no slash, assume it lives under /data/ const ensureDataPrefix = (p) => { if (typeof p !== 'string' || !p) return p; return p.includes('/') ? p : `/data/${p}`; }; const normalizeInput = (inp) => Array.isArray(inp) ? inp.map(ensureDataPrefix) : (typeof inp === 'string' ? [ ensureDataPrefix(inp) ] : null); const CSV_PATHS = Array.isArray(providedData) ? normalizeInput(providedData) : (typeof providedData === 'string' ? normalizeInput(providedData) || [DEFAULT_CSV] : [ DEFAULT_CSV, './assets/data/formatting_filters.csv', '../assets/data/formatting_filters.csv', '../../assets/data/formatting_filters.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(_){} } throw new Error('CSV not found: formatting_filters.csv'); };
function updateLayout(){ const axisColor = getComputedStyle(container).getPropertyValue('--axis-color').trim() || 'rgba(0,0,0,0.25)'; width = container.clientWidth || 800; height = Math.max(260, Math.round(width / 3)); height = Math.max(280, Math.round(width / 3)); svg.attr('width', width).attr('height', height);
// Update controls layout for current width applyResponsiveLayout(width);
gRoot.attr('transform', `translate(${margin.left},${margin.top})`); const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; gRoot.attr('transform', `translate(${margin.left},${margin.top})`);
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); } overlay.attr('x',0).attr('y',0).attr('width', innerWidth).attr('height', innerHeight); hoverLine.attr('y1',0).attr('y2', innerHeight).attr('stroke', axisColor); return { innerWidth, innerHeight }; }
// Grid (horizontal) function render(metricKey){ const { innerWidth, innerHeight } = updateLayout(); const map = dataByMetric.get(metricKey) || {}; const runs = runOrder; // domains let minStep = Infinity, maxStep = -Infinity, minV = Infinity, maxV = -Infinity; 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); }); }); if (!isFinite(minStep) || !isFinite(maxStep)) return; xScale.domain([minStep, maxStep]).range([0, innerWidth]); yScale.domain([minV, maxV]).nice().range([innerHeight, 0]);
// grid 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'); gGrid.selectAll('line').data(yScale.ticks(6)).join('line') .attr('x1',0).attr('x2', innerWidth).attr('y1', d=>yScale(d)).attr('y2', d=>yScale(d)) .attr('stroke','var(--grid-color)').attr('stroke-width',1).attr('shape-rendering','crispEdges');
// Axes // axes gAxes.selectAll('*').remove(); let xAxis = d3.axisBottom(xScale).tickSizeOuter(0); const isNarrow = width <= 600; const formatK = (v) => { const vv = Math.round(v); if (isNarrow && Math.abs(vv) >= 1000) return `${Math.round(vv / 1000)}K`; return d3.format('d')(vv); }; 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(formatK); } else { xAxis = xAxis.ticks(8); if (isNarrow) { xAxis = xAxis.tickFormat((v) => (Math.abs(v) >= 1000 ? `${Math.round(v / 1000)}K` : d3.format('d')(Math.round(v)))); 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'); }); 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'); }); gAxes.append('text').attr('class','axis-label').attr('text-anchor','middle').attr('x', innerWidth/2).attr('y', innerHeight + 38).text('Step'); gAxes.append('text').attr('class','axis-label').attr('text-anchor','middle').attr('transform', `translate(${-44}, ${innerHeight/2}) rotate(-90)`).text('Value');
// shaded areas (stderr or min/max if provided) gAreas.selectAll('*').remove(); const areaGenClosed = d3.line().x(d=>d[0]).y(d=>d[1]).curve(d3.curveLinearClosed); // Colors (needed for both areas and lines) const colors = getRunColors(runs.length); const seriesForAreas = []; runs.forEach((r, i) => { const vals = (map[r]||[]).slice().sort((a,b)=>a.step-b.step); const withBounds = vals.map(v => { let lo = null, hi = null; if (v.stderr != null && isFinite(v.stderr) && v.stderr > 0) { lo = v.value - v.stderr; hi = v.value + v.stderr; } if (v.min != null && isFinite(v.min)) lo = (lo==null) ? v.min : lo; if (v.max != null && isFinite(v.max)) hi = (hi==null) ? v.max : hi; return { step: v.step, lo, hi }; }).filter(v => v.lo != null && v.hi != null && isFinite(v.lo) && isFinite(v.hi)); if (withBounds.length > 0) { seriesForAreas.push({ run: r, color: colors[i % colors.length], bounds: withBounds }); } } 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)' });
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); }); seriesForAreas.forEach(s => { const upper = s.bounds.map(d => [ xScale(d.step), yScale(d.hi) ]); const lower = s.bounds.slice().reverse().map(d => [ xScale(d.step), yScale(d.lo) ]); const coords = upper.concat(lower); gAreas.append('path') .attr('class','area') .attr('data-run', s.run) .attr('d', areaGenClosed(coords)) .attr('fill', s.color) .attr('opacity', 0.15) .attr('stroke','none'); }); 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([0, Math.max(1, maxVal)]).nice(); } isRankStrictFlag = isRankStrict;
const { innerWidth, innerHeight } = updateScales();
// Bind lines const series = runs.map((r, i) => ({ run: r, color: pool[i % pool.length], values: (map[r]||[]) .slice() .sort((a,b)=>a.step-b.step) .map(pt => isRankStrict ? { step: pt.step, value: Math.round(pt.value) } : pt) .filter(pt => !isRankStrict || (pt.step % 1000 === 0)) })); const paths = gLines.selectAll('path.run-line').data(series, d=>d.run); const gen = isRank ? lineGenStep : lineGenSmooth; 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=>gen(d.values)) .merge(paths) .transition().duration(200) .attr('stroke', d=>d.color) .attr('d', d=>gen(d.values)); // lines const series = runs.map((r, i) => ({ run:r, color: colors[i % colors.length], values: (map[r]||[]).slice().sort((a,b)=>a.step-b.step) })); const paths = gLines.selectAll('path.run').data(series, d=>d.run); 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)); pathsEnter.merge(paths).transition().duration(200).attr('stroke', d=>d.color).attr('d', d=>lineGen(d.values)); paths.exit().remove();
// No point markers for rank metrics (and none for others) gPoints.selectAll('*').remove();
// Inline legend content (row, right side) compact legendInline.innerHTML = series.map(s => `<span style="display:inline-flex;align-items:center;gap:6px;white-space:nowrap;"><span style="width:18px;height:10px;background:${s.color};border-radius:3px;display:inline-block"></span><span>${s.run}</span></span>`).join('');
// 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]); // Hover capture paths (wider invisible stroke for easy hover) const captures = gLines.selectAll('path.run-hover').data(series, d=>`cap-${d.run}`); captures.enter().append('path').attr('class','run-hover').attr('fill','none').attr('stroke','transparent').attr('stroke-width', 12).style('pointer-events','stroke') .attr('d', d=>lineGen(d.values)) .merge(captures) .attr('d', d=>lineGen(d.values)) .on('mouseenter', function(ev, d){ container.classList.add('hovering'); // ghost non hovered lines and points gLines.selectAll('path.run').classed('ghost', s => s.run !== d.run); gPoints.selectAll('circle.pt').classed('ghost', p => p.run !== d.run); gAreas.selectAll('path.area').classed('ghost', a => a && a.getAttribute && a.getAttribute('data-run') !== d.run); // ghost legend items try { const legendNode = legendBottom; if (legendNode) { legendNode.querySelectorAll('.item').forEach(el => { const name = el.getAttribute('data-run'); el.classList.toggle('ghost', name !== d.run); }); } } catch {} }) .on('mouseleave', function(){ container.classList.remove('hovering'); gLines.selectAll('path.run').classed('ghost', false); gPoints.selectAll('circle.pt').classed('ghost', false); gAreas.selectAll('path.area').classed('ghost', false); try { const legendNode = legendBottom; if (legendNode) legendNode.querySelectorAll('.item').forEach(el => el.classList.remove('ghost')); } catch {} }); captures.exit().remove();
// point markers (subtle) const allPts = series.flatMap(s => s.values.map(v => ({ run:s.run, color:s.color, step:v.step, value:v.value }))); const ptsSel = gPoints.selectAll('circle.pt').data(allPts, d=>`${d.run}-${d.step}`); ptsSel.enter().append('circle').attr('class','pt').attr('r', 2).attr('fill', d=>d.color).attr('fill-opacity', 0.6) .attr('cx', d=>xScale(d.step)).attr('cy', d=>yScale(d.value)) .merge(ptsSel).transition().duration(150).attr('cx', d=>xScale(d.step)).attr('cy', d=>yScale(d.value)); ptsSel.exit().remove();
// legend (HTML below, left) with title above items 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>`; // Legend hover → ghost lines/points try { const legendNode = legendBottom; legendNode.querySelectorAll('.item').forEach(el => { el.addEventListener('mouseenter', () => { const run = el.getAttribute('data-run'); if (!run) return; container.classList.add('hovering'); gLines.selectAll('path.run').classed('ghost', s => s.run !== run); gPoints.selectAll('circle.pt').classed('ghost', p => p.run !== run); gAreas.selectAll('path.area').classed('ghost', a => a && a.getAttribute && a.getAttribute('data-run') !== run); legendNode.querySelectorAll('.item').forEach(it => it.classList.toggle('ghost', it.getAttribute('data-run') !== run)); }); el.addEventListener('mouseleave', () => { container.classList.remove('hovering'); gLines.selectAll('path.run').classed('ghost', false); gPoints.selectAll('circle.pt').classed('ghost', false); gAreas.selectAll('path.area').classed('ghost', false); legendNode.querySelectorAll('.item').forEach(it => it.classList.remove('ghost')); }); }); } catch {}
// hover function onMove(ev){ const [mx, my] = d3.pointer(ev, overlay.node()); const sx = xScale.invert(mx); // nearest integer step if steps are integers; else nearest by distance const steps = Array.from(new Set(allPts.map(p=>p.step))).sort((a,b)=>a-b); const nearest = steps.reduce((best, s) => Math.abs(s - sx) < Math.abs(best - sx) ? s : best, steps[0]); const xpx = xScale(nearest); hoverLine.attr('x1', xpx).attr('x2', xpx).style('display', null).attr('stroke', 'rgba(0,0,0,0.25)'); // Tooltip content let html = `<div><strong>${metricKey}</strong></div><div><strong>step</strong> ${nearest}</div>`; series.forEach(s=>{ hoverLine.style('display', null).attr('x1', xpx).attr('x2', xpx); // tooltip content (styled) 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>`; const entries = series.map(s => { const m = new Map(s.values.map(v=>[v.step, v.value])); const val = m.has(nearest) ? m.get(nearest) : null; if (val != null) { const formatVal = (vv) => (isRankStrict ? d3.format('d')(vv) : (+vv).toFixed(4)); html += `<div><span style=\"display:inline-block;width:10px;height:10px;background:${s.color};border-radius:50%;margin-right:6px;\"></span><strong>${s.run}</strong> ${formatVal(val)}</div>`; } const val = m.get(nearest); return { run: s.run, color: s.color, val }; }).filter(e => e.val != null); entries.sort((a, b) => a.val - b.val); entries.forEach(e => { 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>`; }); 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)`; 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)`; } 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 // load CSV and init (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 })); metricList = Array.from(new Set(rows.map(r=>r.metric))).sort(); runList = Array.from(new Set(rows.map(r=>r.run))).sort(); runOrder = 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 }); }); const rows = d3.csvParse(text, d => ({ run:(d.run||'').trim(), step:+d.step, metric:(d.metric||'').trim(), value:+d.value, // Optional bounds: stderr or [min,max] or [lower,upper] stderr: (d.stderr!=null && d.stderr!=='') ? +d.stderr : null, min: (d.min!=null && d.min!=='') ? +d.min : (d.lower!=null && d.lower!=='') ? +d.lower : null, max: (d.max!=null && d.max!=='') ? +d.max : (d.upper!=null && d.upper!=='') ? +d.upper : null })); const metrics = Array.from(new Set(rows.map(r=>r.metric))).sort(); runOrder = Array.from(new Set(rows.map(r=>r.run))).sort(); metrics.forEach(m => { const map = {}; runOrder.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, min: r.min, max: r.max }); }); dataByMetric.set(m, map); }); // populate metric select (pretty labels) or hide if single-file with single metric const isSingleFile = !Array.isArray(providedData) && typeof providedData === 'string'; metrics.forEach(m => { const o = document.createElement('option'); o.value=m; o.textContent=prettyMetricLabel(m); selectMetric.appendChild(o); }); // default metric selection via config.defaultMetric (match raw key or pretty label, case-insensitive) if (metrics.length) { let initial = metrics[0]; const desired = providedConfig && typeof providedConfig === 'object' && providedConfig.defaultMetric ? String(providedConfig.defaultMetric) : null; if (desired) { const lcDesired = desired.toLowerCase(); const byKey = metrics.find(m => m.toLowerCase() === lcDesired); const byPretty = metrics.find(m => prettyMetricLabel(m).toLowerCase() === lcDesired); initial = byKey || byPretty || initial; } selectMetric.value = initial; } if (isSingleFile && metrics.length <= 1) { controls.style.display = 'none'; }
// Populate metric select (default to average_rank if present) metricList.forEach((m)=>{ const o=document.createElement('option'); o.value=m; o.textContent=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); } render(selectMetric.value); selectMetric.addEventListener('change', () => render(selectMetric.value)); const rerender = () => render(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); 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); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515<div class="d3-matrix" ></div><style> .d3-matrix { position: relative; } .d3-matrix .panels { display: flex; flex-wrap: wrap; gap: 16px; margin-bottom: 4px; } .d3-matrix .panel { flex: 1 1 320px; min-width: 280px; } .d3-matrix .panel__title { color: var(--text-color); font-size: 12px; line-height: 1.35; margin: 0 0 6px 0; font-weight: 600; } .d3-matrix .axis-label { fill: var(--text-color); font-size: 11px; font-weight: 700; } .d3-matrix .cell-border { stroke: var(--border-color); stroke-width: 1px; fill: none; } .d3-matrix .cell-text { fill: var(--muted-color); font-size: 11px; pointer-events: none; } .d3-matrix .chart-card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px; }</style><script> (() => { // Load D3 from CDN once 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-matrix'))){ const cs = Array.from(document.querySelectorAll('.d3-matrix')).filter(el => !(el.dataset && el.dataset.mounted === 'true')); container = cs[cs.length - 1] || null; } if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Tooltip (HTML, single instance inside container) 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; }
// Panels container (two side-by-side matrices) const panels = document.createElement('div'); panels.className = 'panels'; const panelA = document.createElement('div'); panelA.className = 'panel'; const titleA = document.createElement('div'); titleA.className = 'panel__title'; titleA.textContent = 'Baseline (row-normalized %)'; panelA.appendChild(titleA); const mountA = document.createElement('div'); panelA.appendChild(mountA); const panelB = document.createElement('div'); panelB.className = 'panel'; const titleB = document.createElement('div'); titleB.className = 'panel__title'; titleB.textContent = 'Delta (Improved − Baseline, pp)'; panelB.appendChild(titleB); const mountB = document.createElement('div'); panelB.appendChild(mountB); panels.appendChild(panelA); panels.appendChild(panelB); container.appendChild(panels);
// SVG scaffolding const cardA = document.createElement('div'); cardA.className = 'chart-card'; mountA.appendChild(cardA); const svgA = d3.select(cardA).append('svg').attr('width', '100%').style('display', 'block'); const gRootA = svgA.append('g'); const gCellsA = gRootA.append('g'); const gAxesA = gRootA.append('g'); const cardB = document.createElement('div'); cardB.className = 'chart-card'; mountB.appendChild(cardB); const svgB = d3.select(cardB).append('svg').attr('width', '100%').style('display', 'block'); const gRootB = svgB.append('g'); const gCellsB = gRootB.append('g'); const gAxesB = gRootB.append('g');
// Demo data (two distinct 10x10 matrices: Baseline vs Improved) // Rows / Columns are generic class labels const classes = ['0','1','2','3','4','5','6','7','8','9']; const matrixA = [ [90, 2, 1, 0, 0, 0, 1, 0, 5, 1], [ 3, 85, 5, 1, 0, 1, 2, 1, 1, 1], [ 1, 6, 70, 10, 4, 4, 1, 1, 1, 2], [ 0, 1, 8, 65, 10, 10, 2, 1, 1, 2], [ 0, 0, 2, 6, 83, 3, 1, 1, 3, 1], [ 0, 1, 2, 12, 4, 70, 5, 2, 2, 2], [ 1, 2, 1, 0, 1, 2, 88, 1, 3, 1], [ 0, 1, 1, 1, 1, 1, 2, 90, 1, 2], [ 6, 2, 2, 4, 6, 3, 3, 2, 70, 2], [ 1, 1, 1, 1, 2, 1, 1, 2, 1, 89] ]; const matrixB = [ [94, 1, 0, 0, 0, 0, 1, 0, 3, 1], [ 2, 90, 3, 1, 0, 0, 1, 1, 1, 1], [ 1, 4, 78, 7, 3, 3, 1, 1, 1, 1], [ 0, 1, 5, 74, 7, 8, 1, 1, 1, 2], [ 0, 0, 1, 4, 88, 2, 1, 1, 2, 1], [ 0, 1, 1, 9, 3, 78, 3, 1, 2, 2], [ 1, 1, 1, 0, 1, 1, 91, 1, 2, 1], [ 0, 1, 1, 1, 1, 1, 1, 92, 1, 1], [ 4, 1, 1, 3, 4, 2, 2, 2, 79, 2], [ 1, 1, 1, 1, 2, 1, 1, 1, 1, 90] ];
// Colors: sequential palette via window.ColorPalettes with graceful fallback const getSequentialColors = (count) => { try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') { return window.ColorPalettes.getColors('sequential', count); } } catch (_) {} // Fallback: generate a monochrome scale using the primary color with varying opacity const arr = []; for (let i = 0; i < count; i++) arr.push('var(--primary-color)'); return arr; };
const palette = getSequentialColors(13); const getDivergingColors = (count) => { try { if (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function') { return window.ColorPalettes.getColors('diverging', count); } } catch (_) {} const steps = Math.max(3, count|0); const arr = []; for (let i = 0; i < steps; i++) { const t = i / (steps - 1); const pct = Math.round(t * 100); arr.push(`color-mix(in srgb, #D64545 ${100-pct}%, #3A7BD5 ${pct}%)`); } return arr; };
let width = 800; let height = 480; const margin = { top: 36, right: 24, bottom: 26, left: 56 };
function updateSize() { const isDark = document.documentElement.getAttribute('data-theme') === 'dark'; width = container.clientWidth || 800; const gap = 16; // matches CSS .panels gap const minPanel = 320; const nCols = (width >= (minPanel * 2 + gap)) ? 2 : 1; const panelWidth = nCols === 2 ? Math.max(minPanel, Math.floor((width - gap) / 2)) : Math.max(minPanel, width); const base = Math.max(minPanel, Math.round(panelWidth * 0.92)); height = base; // Responsive SVG: width 100%, height auto, preserve aspect via viewBox svgA .attr('viewBox', `0 0 ${panelWidth} ${height}`) .attr('preserveAspectRatio', 'xMidYMid meet') .style('width', '100%') .style('height', 'auto'); svgB .attr('viewBox', `0 0 ${panelWidth} ${height}`) .attr('preserveAspectRatio', 'xMidYMid meet') .style('width', '100%') .style('height', 'auto'); gRootA.attr('transform', `translate(${margin.left},${margin.top})`); gRootB.attr('transform', `translate(${margin.left},${margin.top})`); const innerWidth = panelWidth - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; return { innerWidth, innerHeight, isDark }; }
function computeValues(normalization, matrix) { const n = classes.length; const totalsByRow = matrix.map(row => row.reduce((a, b) => a + b, 0)); const flat = []; let minV = Infinity, maxV = -Infinity; for (let r = 0; r < n; r++) { for (let c = 0; c < n; c++) { const count = matrix[r][c]; const value = normalization === 'row' ? (totalsByRow[r] ? count / totalsByRow[r] : 0) : count; if (value < minV) minV = value; if (value > maxV) maxV = value; flat.push({ r, c, count, value }); } } return { data: flat, minV, maxV }; }
function getColorScale(values, minV, maxV) { // If ColorPalettes is available, use quantiles to enhance visual variation across the distribution const hasPalette = !(palette.length === 0); if (hasPalette && (window.ColorPalettes && typeof window.ColorPalettes.getColors === 'function')) { const scale = d3.scaleQuantile().domain(values).range(palette); return (v) => scale(v); } // Fallback: primary color with opacity mapped to normalized value const norm = d3.scaleLinear().domain([minV, maxV]).range([0.08, 0.9]).clamp(true); return (v) => `color-mix(in oklab, var(--primary-color) ${Math.round(norm(v) * 100)}%, var(--surface-bg))`; }
// Compute a fixed readable text color from a CSS rgb()/rgba() string function chooseFixedReadableTextOnBg(bgCss){ try { const m = String(bgCss||'').match(/rgba?\(([^)]+)\)/); if (!m) return '#0e1116'; const parts = m[1].split(',').map(s => parseFloat(s.trim())); const [r, g, b] = parts; // sRGB → relative luminance const srgb = [r, g, b].map(v => Math.max(0, Math.min(255, v)) / 255); const linear = srgb.map(c => (c <= 0.03928 ? c/12.92 : Math.pow((c + 0.055)/1.055, 2.4))); const L = 0.2126*linear[0] + 0.7152*linear[1] + 0.0722*linear[2]; // Threshold ~ 0.5 for readability; darker BG → white text, else near-black return L < 0.5 ? '#ffffff' : '#0e1116'; } catch(_) { return '#0e1116'; } }
function render() { const { innerWidth, innerHeight } = updateSize(); const n = classes.length; const gridSize = Math.min(innerWidth, innerHeight); const cellSize = gridSize / n;
const x = d3.scaleBand().domain(d3.range(n)).range([0, gridSize]).paddingInner(0.06); const y = d3.scaleBand().domain(d3.range(n)).range([0, gridSize]).paddingInner(0.06);
// Panel A: Baseline (row-normalized) const dataA = computeValues('row', matrixA); const colorA = getColorScale(dataA.data.map(d => d.value), dataA.minV, dataA.maxV);
gCellsA.selectAll('rect.cell-bg') .data([0]) .join('rect') .attr('class', 'cell-bg') .attr('x', 0) .attr('y', 0) .attr('width', gridSize) .attr('height', gridSize) .attr('fill', 'none') .attr('stroke', 'var(--border-color)') .attr('stroke-width', 1);
const cellsA = gCellsA.selectAll('g.cell') .data(dataA.data, d => `${d.r}-${d.c}-A`);
const cellsEnterA = cellsA.enter() .append('g') .attr('class', 'cell');
cellsEnterA.append('rect') .attr('rx', 2) .attr('ry', 2) .on('mousemove', (event, d) => { const [px, py] = d3.pointer(event, container); tipInner.innerHTML = `<strong>${classes[d.r]}</strong> → <strong>${classes[d.c]}</strong><br/>${(d.value * 100).toFixed(1)}% (${d.count})`; tip.style.transform = `translate(${px + 10}px, ${py + 10}px)`; tip.style.opacity = '1'; }) .on('mouseleave', () => { tip.style.opacity = '0'; });
cellsEnterA.append('text') .attr('class', 'cell-text') .attr('text-anchor', 'middle') .attr('dominant-baseline', 'middle');
const cellsMergedA = cellsEnterA.merge(cellsA);
cellsMergedA.select('text') .attr('x', d => x(d.c) + x.bandwidth() / 2) .attr('y', d => y(d.r) + y.bandwidth() / 2) .text(d => `${Math.round(d.value * 100)}`) .style('fill', function(d){ try { const rect = this && this.parentNode ? this.parentNode.querySelector('rect') : null; const bg = rect ? getComputedStyle(rect).fill : colorA(d.value); return chooseFixedReadableTextOnBg(bg); } catch (_) { return '#0e1116'; } });
cellsMergedA.select('rect') .attr('x', d => x(d.c)) .attr('y', d => y(d.r)) .attr('width', Math.max(1, x.bandwidth())) .attr('height', Math.max(1, y.bandwidth())) .attr('fill', d => colorA(d.value));
cellsA.exit().remove();
gAxesA.selectAll('*').remove();
gAxesA.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', (_, i) => x(i) + x.bandwidth() / 2) .attr('y', -8) .text(d => d);
gAxesA.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'end') .attr('x', -8) .attr('y', (_, i) => y(i) + y.bandwidth() / 2) .attr('dominant-baseline', 'middle') .text(d => d);
gAxesA.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', gridSize / 2) .attr('y', innerHeight + 20) .text('Columns');
gAxesA.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('transform', `translate(${-40}, ${gridSize / 2}) rotate(-90)`) .text('Rows');
// Panel B: Delta (Improved �� Baseline), row-normalized differences in percentage points const dataB = computeValues('row', matrixB); const diverging = getDivergingColors(13); // Build delta values aligned to A's ordering const mapA = new Map(dataA.data.map(d => [d.r + '-' + d.c, d.value])); const delta = dataB.data.map(d => ({ r: d.r, c: d.c, count: d.count, value: (d.value - (mapA.get(d.r + '-' + d.c) || 0)) })); // Symmetric domain around 0 (in proportions), express later as pp in labels const maxAbsDelta = Math.max(0.01, d3.max(delta, d => Math.abs(d.value)) || 0.01); const colorB = d3.scaleQuantize().domain([-maxAbsDelta, maxAbsDelta]).range(diverging);
gCellsB.selectAll('rect.cell-bg') .data([0]) .join('rect') .attr('class', 'cell-bg') .attr('x', 0) .attr('y', 0) .attr('width', gridSize) .attr('height', gridSize) .attr('fill', 'none') .attr('stroke', 'var(--border-color)') .attr('stroke-width', 1);
const cellsB = gCellsB.selectAll('g.cell') .data(dataB.data, d => `${d.r}-${d.c}-B`);
const cellsEnterB = cellsB.enter() .append('g') .attr('class', 'cell');
cellsEnterB.append('rect') .attr('rx', 2) .attr('ry', 2) .on('mousemove', (event, d) => { const [px, py] = d3.pointer(event, container); const a = dataA.data.find(x => x.r===d.r && x.c===d.c); const b = dataB.data.find(x => x.r===d.r && x.c===d.c); const dv = ((b ? b.value : 0) - (a ? a.value : 0)) * 100; tipInner.innerHTML = `<strong>${classes[d.r]}</strong> → <strong>${classes[d.c]}</strong>` + `<br/>baseline ${(a ? a.value*100 : 0).toFixed(1)}%` + `<br/>improved ${(b ? b.value*100 : 0).toFixed(1)}%` + `<br/>delta ${dv.toFixed(1)} pp`; tip.style.transform = `translate(${px + 10}px, ${py + 10}px)`; tip.style.opacity = '1'; }) .on('mouseleave', () => { tip.style.opacity = '0'; });
cellsEnterB.append('text') .attr('class', 'cell-text') .attr('text-anchor', 'middle') .attr('dominant-baseline', 'middle');
const cellsMergedB = cellsEnterB.merge(cellsB);
cellsMergedB.select('rect') .attr('x', d => x(d.c)) .attr('y', d => y(d.r)) .attr('width', Math.max(1, x.bandwidth())) .attr('height', Math.max(1, y.bandwidth())) .attr('fill', d => colorB(delta.find(x => x.r===d.r && x.c===d.c).value));
cellsMergedB.select('text') .attr('x', d => x(d.c) + x.bandwidth() / 2) .attr('y', d => y(d.r) + y.bandwidth() / 2) .text(d => { const dv = delta.find(x => x.r===d.r && x.c===d.c).value; return `${Math.round(dv * 100)}`; }) .style('fill', function(d){ try { const rect = this && this.parentNode ? this.parentNode.querySelector('rect') : null; const dv = delta.find(x => x.r===d.r && x.c===d.c).value; const bg = rect ? getComputedStyle(rect).fill : colorB(dv); return chooseFixedReadableTextOnBg(bg); } catch (_) { return '#0e1116'; } });
cellsB.exit().remove();
gAxesB.selectAll('*').remove();
gAxesB.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', (_, i) => x(i) + x.bandwidth() / 2) .attr('y', -8) .text(d => d);
gAxesB.append('g') .selectAll('text') .data(classes) .join('text') .attr('class', 'axis-label') .attr('text-anchor', 'end') .attr('x', -8) .attr('y', (_, i) => y(i) + y.bandwidth() / 2) .attr('dominant-baseline', 'middle') .text(d => d);
gAxesB.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('x', gridSize / 2) .attr('y', innerHeight + 20) .text('Columns');
gAxesB.append('text') .attr('class', 'axis-label') .attr('text-anchor', 'middle') .attr('transform', `translate(${-40}, ${gridSize / 2}) rotate(-90)`) .text('Rows'); }
// Initial render + resize handling render(); const rerender = () => render(); if (window.ResizeObserver) { const ro = new ResizeObserver(() => rerender()); ro.observe(container); } else { window.addEventListener('resize', rerender); } };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
11234566787891011121314151617181920214 unmodified lines26272819293031323321 unmodified lines55565758596061626364656652676869706 unmodified lines777879808182838410 unmodified lines95969798991001013 unmodified lines10510610790108109110111145 unmodified lines2572582592422602612622632462472642652662672682692702713 unmodified lines2752762772582592602612622632782792802812822832842852862872662882682692702712722732742892902912922932942772782952962972982993003013023033043053063073083093103113123133143153163173183193206 unmodified lines3273283292953303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843043853863873883893903913923073083093103113933943953963973983994004014024034043164054064074084093194104114124134144154164174184194204214224234244254264274284294304314324334344354364374384 unmodified lines4434444453333344464474484494504514524531 unmodified line4554564573424584593443454604614624634644654664674684693484704714724734744754764774783523533543553563574794803604814823624834844854864873654884894904914923 unmodified lines4964974984993755005015025035045055065075085095105115125 unmodified lines5185195203885215223903913923935235245255265275285295305315325335345355365375383965395403983994004015415425435445455465475485495505515525535545555565575585594034045605615625635644084094104114124134145655665675685695705715724195735744214224234244254264275755765775785795805815825835845855865875885895905915925935945955965975985996006016026036 unmodified lines61061161261361461561661750 unmodified lines6686696706716726736748 unmodified lines683684685514686687688689690691692693<div class="d3-neural" style="width:100%;margin:10px 0;"></div><div class="d3-neural"></div><style> .d3-neural { position: relative; width:100%;margin:0;} .d3-neural .controls { margin-top: 12px; display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } .d3-neural .controls label { font-size: 12px; color: var(--muted-color); display: flex; align-items: center; gap: 8px; white-space: nowrap; padding: 6px 10px; } .d3-neural .controls input[type="range"]{ width: 160px; } .d3-neural .panel { display:flex; gap:16px; align-items:center; } .d3-neural .left { flex: 0 0 320px; display:flex; flex-direction:column; gap:8px; } .d3-neural .right { flex: 1 1 auto; min-width: 0; } .d3-neural .panel { display:flex; gap:8px; align-items:stretch; flex-wrap: nowrap; } .d3-neural .left { flex: 0 0 33.333%; max-width: 33.333%; min-width: 160px; display:flex; flex-direction:column; gap:8px; } .d3-neural .right { flex: 1 1 66.666%; max-width: 66.666%; min-width: 280px; display:flex; } .d3-neural .right > svg { flex: 1 1 auto; height: 100%; } .d3-neural .arrow-sep { flex: 0 0 18px; max-width: 18px; display:flex; align-items:center; justify-content:center; color: var(--muted-color); } .d3-neural .arrow-sep svg { display:block; width: 16px; height: 16px; } @media (max-width: 800px) { .d3-neural .panel { flex-direction: column; } .d3-neural .left, .d3-neural .right { flex: 0 0 100%; max-width: 100%; min-width: 0; } .d3-neural .arrow-sep { display: none; } } .d3-neural canvas { width: 100%; height: auto; border-radius: 8px; border: 1px solid var(--border-color); background: var(--surface-bg); display:block; } .d3-neural .preview28 { display:grid; grid-template-columns: repeat(28, 1fr); gap: 1px; width: 100%; } .d3-neural .preview28 span { display:block; aspect-ratio:1/1; border-radius:2px; }4 unmodified lines .d3-neural .probs .tick { font-size: 10px; color: var(--muted-color); text-align:center; margin-top: 2px; } .d3-neural .canvas-wrap { position: relative; } .d3-neural .erase-btn { position: absolute; top: 8px; right: 8px; width: 32px; height: 32px; display:flex; align-items:center; justify-content:center; border: 1px solid var(--border-color); } .d3-neural .canvas-hint { position: absolute; top: 8px; left: 12px; font-size: 12px; font-weight: 700; color: rgb(156, 156, 156); pointer-events: none; } .d3-neural .canvas-hint { position: absolute; top: 8px; left: 12px; font-size: 12px; font-weight: 700; color: rgba(0,0,0,.9); pointer-events: none; transition: opacity .12s ease; } </style><script> (() => {21 unmodified lines if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// (tooltip removed)
// Layout: left (canvas + preview + controls), right (svg network) const panel = document.createElement('div'); panel.className = 'panel'; const left = document.createElement('div'); left.className = 'left'; const arrowSep = document.createElement('div'); arrowSep.className = 'arrow-sep'; arrowSep.innerHTML = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><line x1="3" y1="12" x2="19" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><polyline points="17,7 22,12 17,17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'; const right = document.createElement('div'); right.className = 'right'; panel.appendChild(left); panel.appendChild(right); panel.appendChild(left); panel.appendChild(arrowSep); panel.appendChild(right); container.appendChild(panel);
// Canvas for drawing6 unmodified lines canvasWrap.appendChild(canvas); // Erase icon button (top-right) const eraseBtn = document.createElement('button'); eraseBtn.className='erase-btn button--ghost'; eraseBtn.type='button'; eraseBtn.setAttribute('aria-label','Clear'); // Hidden until the user interacts with the canvas eraseBtn.style.display = 'none'; eraseBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path><path d="M10 11v6"></path><path d="M14 11v6"></path><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"></path></svg>'; eraseBtn.addEventListener('click', () => clearCanvas()); canvasWrap.appendChild(eraseBtn);10 unmodified lines
// SVG network on right const svg = d3.select(right).append('svg').attr('width','100%').style('display','block'); const defs = svg.append('defs'); const gRoot = svg.append('g'); const gInput = gRoot.append('g').attr('class','input'); const gInputLinks = gRoot.append('g').attr('class','input-links');3 unmodified lines const gOutText = gRoot.append('g').attr('class','out-probs');
// Network structure (compact: 8 -> 8 -> 10) const layerSizes = [8, 8, 10]; const layerSizes = [8, 8, 8]; const layers = layerSizes.map((n, li)=> Array.from({length:n}, (_, i)=>({ id:`L${li}N${i}`, layer: li, index: i, a:0 }))); // Links only between hidden->hidden and hidden->output const links = [];145 unmodified lines function dot(a,b){ let s=0; for (let i=0;i<a.length;i++) s+=a[i]*b[i]; return s; }
// Resize handling and node layout let width=800, height=360; const margin = { top: 16, right: 24, bottom: 24, left: 24 }; let width=640, height=360; const margin = { top: 16, right: 8, bottom: 24, left: 8 }; let inputGrid = { cell: 0, x: 0, y: 0, width: 0, height: 0 }; function layoutNodes(){ // Right panel width, and a non-square aspect ratio for clarity width = Math.max(300, Math.round(right.clientWidth || 800)); height = Math.max(260, Math.round(width * 0.45)); width = Math.max(280, Math.round(right.clientWidth || 640)); height = Math.max(260, Math.round(width * 0.56)); svg.attr('width', width).attr('height', height); // Match canvas height to SVG height so both columns align vertically try { canvas.style.height = '100%'; canvasWrap.style.height = height + 'px'; } catch(_) {} const innerW = width - margin.left - margin.right; const innerH = height - margin.top - margin.bottom; gRoot.attr('transform', `translate(${margin.left},${margin.top})`); // Input grid layout (28x28) at left — cap width to a fraction of innerW3 unmodified lines let cell = Math.max(3, Math.min(cellByHeight, cellByWidth)); let gridH = cell * 28; let gridY = Math.floor((innerH - gridH)/2); inputGrid = { cell, x: 0, y: gridY, width: cell*28, height: gridH }; // Ensure there is always space for layers to the right const minRightPad = 40; // minimal free space at right let startX = inputGrid.width + 24; if (startX > innerW - minRightPad) { // Shrink grid to free horizontal room cell = Math.max(3, Math.floor((innerW - minRightPad - 24) / 28)); // Equal horizontal gaps: grid -> L0 -> L1 -> L2 const nLayers = layerSizes.length; // 3 const rightLabelPad = 36; // smaller pad; use more width for spreading layers const minGap = 28; const maxGap = 260; // Ensure enough free space; shrink grid if needed const desiredMinFree = rightLabelPad + nLayers * minGap; // 3 equal gaps if (inputGrid.width + desiredMinFree > innerW) { cell = Math.max(3, Math.floor((innerW - desiredMinFree) / 28)); gridH = cell * 28; gridY = Math.floor((innerH - gridH)/2); inputGrid = { cell, x: 0, y: gridY, width: cell*28, height: gridH }; startX = inputGrid.width + 24; } const nLayers = layerSizes.length; // Reserve space at right for output labels/bars so they don't get cut off const rightLabelPad = 100; // px reserved for digit label + bar const availableW = Math.max(100, innerW - startX - rightLabelPad); // Reduce inter-layer spacing slightly; keep a sane min/max const stepX = nLayers > 1 ? Math.min(200, Math.max(28, availableW / (nLayers - 1))) : 0; const xs = Array.from({ length: nLayers }, (_, li) => startX + stepX * li); const gridRight = inputGrid.x + inputGrid.width; const freeW = Math.max(nLayers * minGap, innerW - gridRight - rightLabelPad); const gapX = Math.min(maxGap, Math.max(minGap, Math.floor(freeW / nLayers))); const xs = Array.from({ length: nLayers }, (_, li) => gridRight + gapX * (li + 1)); // Y positions evenly spaced per layer layers.forEach((nodes, li)=>{ const n = nodes.length; const spacing = innerH/(n+1); nodes.forEach((nd, i)=>{ nd.x = xs[li]; nd.y = spacing*(i+1); }); const n = nodes.length; if (n <= 1) { nodes.forEach((nd)=>{ nd.x = xs[li]; nd.y = innerH/2; }); } else { const occupancy = 0.9; // use 90% of vertical space const span = innerH * occupancy; const topPad = (innerH - span) / 2; const spacing = span / (n - 1); nodes.forEach((nd, i)=>{ nd.x = xs[li]; nd.y = topPad + i*spacing; }); } }); }
let lastX28 = new Float32Array(28*28); function nodeRadiusForNode(n){ const a = Math.max(0, Math.min(1, (n && typeof n.a === 'number') ? n.a : 0)); if (n && n.layer === 2) { // Output nodes: variable radius based on activation return 8 + 10 * a; // ~8–18 } // Hidden/feature nodes: variable radius based on activation return 5 + 5 * a; // ~5–10 } function renderInputGrid(){ if (!inputGrid || inputGrid.cell <= 0) return; const data = Array.from({ length: 28*28 }, (_, i) => ({ i, v: lastX28[i] || 0 }));6 unmodified lines .merge(sel) .attr('x', d => inputGrid.x + (d.i % 28) * inputGrid.cell + offset) .attr('y', d => inputGrid.y + Math.floor(d.i / 28) * inputGrid.cell + offset) .attr('fill', d => { const g = 255 - Math.round(d.v * 255); return `rgb(${g},${g},${g})`; }) .attr('fill', d => { // Increase perceived contrast of the input grid by applying a gamma curve const k = Math.pow(Math.max(0, Math.min(1, d.v)), 0.6); // gamma < 1 → darker darks const g = 255 - Math.round(k * 255); return `rgb(${g},${g},${g})`; }) .attr('stroke', 'none'); sel.exit().remove();
// Border around the input grid area const borderSel = gInput.selectAll('rect.input-border').data([0]); borderSel.enter().append('rect').attr('class','input-border') .attr('fill','none') .attr('rx', 0).attr('ry', 0) .attr('stroke','var(--text-color)') .attr('stroke-opacity', 0.25) .attr('stroke-width', 1) .lower() .merge(borderSel) .attr('x', inputGrid.x-1) .attr('y', inputGrid.y-1) .attr('width', inputGrid.width+1) .attr('height', inputGrid.height+1);
// Centered label above the input grid const labelSel = gInput.selectAll('text.input-label').data([0]); labelSel.enter().append('text').attr('class','input-label') .attr('text-anchor','middle') .style('font-size','12px') .style('font-weight','700') .style('fill','var(--muted-color)') .merge(labelSel) .attr('x', inputGrid.x + inputGrid.width / 2) .attr('y', Math.max(12, inputGrid.y - 10)) .text('Input 28×28'); }
// Compute link path between two layered nodes using their current radii function computeLinkD(d){ const s = layers[d.s.l][d.s.i]; const t = layers[d.t.l][d.t.j]; if (!s || !t) return ''; const rs = nodeRadiusForNode(s); const rt = nodeRadiusForNode(t); // Use fixed anchors on circle edges for all inter-layer links (except grid->L0 handled elsewhere) const x1 = s.x + rs, y1 = s.y; // right edge of source circle const x2 = t.x - rt, y2 = t.y; // left edge of target circle const dx = (x2 - x1) * 0.45; return `M${x1},${y1} C${x1+dx},${y1} ${x2-dx},${y2} ${x2},${y2}`; }
function renderInputLinks(){ // Draw bundle-like links from input grid right edge to first layer nodes (features) const firstLayer = layers[0]; if (!firstLayer || !inputGrid || inputGrid.cell <= 0) { gInputLinks.selectAll('path').remove(); return; } const innerH = height - margin.top - margin.bottom; const x0 = inputGrid.x + inputGrid.width; // Define a centered vertical band (half grid height) and distribute sources evenly const k = firstLayer.length; const band = inputGrid.height * 0.5; const centerY = inputGrid.y + inputGrid.height / 2; const yStart = centerY - band / 2; const spacing = k > 1 ? band / (k - 1) : 0; const paths = firstLayer.map((n, idx) => { const yTarget = n.y; // source y roughly aligned to node y, clamped within the grid const y0 = Math.max(inputGrid.y, Math.min(inputGrid.y + inputGrid.height, yTarget)); const dx = (n.x - x0) * 0.35; return { x0, y0, x1: n.x - 12, y1: yTarget, c1x: x0 + dx, c1y: y0, c2x: n.x - dx, c2y: yTarget }; // source y from centered band, equidistant const y0 = k > 1 ? (yStart + idx * spacing) : centerY; // Target anchor: center of left edge of the node circle const r = nodeRadiusForNode(n); const x1 = n.x - r; const y1 = n.y; const dx = (x1 - x0) * 0.35; return { x0, y0, x1, y1, c1x: x0 + dx, c1y: y0, c2x: x1 - dx, c2y: y1, idx }; }); const sel = gInputLinks.selectAll('path.input-link').data(paths); sel.enter().append('path').attr('class','input-link') .attr('fill','none') .attr('stroke','rgba(0,0,0,0.25)') .attr('stroke','var(--text-color)') .attr('stroke-opacity', 0.25) .attr('stroke-width', 1) .attr('stroke-linecap','round') .merge(sel) .attr('d', d => `M${d.x0},${d.y0} C${d.c1x},${d.c1y} ${d.c2x},${d.c2y} ${d.x1},${d.y1}`); .attr('d', d => `M${d.x0},${d.y0} C${d.c1x},${d.c1y} ${d.c2x},${d.c2y} ${d.x1},${d.y1}`) .attr('stroke','var(--text-color)'); sel.exit().remove(); }
// Recompute input link path on the fly (used when node radii change) function computeInputLinkD(idx){ const firstLayer = layers[0]; const n = firstLayer[idx]; if (!n) return ''; const x0 = inputGrid.x + inputGrid.width; const k = firstLayer.length; const band = inputGrid.height * 0.5; const centerY = inputGrid.y + inputGrid.height / 2; const yStart = centerY - band / 2; const spacing = k > 1 ? band / (k - 1) : 0; const y0 = k > 1 ? (yStart + idx * spacing) : centerY; const yTarget = n.y; const vx = n.x - x0; const vy = yTarget - y0; const L = Math.hypot(vx, vy) || 1; const r = nodeRadiusForNode(n); const x1 = n.x - (vx / L) * r; const y1 = yTarget - (vy / L) * r; const dx = (x1 - x0) * 0.35; const c1x = x0 + dx, c1y = y0, c2x = x1 - dx, c2y = y1; return `M${x0},${y0} C${c1x},${c1y} ${c2x},${c2y} ${x1},${y1}`; }
function renderGraph(showEdges){ layoutNodes(); renderInputGrid();4 unmodified lines nodeSel.enter().append('circle').attr('class','node') .attr('r', 10) .attr('cx', d=>d.x).attr('cy', d=>d.y) .attr('fill', d=> d.layer===2 ? 'var(--primary-color)' : 'var(--surface-bg)') .attr('stroke','var(--border-color)').attr('stroke-width',1) .attr('fill', d=> d.layer===2 ? 'var(--page-bg)' : 'var(--primary-color)') .attr('fill-opacity', d=> d.layer===2 ? 1 : 0.12) .attr('stroke', d=> d.layer===2 ? 'var(--border-color)' : 'var(--border-color)') .attr('stroke-width',1) .attr('stroke-linejoin','round') .merge(nodeSel) .attr('cx', d=>d.x).attr('cy', d=>d.y) .attr('opacity', 1);1 unmodified line
// Labels for first hidden layer only (avoid stacking with output probs) const labels = []; layers[0].forEach((n,i)=> labels.push({ x:n.x, y:n.y-16, txt:`f${i+1}` })); layers[0].forEach((n,i)=> labels.push({ x:n.x-30, y:n.y+4, txt:`f${i+1}` })); const labSel = gLabels.selectAll('text').data(labels); labSel.enter().append('text').style('font-size','12px').style('fill','var(--muted-color)') .attr('x', d=>d.x).attr('y', d=>d.y) labSel.enter().append('text') .style('font-size','10px') .style('fill','var(--muted-color)') .style('paint-order','stroke') .style('stroke','var(--page-bg)') .style('stroke-width','3px') .attr('x', d=>d.x) .attr('y', d=>d.y) .text(d=>d.txt) .merge(labSel) .attr('x', d=>d.x).attr('y', d=>d.y).text(d=>d.txt); .style('paint-order','stroke') .style('stroke','var(--page-bg)') .style('stroke-width','5px') .attr('x', d=>d.x) .attr('y', d=>d.y) .text(d=>d.txt); labSel.exit().remove();
// Links as smooth curves const pathFor = (d) => { const x1 = layers[d.s.l][d.s.i].x, y1 = layers[d.s.l][d.s.i].y; const x2 = layers[d.t.l][d.t.j].x, y2 = layers[d.t.l][d.t.j].y; const dx = (x2 - x1) * 0.45; return `M${x1},${y1} C${x1+dx},${y1} ${x2-dx},${y2} ${x2},${y2}`; }; const linkSel = gLinks.selectAll('path.link').data(links, d=> `${d.s.l}-${d.s.i}-${d.t.l}-${d.t.j}`); linkSel.enter().append('path').attr('class','link') .attr('d', pathFor) .attr('d', computeLinkD) .attr('fill','none') .attr('stroke','rgba(0,0,0,0.25)') .attr('stroke','var(--text-color)') .attr('stroke-opacity', 0.25) .attr('stroke-width', d=> 0.5 + d.w*1.2) .attr('stroke-linecap','round') .merge(linkSel) .attr('d', pathFor) .attr('d', computeLinkD) .attr('stroke','var(--text-color)') .attr('stroke-width', d=> 0.5 + d.w*1.2); linkSel.exit().remove();
3 unmodified lines if (!d || typeof d.digit !== 'number') return d3.select(this).attr('transform'); const n = layers[2][d.digit]; if (!n) return d3.select(this).attr('transform'); const offset = nodeRadiusForNode(n) + 8; return `translate(${n.x+18},${n.y})`; return `translate(${n.x + offset},${n.y})`; }); // Ensure clip-path circles are updated on resize if (defs) { const clips = defs.selectAll('clipPath.clip-node').data(layers[2], d=>d.id); const ce = clips.enter().append('clipPath').attr('class','clip-node').attr('clipPathUnits','userSpaceOnUse').attr('id', d=>`clip-${d.id}`); ce.append('circle'); clips.merge(ce).select('circle').attr('cx', d=>d.x).attr('cy', d=>d.y).attr('r', d=>nodeRadiusForNode(d)); clips.exit().remove(); } }
function setNodeActivations(h1, h2, out){5 unmodified lines if (Array.isArray(out)) { for (let i=0;i<out.length;i++){ if (out[i] > bestProb){ bestProb = out[i]; argmaxIdx = i; } } } // Color/opacity by activation // Color/size by activation with smooth transitions gNodes.selectAll('circle.node') .attr('fill', d=> d.layer===2 ? 'var(--primary-color)' : `rgba(0,0,0,${0.06 + 0.44*d.a})`) .attr('stroke', d=> d.layer===2 ? 'var(--primary-color)' : 'var(--border-color)') .attr('opacity', d=> 0.25 + 0.75*Math.min(1, d.a)) .attr('r', d=> 8 + 6*Math.min(1, d.a)); .transition().duration(180).ease(d3.easeCubicOut) .attr('fill', d=> d.layer===2 ? 'var(--page-bg)' : 'var(--primary-color)') .attr('fill-opacity', d=> d.layer===2 ? 1 : (0.12 + 0.58*Math.min(1, d.a||0))) .attr('stroke', 'var(--primary-color)') .attr('stroke-opacity', d=> (d.layer===2 ? 0.9 : (0.45 + 0.45*Math.min(1, d.a||0)))) .attr('opacity', d=> 0.55 + 0.45*Math.min(1, d.a||0)) .attr('r', d=> nodeRadiusForNode(d)); // Link opacity by activation flow gLinks.selectAll('path.link') .transition().duration(180).ease(d3.easeCubicOut) .attr('d', computeLinkD) .attr('stroke','var(--text-color)') .attr('stroke-opacity', d=>{ const aS = layers[d.s.l][d.s.i].a || 0; const aT = layers[d.t.l][d.t.j].a || 0; return Math.min(1, 0.15 + 0.85 * (aS * aT)); }) .attr('stroke', d=>{ .attr('stroke-width', d=>{ const aS = layers[d.s.l][d.s.i].a || 0; const aT = layers[d.t.l][d.t.j].a || 0; const alpha = Math.min(1, 0.08 + 0.85 * (aS * aT)); const isDark = document.documentElement.getAttribute('data-theme') === 'dark'; const base = isDark ? 255 : 0; return `rgba(${base},${base},${base},${alpha})`; return 0.6 + 2.2*(aS*aT); }); // Theme-aware and activation-aware input links gInputLinks.selectAll('path.input-link') .transition().duration(180).ease(d3.easeCubicOut) .attr('d', (d)=> computeInputLinkD(d.idx)) .attr('stroke','var(--text-color)') .attr('stroke-opacity', 0.25) .attr('stroke-width', d=> 0.6 + 2.0*(layers[0][d.idx] ? (layers[0][d.idx].a||0) : 0)); // Update clip-path circles to match new radii/positions of output nodes if (defs) { const clips = defs.selectAll('clipPath.clip-node').data(layers[2], d=>d.id); clips.select('circle') .transition().duration(180).ease(d3.easeCubicOut) .attr('cx', d=>d.x) .attr('cy', d=>d.y) .attr('r', d=> nodeRadiusForNode(d)); } // Theme-aware input links on updates handled above via transition // Output labels: bold digit + small horizontal bar for probability const outs = layers[2].map((n,i)=>({ x:n.x+18, y:n.y, digit: i, prob: (out[i]||0), isTop: i===argmaxIdx })); // Output labels: digit placed to the right of the node const outs = layers[2].map((n,i)=>({ x:n.x + nodeRadiusForNode(n) + 8, y:n.y, digit: i, prob: (out[i]||0), isTop: i===argmaxIdx })); const gSel = gOutText.selectAll('g.out-label').data(outs, d=>d.digit); const gEnter = gSel.enter().append('g').attr('class','out-label'); gEnter.append('text').attr('class','out-digit') .style('font-size','12px').style('font-weight','700').style('fill','var(--text-color)'); gEnter.append('rect').attr('class','out-bar-bg').attr('rx',2).attr('ry',2) .attr('height', 4).attr('fill', 'var(--border-color)'); gEnter.append('rect').attr('class','out-bar').attr('rx',2).attr('ry',2) .attr('height', 4); const BAR_MAX = 64; gEnter.merge(gSel) .style('font-size','12px').style('font-weight','800').style('fill','var(--text-color)') .attr('text-anchor','start').attr('dominant-baseline','middle') .style('paint-order','stroke').style('stroke','var(--transparent-page-contrast)').style('stroke-width','3px'); const merged = gEnter.merge(gSel) .attr('transform', d=>`translate(${d.x},${d.y})`) .each(function(d){ const sel = d3.select(this); sel.select('text.out-digit') .attr('x', 0).attr('y', -2) .attr('x', 0).attr('y', 0) .text(String(d.digit)); sel.select('rect.out-bar-bg') .attr('x', 0).attr('y', 6) .attr('width', BAR_MAX); sel.select('rect.out-bar') .attr('x', 0).attr('y', 6) .attr('width', Math.max(1, Math.round(d.prob * BAR_MAX))) .attr('fill', d.isTop ? 'var(--primary-color)' : 'var(--border-color)'); // Ghost non-top predictions sel.style('opacity', d.isTop ? 1 : 0.35); }); // Remove any previous decorative rings (no highlight ring desired) gRoot.selectAll('circle.top-ring').remove(); // (tooltip interactions removed) gSel.exit().remove();
// Output liquid fill using clipPath + rect from bottom const rects = gNodes.selectAll('rect.out-liquid').data(layers[2], d=>d.id); const rectEnter = rects.enter().append('rect').attr('class','out-liquid') .attr('fill','var(--primary-color)') .attr('fill-opacity', 0.55) .attr('clip-path', d => `url(#clip-${d.id})`); rectEnter.merge(rects) .transition().duration(180).ease(d3.easeCubicOut) .attr('x', d=> d.x - nodeRadiusForNode(d)) .attr('width', d=> 2 * nodeRadiusForNode(d)) .attr('y', d=> { const r = nodeRadiusForNode(d); const h = 2 * r * Math.max(0, Math.min(1, d.a||0)); return d.y + r - h; }) .attr('height', d=> 2 * nodeRadiusForNode(d) * Math.max(0, Math.min(1, d.a||0))) .attr('fill-opacity', 0.55); rects.exit().remove(); }
// (no separate updateBars; bars are rendered next to nodes)6 unmodified lines renderInputGrid(); const feats = computeFeatures(x28); // 8D in [0,1] const inkMass = feats[0]; // Hide hint when user has drawn something if (hint) { hint.style.opacity = inkMass < 0.01 ? 1 : 0; } // Hidden 1 = raw features const h1 = feats; // Hidden 2 = simple non-linear mix for visualization only50 unmodified lines
// Drawing interactions let drawing=false; let last=null; let hasInteracted=false; const getPos = (ev) => { const rect = canvas.getBoundingClientRect(); const sx = CANVAS_PX/rect.width; const sy = CANVAS_PX/rect.height;8 unmodified lines ctx.beginPath(); ctx.moveTo(last.x, last.y); ctx.lineTo(p.x, p.y); ctx.stroke(); last = p; runPipeline(); } function onDown(ev){ drawing=true; last=null; drawTo(getPos(ev)); ev.preventDefault(); } function onDown(ev){ drawing=true; last=null; if (!hasInteracted){ hasInteracted=true; try { eraseBtn.style.display = 'flex'; } catch(_) {} } drawTo(getPos(ev)); ev.preventDefault(); } function onMove(ev){ if (!drawing) return; drawTo(getPos(ev)); ev.preventDefault(); } function onUp(){ drawing=false; last=null; } canvas.addEventListener('mousedown', onDown); canvas.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp);112346 unmodified lines111213141514161718192021222324252632 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989931 unmodified lines131132133909113413513613713813953 unmodified lines19319419515119619719819929 unmodified lines22923023123218723323423523610 unmodified lines2472482492042502512522072532542552562 unmodified lines2592602612622632642652662672682692702192712722732742752762772782792802812252822832842852862872882892902914 unmodified lines296297298236299300301302303304305306307308309310311312313314315<div class="d3-pie" style="width:100%;margin:10px 0;"></div><div class="d3-pie"></div><style> /* Layout piloté par container queries (par rapport au parent) */ .d3-pie { container-type: inline-size; }6 unmodified lines .d3-pie .caption { font-size: 14px; font-weight: 800; fill: var(--text-color); } .d3-pie .caption-subtitle { font-size: 11px; font-weight: 400; fill: var(--muted-color); } .d3-pie .nodata { font-size: 12px; fill: var(--muted-color); } /* Ghost legend items when hovering slices */ .d3-pie.hovering .legend .item.ghost { opacity: .35; } .d3-pie .slice-label { font-size: 11px; font-weight: 700; fill: var(--text-color); paint-order: stroke; stroke: rgba(255,255,255,0.2); stroke-width: 3px; } .d3-pie .slice-label { font-size: 11px; font-weight: 700; fill: var(--text-color); paint-order: stroke; stroke: var(--transparent-page-contrast); stroke-width: 3px; } /* Effet ghost synchronisé */ .d3-pie .slice { transition: opacity .15s ease; } .d3-pie.hovering .slice.ghost { opacity: .25; } /* Layout HTML (pas JS) pour la grille et les cellules */ .d3-pie .plots-grid { display: flex;32 unmodified lines @media (max-width: 500px) { .d3-pie .pie-cell { flex: 0 0 100%; } } /* Tooltip styling aligned with filters-quad */ .d3-pie .d3-tooltip { z-index: var(--z-elevated); backdrop-filter: saturate(1.12) blur(8px); } .d3-pie .d3-tooltip__inner { display: flex; flex-direction: column; gap: 6px; min-width: 220px; } .d3-pie .d3-tooltip__inner > div:first-child { font-weight: 800; letter-spacing: 0.1px; margin-bottom: 0; } .d3-pie .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; } .d3-pie .d3-tooltip__inner > div:nth-child(n+3) { padding-top: 6px; border-top: 1px solid var(--border-color); } .d3-pie .d3-tooltip__color-dot { display: inline-block; width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-color); }</style><script> (() => {31 unmodified lines 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' padding:'10px 12px', borderRadius:'12px', fontSize:'12px', lineHeight:'1.35', border:'1px solid var(--border-color)', background:'var(--surface-bg)', color:'var(--text-color)', boxShadow:'0 8px 32px rgba(0,0,0,.28), 0 2px 8px rgba(0,0,0,.12)', opacity:'0', transition:'opacity .12s ease', zIndex: 'var(--z-elevated)', backdropFilter: 'saturate(1.12) blur(8px)' }); 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; }53 unmodified lines legendHost.style.display = 'flex'; legendHost.style.alignItems = 'center'; legendHost.style.justifyContent = 'center'; legendHost.innerHTML = `<div class="items">${categories.map(c => `<div class="item"><span class="swatch" style="background:${colorOf(c)}"></span><span style="font-weight:500">${c}</span></div>`).join('')}</div>`; legendHost.innerHTML = `<div class="items">${categories.map(c => `<div class="item" data-category="${c}"><span class="swatch" style="background:${colorOf(c)}"></span><span style="font-weight:500">${c}</span></div>`).join('')}</div>`; }
function drawPies(rows){29 unmodified lines const totals = new Map(); categories.forEach(c => totals.set(c, 0)); rows.forEach(r => { totals.set(r.eagle_cathegory, totals.get(r.eagle_cathegory) + (r[metric.key] || 0)); }); const values = categories.map(c => ({ category: c, value: totals.get(c) || 0 })); const nonZeroValues = values.filter(v => (v.value || 0) > 0); const totalSum = d3.sum(values, d => d.value); const totalSum = d3.sum(nonZeroValues, d => d.value);
// Create HTML cell container const cell = document.createElement('div');10 unmodified lines const svg = d3.select(cell).append('svg').attr('width', radius * 2).attr('height', radius * 2 + SVG_VPAD * 2).style('display','block'); const gCell = svg.append('g').attr('transform', `translate(${radius},${radius + SVG_VPAD})`);
if (!totalSum || totalSum <= 0) { if (!totalSum || totalSum <= 0 || nonZeroValues.length === 0) { gCell.append('text').attr('class','nodata').attr('text-anchor','middle').attr('dy','0').text('No data for this metric'); } else { const data = pie(values); const data = pie(nonZeroValues); const percent = (v) => (v / totalSum) * 100;
// Slices2 unmodified lines .attr('fill', d => colorOf(d.data.category)) .attr('stroke', 'var(--surface-bg)') .attr('stroke-width', 1.2) .attr('data-category', d => d.data.category) .on('mouseenter', function(ev, d){ const hoveredCategory = d.data.category; d3.select(container).classed('hovering', true); d3.select(container).selectAll('path.slice').classed('ghost', s => (s.data && s.data.category) !== hoveredCategory); // Ghost legend items that are not hovered d3.select(legendHost).selectAll('.item').classed('ghost', function(){ return this.dataset && this.dataset.category !== hoveredCategory; }); d3.select(this).attr('stroke', 'rgba(0,0,0,0.85)').attr('stroke-width', 1); const p = percent(d.data.value); tipInner.innerHTML = `<div><strong>${d.data.category}</strong></div><div><strong>${metric.name}</strong> ${d.data.value.toLocaleString()}</div><div><strong>Share</strong> ${p.toFixed(1)}%</div>`; const catColor = colorOf(d.data.category); let html = `<div style="display:flex;align-items:center;gap:8px;white-space:nowrap;"><span class=\"d3-tooltip__color-dot\" style=\"background:${catColor}\"></span><strong>${d.data.category}</strong></div>`; html += `<div>${metric.name}</div>`; html += `<div style="display:flex;align-items:center;gap:6px;white-space:nowrap;"><strong>Value</strong><span style="margin-left:auto;text-align:right;">${d.data.value.toLocaleString()}</span></div>`; /* Share row removed per request */ tipInner.innerHTML = html; tip.style.opacity = '1'; }) .on('mousemove', function(ev){ const [mx, my] = d3.pointer(ev, container); const offsetX = 12, offsetY = 12; tip.style.transform = `translate(${Math.round(mx+offsetX)}px, ${Math.round(my+offsetY)}px)`; }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(this).attr('stroke','var(--surface-bg)'); }); .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(container).classed('hovering', false); d3.select(container).selectAll('path.slice').classed('ghost', false); d3.select(legendHost).selectAll('.item').classed('ghost', false); d3.select(this).attr('stroke','var(--surface-bg)'); });
// Percentage labels (>= 3%) gCell.selectAll('text.slice-label').data(data.filter(d => percent(d.data.value) >= 3)).enter()4 unmodified lines }
// HTML captions under the SVG (keep design) const subtitleEl = document.createElement('div'); subtitleEl.className = 'caption-subtitle'; subtitleEl.textContent = metric.title; subtitleEl.style.textAlign = 'center'; subtitleEl.style.marginTop = (CAPTION_GAP - 18) + 'px'; cell.appendChild(subtitleEl); const subtitleEl = document.createElement('div'); subtitleEl.className = 'caption-subtitle'; subtitleEl.textContent = metric.title; subtitleEl.style.textAlign = 'center'; cell.appendChild(subtitleEl); const titleEl = document.createElement('div'); titleEl.className = 'caption'; titleEl.textContent = metric.name; titleEl.style.textAlign = 'center'; cell.appendChild(titleEl); });
// Container height flows naturally with HTML; nothing to do
// Reset global hover/ghost when leaving the plots area plotsHost.onmouseleave = () => { tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(container).classed('hovering', false); d3.select(container).selectAll('path.slice').classed('ghost', false); d3.select(legendHost).selectAll('.item').classed('ghost', false); }; }
async function init(){1123456789101112131415161718192021222324252627282930313233343521 unmodified lines575859326061626312 unmodified lines767778798081828314 unmodified lines989910071727310110210310410510610734 unmodified lines14214314414514611511614714814915015115215315415515612015715815916012416116216316416545 unmodified lines211212213176214215216217218181182183219220221222223224<div class="d3-scatter" style="width:100%;margin:10px 0;"></div><div class="d3-scatter" ></div><style> /* Frameless: no controls, no axes, only dots */ .d3-scatter svg { display: block; } /* Tooltip refined styling (align with filters-quad) */ .d3-scatter .d3-tooltip { z-index: 20; backdrop-filter: saturate(1.12) blur(8px); } .d3-scatter .d3-tooltip__inner { display: flex; flex-direction: column; gap: 6px; min-width: 200px; } .d3-scatter .d3-tooltip__inner > div:first-child { font-weight: 800; letter-spacing: 0.1px; margin-bottom: 0; } .d3-scatter .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; } .d3-scatter .d3-tooltip__inner > div:nth-child(n+3) { padding-top: 6px; border-top: 1px solid var(--border-color); }</style><script> (() => {21 unmodified lines 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' }); Object.assign(tip.style, { position:'absolute', top:'0px', left:'0px', transform:'translate(-9999px, -9999px)', pointerEvents:'none', padding:'10px 12px', borderRadius:'12px', fontSize:'12px', lineHeight:'1.35', border:'1px solid var(--border-color)', background:'var(--surface-bg)', color:'var(--text-color)', boxShadow:'0 8px 32px rgba(0,0,0,.28), 0 2px 8px rgba(0,0,0,.12)', opacity:'0', transition:'opacity .12s ease', backdropFilter:'saturate(1.12) blur(8px)' }); 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; }
12 unmodified lines const y = d3.scaleLinear(); const color = d3.scaleOrdinal(); const radius = () => 4; let isDarkMode = false; function getDotStrokeColor(){ return 'var(--muted-color)'; }
// Data loading (real): banner visualization positions by category async function fetchFirstAvailable(paths){14 unmodified lines
function updateScales(data){ 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)'; isDarkMode = !!isDark; const axisColor = "var(--page-bg)"; const tickColor = "var(--page-bg)"; const gridColor = "var(--page-bg)";
width = container.clientWidth || 800; height = Math.max(260, Math.round(width/3)); 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})`);34 unmodified lines dots.enter().append('circle').attr('class','dot') .attr('cx', d=>x(d.x)).attr('cy', d=>y(d.y)).attr('r', radius()) .attr('fill', fillFor).attr('fill-opacity', 0.85) .attr('stroke', getDotStrokeColor()).attr('stroke-width', '0.75px') .on('mouseenter', function(ev, d){ d3.select(this).attr('stroke','rgba(0,0,0,0.9)').attr('stroke-width', 1); tipInner.innerHTML = `<div><strong>${d.label || 'Item'}</strong></div><div>(x: ${d.x.toFixed(2)}, y: ${d.y.toFixed(2)})</div><div>Category: ${d.group}</div>`; d3.select(this).style('stroke','var(--text-color)').style('stroke-width','1.5px').attr('fill-opacity', 1); const swatch = `<svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><circle cx="5" cy="5" r="5" fill="${fillFor(d)}" /></svg>`; tipInner.innerHTML = ` <div><strong>${d.label || 'Item'}</strong></div> <div style="display:flex;align-items:center;gap:6px;">${swatch}<span>${d.group}</span></div> <div style="display:flex;align-items:center;gap:6px;white-space:nowrap;"><strong>x</strong><span style="margin-left:auto;text-align:right;">${d.x.toFixed(2)}</span></div> <div style="display:flex;align-items:center;gap:6px;white-space:nowrap;"><strong>y</strong><span style="margin-left:auto;text-align:right;">${d.y.toFixed(2)}</span></div>`; tip.style.opacity = '1'; }) .on('mousemove', function(ev){ const [mx, my] = d3.pointer(ev, container); const ox=12, oy=12; tip.style.transform = `translate(${Math.round(mx+ox)}px, ${Math.round(my+oy)}px)`; }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(this).attr('stroke','none'); }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px, -9999px)'; d3.select(this).style('stroke', getDotStrokeColor()).style('stroke-width','0.75px').attr('fill-opacity', 0.85); }) .merge(dots) .transition().duration(180) .attr('cx', d=>x(d.x)).attr('cy', d=>y(d.y)).attr('r', radius()) .attr('fill', fillFor).attr('fill-opacity', 0.85); .attr('fill', fillFor).attr('fill-opacity', 0.85) .attr('stroke', getDotStrokeColor()).attr('stroke-width','0.75px'); dots.exit().remove();
// Compute centroids per category45 unmodified lines .attr('transform', d => `translate(${Math.round(d.x)}, ${Math.round(d.y)})`) .each(function(d){ const base = color(d.category || 'Unknown') || 'var(--text-color)'; const bg = getComputedStyle(document.documentElement).getPropertyValue('--surface-bg').trim() || '#fff'; const bg = getComputedStyle(document.documentElement).getPropertyValue('--page-bg').trim() || '#fff'; const bgNode = this.querySelector('text.label-bg'); const fgNode = this.querySelector('text.label-fg'); if (bgNode) { bgNode.textContent = d.category; bgNode.style.setProperty('fill', bg, 'important'); bgNode.style.setProperty('stroke', bg); bgNode.style.setProperty('stroke-width', '10px'); bgNode.style.setProperty('fill', "var(--page-bg)", 'important'); bgNode.style.setProperty('stroke', "var(--page-bg)"); bgNode.style.setProperty('stroke-width', '8px'); bgNode.style.setProperty('paint-order', 'stroke fill'); bgNode.style.setProperty('font-weight','800'); bgNode.style.setProperty('font-size','16px');123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159<div class="d3-train-diagram" style="width:100%;margin:10px 0;"></div><div class="caption">Hover blocks to show an explanation.</div><style> .d3-train-diagram + .caption { margin-top: 8px; font-size: 14px; color: var(--muted-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 mount = document.currentScript ? document.currentScript.previousElementSibling : null; const container = (mount && mount.querySelector && mount.querySelector('.d3-train-diagram')) || document.querySelector('.d3-train-diagram'); if (!container) return; if (container.dataset) { if (container.dataset.mounted === 'true') return; container.dataset.mounted = 'true'; }
// Diagram spec const numBlocks = 7; const rows = [ { key: 'model', label: 'Model', color: '#a78bfa' }, { key: 'forward', label: 'Forward', color: '#14b8a6' }, { key: 'backward', label: 'Backward', color: '#f59e0b' }, { key: 'gradients', label: 'Gradients', color: 'var(--primary-color)' }, { key: 'optimization', label: 'Optimization', color: '#10b981' }, { key: 'updated', label: 'Updated', color: '#7c3aed' }, ]; const hoverText = { model: 'Each block represents a submodule of the model.', forward: 'Forward pass: compute activations layer by layer.', backward: 'Backpropagation: compute gradients through the chain.', gradients: 'Gradient accumulators for each layer.', optimization: 'Optimization step: update the weights.', updated: 'Parameters updated, ready for the next iteration.' };
// SVG const svg = d3.select(container).append('svg').attr('width', '100%').style('display','block'); const gRoot = svg.append('g'); const gLegend = gRoot.append('foreignObject').attr('class','legend'); const gArrows = gRoot.append('g').attr('class','arrows'); const gBlocks = gRoot.append('g').attr('class','blocks'); const gLabels = gRoot.append('g').attr('class','row-labels');
// Tooltip (reuse style from others) 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; }
// Layout let width=800, height=360; const margin = { top: 24, right: 180, bottom: 40, left: 32 }; const x = d3.scaleBand().domain(d3.range(numBlocks)).paddingInner(0.2).paddingOuter(0.05); const y = d3.scaleBand().domain(d3.range(rows.length)).paddingInner(0.35);
function updateScales(){ width = container.clientWidth || 800; const rowH = Math.max(54, Math.min(80, Math.round(width / 12))); const innerHeight = rows.length * rowH; height = innerHeight + margin.top + margin.bottom; svg.attr('width', width).attr('height', height); const innerWidth = width - margin.left - margin.right; gRoot.attr('transform', `translate(${margin.left},${margin.top})`);
x.range([0, innerWidth]); y.range([0, innerHeight]);
return { innerWidth, innerHeight }; }
function render(){ const { innerWidth, innerHeight } = updateScales();
// Legend right side const legendWidth = 160, legendHeight = rows.length * 20; gLegend.attr('x', innerWidth + 16).attr('y', 0).attr('width', legendWidth).attr('height', legendHeight); const lroot = gLegend.selectAll('div').data([0]).join('xhtml:div'); lroot.html(` <div style="display:flex;flex-direction:column;gap:8px;"> ${rows.map(r => `<div style=\"display:flex;align-items:center;gap:8px;\"><span style=\"width:14px;height:14px;background:${r.color};border-radius:4px;display:inline-block\"></span><span>${r.label}</span></div>`).join('')} </div> `);
// Row labels on the right side aligned to centers gLabels.selectAll('*').remove(); gLabels.selectAll('text').data(rows).join('text') .attr('x', innerWidth + 16) .attr('y', (_,i)=> y(i) + y.bandwidth()/2) .attr('dy','0.35em') .style('font-size','14px') .style('fill','var(--text-color)') .text(d=>d.label);
// Blocks per row const blockW = Math.min(84, x.bandwidth()); const blockH = Math.min(52, Math.round(y.bandwidth() * 0.8)); const blocks = []; rows.forEach((row, ri) => { for (let i=0;i<numBlocks;i++) blocks.push({ row, ri, i }); }); const sel = gBlocks.selectAll('rect.block').data(blocks, d=>`${d.row.key}-${d.i}`); sel.join( enter => enter.append('rect').attr('class','block') .attr('x', d=>x(d.i)) .attr('y', d=>y(d.ri) + (y.bandwidth()-blockH)/2) .attr('rx', 12).attr('ry', 12) .attr('width', blockW) .attr('height', blockH) .attr('fill', d=>d.row.color) .attr('opacity', 0.95) .attr('stroke', 'rgba(0,0,0,0.18)') .attr('filter', 'url(#shadow)') .on('mouseenter', function(ev, d){ d3.select(this).attr('opacity', 1.0).attr('stroke-width', 1.2); tipInner.innerHTML = `<div><strong>${d.row.label}</strong></div><div>${hoverText[d.row.key]}</div>`; tip.style.opacity = '1'; }) .on('mousemove', function(ev){ const [mx,my] = d3.pointer(ev, container); tip.style.transform = `translate(${mx+12}px, ${my+12}px)`; }) .on('mouseleave', function(){ tip.style.opacity='0'; tip.style.transform='translate(-9999px,-9999px)'; d3.select(this).attr('opacity', 0.95).attr('stroke-width', 1); }) );
// Arrows forward/backward gArrows.selectAll('*').remove(); const arrowY = (ri) => y(ri) + y.bandwidth()/2; const isDark = document.documentElement.getAttribute('data-theme') === 'dark'; const arrowColor = isDark ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.55)'; const defs = svg.select('defs').empty() ? svg.append('defs') : svg.select('defs'); const marker = defs.append('marker').attr('id','arrow').attr('viewBox','0 0 10 10').attr('refX', 10).attr('refY', 5).attr('markerWidth', 6).attr('markerHeight', 6).attr('orient','auto-start-reverse'); marker.append('path').attr('d','M 0 0 L 10 5 L 0 10 z').attr('fill', arrowColor); // drop shadow filter const flt = defs.append('filter').attr('id','shadow').attr('x','-20%').attr('y','-20%').attr('width','140%').attr('height','140%'); flt.append('feDropShadow').attr('dx','0').attr('dy','1').attr('stdDeviation','1.5').attr('flood-color','rgba(0,0,0,0.18)'); // Forward arrow (top orientation) gArrows.append('line').attr('x1', x(0)).attr('y1', arrowY(1)-28).attr('x2', x(numBlocks-1)+blockW).attr('y2', arrowY(1)-28) .attr('stroke', rows[1].color).attr('stroke-width', 4).attr('marker-end','url(#arrow)'); // Backward arrow (orange, reversed) gArrows.append('line').attr('x1', x(numBlocks-1)+blockW).attr('y1', arrowY(2)-20).attr('x2', x(0)).attr('y2', arrowY(2)-20) .attr('stroke', rows[2].color).attr('stroke-width', 4).attr('marker-end','url(#arrow)'); // Vertical arrows (gradients down, updated up) const midX = x(3) + blockW/2; gArrows.append('line').attr('x1', midX).attr('y1', arrowY(2)+blockH/2+4).attr('x2', midX).attr('y2', arrowY(3)-blockH/2-6) .attr('stroke', rows[3].color).attr('stroke-width', 3).attr('marker-end','url(#arrow)'); gArrows.append('line').attr('x1', midX).attr('y1', arrowY(4)+blockH/2+6).attr('x2', midX).attr('y2', arrowY(5)-blockH/2-6) .attr('stroke', rows[5].color).attr('stroke-width', 3).attr('marker-end','url(#arrow)'); }
render(); if (window.ResizeObserver) { const ro = new ResizeObserver(()=>render()); ro.observe(container); } else { window.addEventListener('resize', render); } };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => ensureD3(bootstrap), { once: true }); } else { ensureD3(bootstrap); } })();</script>
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768692 unmodified lines727374137576777875 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002011012022032042052062072082092102112122132142152162172182192202212222232242252262272282292305 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233241 unmodified line32632732812312432933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437521 unmodified lines397398399153400401402403156157404405406159407408409410411164412413414415## Embed Chart Authoring Guidelines
### Quickstart (TL;DR)- Create a single self-contained HTML fragment: root div + scoped style + IIFE script.- Draw marks/axes in SVG; render UI (legend and controls) in HTML.- Place legend and controls ABOVE the chart. Include a legend title "Legend" and a select labeled "Metric" when relevant.- Load data from public `/data` first, then fall back to `assets/data`.- Use `window.ColorPalettes` for colors; stick to CSS variables for theming.
Minimal header markup:```html<div class="legend"> <div class="legend-title">Legend</div> <div class="items"></div> <!-- items populated by JS: <span class="item"><span class="swatch"></span><span>Name</span></span> --></div><div class="controls"> <div class="control-group"> <label for="metric-select-<id>">Metric</label> <select id="metric-select-<id>"></select> </div> <!-- optional: other controls --></div>```
See also: `d3-line-simple.html`, `d3-line-quad.html`, `d3-benchmark.html`.
Authoring rules for creating a new interactive chart as a single self-contained `.html` file under `src/content/embeds/`. These conventions are derived from `d3-bar.html`, `d3-comparison.html`, `d3-neural.html`, `d3-line.html`, and `d3-pie.html`.
### A) Colors & palettes (MANDATORY)- Always obtain color arrays from `window.ColorPalettes`; do not hardcode palettes.- Use the categorical/sequential/diverging helpers and the current primary color.- If you change `--primary-color` dynamically, call `window.ColorPalettes.refresh()` so listeners update.
Usage:```js// Usage (with explicit counts)const cat = window.ColorPalettes.getColors('categorical', 8);const seq = window.ColorPalettes.getColors('sequential', 8);const div = window.ColorPalettes.getColors('diverging', 7);
// For current primary color stringconst primaryHex = window.ColorPalettes.getPrimary();
// If you change --primary-color dynamically, call refresh to notify listenersdocument.documentElement.style.setProperty('--primary-color', '#6D4AFF');window.ColorPalettes.refresh();```
Notes:- Keep chart accents (lines, markers, selection) aligned with `--primary-color`.- Prefer CSS variables for fills/strokes when possible; derive series colors via `ColorPalettes`.- Provide a graceful fallback to CSS variables if `window.ColorPalettes` is unavailable.
### B) Layout & form elements (HTML-only)- All UI controls (labels, selects, sliders, buttons, toggles) must be plain HTML inside the root container.- Do not draw controls with SVG; style them consistently (rounded 8px, custom caret, focus ring).- Use `<label>` wrapping inputs for accessibility and concise text (e.g., "Metric", "Model Size").- Manage layout with CSS inside the scoped `<style>` for the root class; avoid global rules.
### C) SVG scope: charts only; UI in HTML- SVG is for chart primitives (marks, axes, gridlines) only.- Put legends and controls in HTML (adjacent DOM is preferred; `foreignObject` only if necessary).- Tooltips are HTML positioned absolutely inside the root container. - Details: see sections 4 (controls), 5 (tooltips), 8 (legends).
### 1) File, naming, and structure- Name files with a clear prefix and purpose: `d3-<type>.html` (e.g., `d3-scatter.html`).- Wrap everything in a single `<div class="<root-class>">`, a `<style>` block scoped to that root class, and a `<script>` IIFE.2 unmodified lines
Minimal skeleton:```html<div class="d3-yourchart" style="width:100%;margin:10px 0;"></div><div class="d3-yourchart"></div><style> .d3-yourchart {/* all styles scoped to the root */}</style>75 unmodified lines### 3) Styling and theming- Scope all rules under the root class; do not style `body`, `svg` globally.- Use CSS variables for theme alignment: `--primary-color`, `--text-color`, `--muted-color`, `--surface-bg`, `--border-color`.- Derive palette colors from `window.ColorPalettes` (categorical, sequential, diverging); do not hardcode arrays.- For dark mode–aware strokes/ticks, either: - Read `document.documentElement.getAttribute('data-theme') === 'dark'`, or - Prefer CSS-only where possible.- Keep backgrounds light and borders subtle; the outer card frame is handled by `HtmlEmbed.astro`.
Standard axis/tick/grid colors (reuse across charts):
```css.your-root-class { --axis-color: rgba(0,0,0,0.25); --tick-color: rgba(0,0,0,0.55); --grid-color: rgba(0,0,0,0.05);}[data-theme="dark"] .your-root-class { --axis-color: rgba(255,255,255,0.25); --tick-color: rgba(255,255,255,0.70); --grid-color: rgba(255,255,255,0.08);}/* Example axis application (D3) */g.axis-x, g.axis-y { }/* In JS after calling axis: */// g.selectAll('path, line').attr('stroke', 'var(--axis-color)');// g.selectAll('text').attr('fill', 'var(--tick-color)').style('font-size','12px');/* Gridlines: */// grid.call(d3.axisLeft(y).ticks(6).tickSize(-innerWidth).tickFormat(''))// .call(g => g.selectAll('.tick line').attr('stroke','var(--grid-color)'));```
#### 3.1) Text on fixed-colored backgrounds
- When rendering text over cells/areas with fixed background colors (that do not change with theme), compute a readable text style once from the actual background color.- Use `window.ColorPalettes.getTextStyleForBackground(bgCss, { blend: 0.6 })` when available; avoid tying text color to dark mode toggles since the background is constant.- Do not re-evaluate on theme toggle unless the background color itself changes.
Example:```jsconst bg = getComputedStyle(cellRect).fill; // e.g., 'rgb(12, 34, 56)'const style = window.ColorPalettes?.getTextStyleForBackground ? window.ColorPalettes.getTextStyleForBackground(bg, { blend: 0.6 }) : { fill: 'var(--text-color)' };textSel.style('fill', style.fill);```
### 4) Controls (labels, selects, sliders)- Compose controls as plain HTML elements appended inside the root container.- Compose controls as plain HTML elements appended inside the root container (no SVG UI).- Style selects like in `d3-line.html`/`d3-bar.html` for consistency (rounded 8px, custom caret via data-URI, focus ring).- Use `<label>` wrapping the input for accessibility; set concise text (e.g., "Metric", "Model Size").
#### 4.1) Required select label: "Metric"- When a select is used to switch metrics, include a visible label above the select with the exact text "Metric".- Preferred markup (grouped for easy vertical stacking):
```html<div class="controls"> <div class="control-group"> <label for="metric-select-<unique>">Metric</label> <select id="metric-select-<unique>"></select> </div></div>```
Minimal CSS (match project styles):
```css.controls { display:flex; gap:16px; align-items:center; justify-content:flex-end; flex-wrap:wrap; }.controls .control-group { display:flex; flex-direction:column; align-items:flex-start; gap:6px; }.controls label { font-size:12px; font-weight:700; color: var(--text-color); }.controls select { font-size:12px; padding:8px 28px 8px 10px; border:1px solid var(--border-color); border-radius:8px; background: var(--surface-bg); color: var(--text-color); }```
### 5) Tooltip pattern- Create a single `.d3-tooltip` absolutely positioned inside the container.- Show on hover, hide on leave; position using `d3.pointer(event, container)` plus a small offset.5 unmodified lines- Implement `fetchFirstAvailable(paths)`; try in order with `cache:'no-cache'`; handle errors gracefully with a red `<pre>` message.- For images or JSON models, mirror the same approach (see `d3-comparison.html`, `d3-neural.html`).
#### 6.1) Data props (HtmlEmbed → embed)
- HtmlEmbed accepts an optional `data` prop that can be a string (single file) or an array of strings (multiple files).- This prop is passed to the fragment via the `data-datafiles` HTML attribute.- In the embed script, read this attribute from the closest ancestor that carries it (the `HtmlEmbed` wrapper), not necessarily the chart’s direct container.- Recommended normalization: if a value contains no slash, automatically prefix it with `/data/` to target the public data folder.- If `data` is not provided, keep the usual fallback (public, then `assets/data`).
Optional configuration (e.g., default metric):
```js// In HtmlEmbed usage (MDX):<HtmlEmbed src="d3-line-simple.html" data="internal_deduplication.csv" config={{ defaultMetric: 'average_rank' }} />
// In the embed script (read from closest ancestor):let mountEl = container;while (mountEl && !mountEl.getAttribute?.('data-datafiles') && !mountEl.getAttribute?.('data-config')) { mountEl = mountEl.parentElement;}let providedConfig = null;try { const cfg = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-config') : null; if (cfg && cfg.trim()) providedConfig = cfg.trim().startsWith('{') ? JSON.parse(cfg) : cfg;} catch(_) {}// Example: selecting initial metric if presentconst desired = providedConfig && providedConfig.defaultMetric ? String(providedConfig.defaultMetric) : null;```
Examples (MDX):
```mdx<HtmlEmbed src="d3-line-simple.html" title="Run A" data="formatting_filters.csv" /><HtmlEmbed src="d3-line-simple.html" title="Run B" data="relevance_filters.csv" />
<HtmlEmbed src="d3-line-simple.html" title="Comparison A vs B" data={[ 'formatting_filters.csv', 'relevance_filters.csv' ]}/>```
Reading on the embed side (JS):
```js// Find the closest ancestor that carries the attributelet mountEl = container;while (mountEl && !mountEl.getAttribute?.('data-datafiles')) { mountEl = mountEl.parentElement;}let providedData = null;try { const attr = mountEl && mountEl.getAttribute ? mountEl.getAttribute('data-datafiles') : null; if (attr && attr.trim()) { providedData = attr.trim().startsWith('[') ? JSON.parse(attr) : attr.trim(); }} catch(_) {}
const DEFAULT_CSV = '/data/formatting_filters.csv';const ensureDataPrefix = (p) => (typeof p === 'string' && p && !p.includes('/')) ? `/data/${p}` : p;const normalizeInput = (inp) => Array.isArray(inp) ? inp.map(ensureDataPrefix) : (typeof inp === 'string' ? [ ensureDataPrefix(inp) ] : null);
const CSV_PATHS = Array.isArray(providedData) ? normalizeInput(providedData) : (typeof providedData === 'string' ? normalizeInput(providedData) || [DEFAULT_CSV] : [ DEFAULT_CSV, './assets/data/formatting_filters.csv', '../assets/data/formatting_filters.csv', '../../assets/data/formatting_filters.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(_){} } throw new Error('CSV not found');};```
### 7) Responsiveness and layout- Compute `width = container.clientWidth`, and a height derived from width (e.g., `width / 3`), with a sensible minimum height.- Maintain a `margin` object and derive `innerWidth/innerHeight` for plots.1 unmodified line- Recompute scales/axes/grid on every render.
### 8) Legends and labels- Use `foreignObject` + inline HTML to render compact legends that wrap nicely (see `d3-line.html`, `d3-pie.html`).- For axes, remove and re-append groups each render (simple and predictable), or update in place if needed.- Prefer HTML for legends for wrapping and accessibility; avoid SVG-based legends.- Always add axis labels when applicable (e.g., `Step`, `Value`).- Standardize legend swatch size: 14×14px, border-radius 3px, 1px border `var(--border-color)`.
#### 8.1) Required legend title: "Legend"- Always render a visible title above legend items with the exact text "Legend".- Canonical markup:
```html<div class="legend"> <div class="legend-title">Legend</div> <div class="items"> <!-- <span class="item"><span class="swatch"></span><span>Series A</span></span> ... --> </div></div>```
Minimal CSS (match project styles):
```css.legend { display:flex; flex-direction:column; align-items:flex-start; gap:6px; }.legend-title { font-size:12px; font-weight:700; color: var(--text-color); }.legend .items { display:flex; flex-wrap:wrap; gap:8px 14px; }.legend .item { display:inline-flex; align-items:center; gap:6px; white-space:nowrap; font-size:12px; color: var(--text-color); }.legend .swatch { width:14px; height:14px; border-radius:3px; border:1px solid var(--border-color); }```
Recommended JS pattern to (re)build the legend:
```jsfunction makeLegend(seriesNames, colorFor) { let legend = container.querySelector('.legend'); if (!legend) { legend = document.createElement('div'); legend.className = 'legend'; container.appendChild(legend); } let title = legend.querySelector('.legend-title'); if (!title) { title = document.createElement('div'); title.className = 'legend-title'; title.textContent = 'Legend'; legend.appendChild(title); } let items = legend.querySelector('.items'); if (!items) { items = document.createElement('div'); items.className = 'items'; legend.appendChild(items); } items.innerHTML = ''; seriesNames.forEach(name => { const el = document.createElement('span'); el.className = 'item'; const sw = document.createElement('span'); sw.className = 'swatch'; sw.style.background = colorFor(name); const txt = document.createElement('span'); txt.textContent = name; el.appendChild(sw); el.appendChild(txt); items.appendChild(el); });}```
### 9) Accessibility- Provide `alt` attributes on `<img>` (see `d3-comparison.html`).21 unmodified lines### 14) Conventions checklist (before committing)- Root class is unique and matches file name (`d3-<type>`).- No globals added; script wrapped in an IIFE.- `data-mounded` guard is present to avoid double-mount.- `data-mounted` guard is present to avoid double-mount.- Colors come from `window.ColorPalettes` (no hardcoded arrays); `--primary-color` respected.- Uses CSS variables for colors; dark-mode friendly.- Responsive: recomputes layout on resize; uses `ResizeObserver`.- Controls are accessible and consistently styled.- Tooltip is present (if hover/inspect is required).- Controls are HTML-only, accessible, and consistently styled.- Legends and tooltips are HTML, not SVG.- Data loading includes public-path-first strategy and graceful error.- Axes/labels/legends are legible at small widths.- Axes/labels are legible at small widths.- Code is easy to skim: clear naming, early returns, short functions.
### 15) Example: small bar chart (structure only)```html<div class="d3-mini-bar" style="width:100%;margin:10px 0;"></div><div class="d3-mini-bar"></div><style> .d3-mini-bar .bar { stroke: none; }</style>163 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162174 unmodified lines222223224177225226227228229230163 unmodified lines const mo = new MutationObserver(() => updatePalettes()); mo.observe(MODE.cssRoot, { attributes: true, attributeFilter: ['style', 'data-theme'] }); setInterval(updatePalettes, 400); // Utility: choose high-contrast (or softened) text style against an arbitrary background color const pickTextStyleForBackground = (bgCss, opts = {}) => { const cssRoot = document.documentElement; const getCssVar = (name) => { try { return getComputedStyle(cssRoot).getPropertyValue(name).trim(); } catch { return ''; } }; const resolveCssToRgb01 = (css) => { const rgb = parseCssColorToRgb(css); if (!rgb) return null; return rgb; // already 0..1 }; const mixRgb01 = (a, b, t) => ({ r: a.r*(1-t)+b.r*t, g: a.g*(1-t)+b.g*t, b: a.b*(1-t)+b.b*t }); const relLum = (rgb) => { const f = (u) => srgbToLinear(u); return 0.2126*f(rgb.r) + 0.7152*f(rgb.g) + 0.0722*f(rgb.b); }; const contrast = (fg, bg) => { const L1 = relLum(fg), L2 = relLum(bg); const a = Math.max(L1,L2), b = Math.min(L1,L2); return (a + 0.05) / (b + 0.05); }; try { const bg = resolveCssToRgb01(bgCss); if (!bg) return { fill: getCssVar('--text-color') || '#000', stroke: 'var(--transparent-page-contrast)', strokeWidth: 1 }; const candidatesCss = [getCssVar('--text-color') || '#111', getCssVar('--on-primary') || '#0f1115', '#000', '#fff']; const candidates = candidatesCss .map(css => ({ css, rgb: resolveCssToRgb01(css) })) .filter(x => !!x.rgb); // Pick the max contrast let best = candidates[0]; let bestCR = contrast(best.rgb, bg); for (let i=1;i<candidates.length;i++){ const cr = contrast(candidates[i].rgb, bg); if (cr > bestCR) { best = candidates[i]; bestCR = cr; } } // Optional softening via blend factor (0..1), blending towards muted color const blend = Math.min(1, Math.max(0, Number(opts.blend || 0))); let finalRgb = best.rgb; if (blend > 0) { const mutedCss = getCssVar('--muted-color') || (getCssVar('--text-color') || '#111'); const mutedRgb = resolveCssToRgb01(mutedCss) || best.rgb; finalRgb = mixRgb01(best.rgb, mutedRgb, blend); } const haloStrength = Math.min(1, Math.max(0, Number(opts.haloStrength == null ? 0.5 : opts.haloStrength))); const stroke = (best.css === '#000' || best.css.toLowerCase() === 'black') ? `rgba(255,255,255,${0.30 + 0.40*haloStrength})` : `rgba(0,0,0,${0.30 + 0.30*haloStrength})`; return { fill: toHex(finalRgb), stroke, strokeWidth: (opts.haloWidth == null ? 1 : Number(opts.haloWidth)) }; } catch { return { fill: getCssVar('--text-color') || '#000', stroke: 'var(--transparent-page-contrast)', strokeWidth: 1 }; } }; window.ColorPalettes = { refresh: updatePalettes, getPrimary: () => getPrimaryHex(),4 unmodified lines if (key === 'sequential') return generators.sequential(primary, total); if (key === 'diverging') return generators.diverging(primary, total); return []; } }, getTextStyleForBackground: (bgCss, opts) => pickTextStyleForBackground(bgCss, opts || {}), chooseReadableText: (bgCss, opts) => pickTextStyleForBackground(bgCss, opts || {}) }; };
19 unmodified lines2021222324252655 unmodified lines82838485868788899091926 unmodified lines9910010110210310410510610710810911019 unmodified lines /* Text & Surfaces */ --page-bg: #ffffff; --text-color: rgba(0,0,0,.85); --transparent-page-contrast: rgba(255,255,255,.85); --muted-color: rgba(0,0,0,.6); --border-color: rgba(0,0,0,.1); --surface-bg: #fafafa;55 unmodified lines --z-overlay: 1000; --z-modal: 1100; --z-tooltip: 1200;
/* Charts (global) */ --axis-color: var(--text-color); --tick-color: var(--muted-color); --grid-color: rgba(0,0,0,.08);}
/* ============================================================================ */6 unmodified lines --border-color: rgba(255,255,255,.15); --surface-bg: #12151b; --code-bg: #12151b; --transparent-page-contrast: rgba(0,0,0,.85); /* Charts (global) */ --axis-color: var(--text-color); --tick-color: var(--muted-color); --grid-color: rgba(255,255,255,.10);
/* Primary (lower L in dark) */ --primary-color: oklch(from var(--primary-base) calc(l - 0.08) c h);123456789.card { background: var(--surface-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: var(--spacing-2); z-index: calc(var(--z-elevated) + 1); position: relative; margin-bottom: var(--block-spacing-y);}6 unmodified lines789101112136 unmodified lines@import './components/_button.css';@import './components/_table.css';@import './components/_tag.css';@import './components/_card.css';
.demo-wide,.demo-full-width {app/src/components/HtmlEmbed.astro+14-9
app/src/content/article.mdx+3
app/src/content/chapters/components.mdx+40-72
app/src/content/chapters/vibe-coding-charts.mdxAdded+70
app/src/content/embeds/banner.html+52-20
app/src/content/embeds/bar.htmlDeleted-1
app/src/content/embeds/d3-area-stacked.htmlDeleted-220
app/src/content/embeds/d3-bar.html+149-43
app/src/content/embeds/d3-benchmark.htmlAdded+444
app/src/content/embeds/d3-boxplot.htmlDeleted-251
app/src/content/embeds/d3-comparison.htmlDeleted-149
app/src/content/embeds/d3-confusion-matrix.htmlAdded+516
app/src/content/embeds/d3-line-example.htmlDeleted-456
app/src/content/embeds/filters-quad.html → app/src/content/embeds/d3-line-quad.htmlRenamed+246-147
app/src/content/embeds/d3-line.html+387-431
app/src/content/embeds/d3-matrix.htmlAdded+515
app/src/content/embeds/d3-neural.html → app/src/content/embeds/d3-neural-network.htmlRenamed+255-79
app/src/content/embeds/d3-pie.html+83-11
app/src/content/embeds/d3-scatter.html+51-13
app/src/content/embeds/heatmap.htmlDeleted-159
app/src/content/embeds/vibe-code-d3-embeds-directives.md+257-9
app/src/scripts/color-palettes.js+51-1
app/src/styles/_variables.css+12
app/src/styles/components/_card.cssAdded+9
app/src/styles/global.css+1