From dfb27d41dc4ac82421928d7fcf703e14dc56ab51 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 28 Aug 2026 15:46:02 +0800 Subject: [PATCH] feat(quantum): Q8 circuit SVG themes and view plot chrome Fix label/wire overlap with gutter + chip labels; default dark tech palette with light/bw themes; restyle probs/bloch and darken view plot frames. Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 4 +- .cursor/skills/marqdo/reference.md | 1 + .gitignore | 3 + doc/design/ext-quantum-viz-style.md | 151 ++++++++ doc/roadmap/ext-quantum.md | 5 +- ext/quantum/quantum.mq.md | 5 +- ext/quantum/量子.mq.md | 5 +- plugins/quantum/src/draw.rs | 530 ++++++++++++++++++++-------- plugins/quantum/src/lib.rs | 18 +- src/view/html.rs | 11 + tests/gold.rs | 14 +- 11 files changed, 592 insertions(+), 155 deletions(-) create mode 100644 doc/design/ext-quantum-viz-style.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index df8516c..83a63cd 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -191,9 +191,9 @@ Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --relea **Q7 linear algebra:** `density`, `partial_trace`, `eig`, `expect` (Pauli string, left=high bit), `purity`, `kron`, `schmidt`, `fidelity`. -**Q7 draw kinds:** `circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch` (quote string args: `kind="hinton"`). +**Q7 draw kinds:** `circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch` (quote string args: `kind="hinton"`). Optional `theme="dark"|"light"|"bw"` (default dark tech lab; fixes label/wire overlap). -Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/). +Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · viz style: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/). ## AI authoring workflow diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md index 163d7df..05c8a77 100644 --- a/.cursor/skills/marqdo/reference.md +++ b/.cursor/skills/marqdo/reference.md @@ -175,4 +175,5 @@ See `doc/design/call-arguments.md`. | `doc/design/web-net-capabilities.md` | ext/web capability matrix (W0–W7 + P3) | | `doc/design/ext-quantum.md` | `ext/quantum` circuits | | `doc/design/ext-quantum-q7.md` | Q7 density linear algebra + advanced SVG | +| `doc/design/ext-quantum-viz-style.md` | Q8 circuit/plot themes (`dark`/`light`/`bw`) | | `doc/design/view-debug.md` | view / debug hosts | diff --git a/.gitignore b/.gitignore index 0ea892a..09ae86c 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,6 @@ plugins/*/tmp/ /tests/ext/quantum-*.svg /examples/quantum-*/**/*.svg /examples/quantum-*/*.svg + +# Local ABI plugin copies (use `marqdo ext add quantum` / cargo build) +/ext/native/ diff --git a/doc/design/ext-quantum-viz-style.md b/doc/design/ext-quantum-viz-style.md new file mode 100644 index 0000000..a9f59c4 --- /dev/null +++ b/doc/design/ext-quantum-viz-style.md @@ -0,0 +1,151 @@ +# `ext/quantum` Q8 — 可视化美学升级(科技感电路图) + +| | | +|---|---| +| 状态 | **Accepted · Q8a/Q8b done · Q8c pending** | +| 日期 | 2026-08-28 | +| 父设计 | [ext-quantum.md](ext-quantum.md) · [ext-quantum-q7.md](ext-quantum-q7.md) | +| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | +| 对照 | [IBM Quantum Composer](https://quantum.cloud.ibm.com/docs/guides/composer) · [Qiskit `iqp` / `iqp-dark`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.visualization.circuit_drawer) · Cirq / Quirk 视觉习惯 | + +--- + +## 0. 一句话 + +修复 view 内嵌量子 SVG 的**文字–导线粘连**,并把电路 / 概率 / 布洛赫 / 密度类图统一到一套**量子实验室科技感**视觉令牌(深底、门族分色、清晰留白)——仍只输出自包含 SVG,无外链字体/CDN。 + +--- + +## 1. 问题诊断(对照用户截图) + +| 现象 | 根因(`plugins/quantum/src/draw.rs`) | +|------|----------------------------------------| +| `q0`/`q1` 与导线穿过文字 | 导线从 `x=8` 起画满宽;标签 `x=4` 且基线对齐导线中心 → 线穿字 | +| 「不好看 / 无科技感」 | 单色 `#1a1a1a` + 浅灰盒;无门族色、无背景板、无线宽层次 | +| 门盒贴线、略挤 | `COL_W=56`、盒 28×28、标签栏与第一列无独立 gutter | +| 测量/控点辨识弱 | 与单比特门同色同描边,缺少语义色 | + +**不在本切片**:交互拖拽、WebGL、外链字体、第二套 view 皮肤。 + +--- + +## 2. 业界对照(联网 2026-08) + +| 来源 | 可借鉴点 | 本仓取舍 | +|------|----------|----------| +| **Qiskit `iqp` / `iqp-dark`** | 门族 `displaycolor`(面色+字色);深色底;线色弱于门 | 移植**色板与分类**,不绑 matplotlib | +| **IBM Composer** | 经典门深蓝、相位门浅蓝、非酉灰;导出 light/dark | 默认 **dark tech**(view 卡片上更醒目);可选 `theme=light` | +| **Quirk** | 高对比栅格、测量仪表清晰 | 测量盒保留仪表符号,加强描边/填充对比 | +| **教科书 bw** | 印刷友好 | 保留为 `theme=bw` 后备,非默认 | + +**刻意避开**:紫白渐变「AI 默认皮肤」;过重 glow 光晕(打印/浅底卡片会糊)。科技感靠:**深 slate 底 + 青/靛门色 + 清晰层级 + 留白**,而非堆霓虹。 + +--- + +## 3. 视觉令牌(锁定 `marqdo-iqp`) + +### 3.1 主题 + +| `theme` | 用途 | +|---------|------| +| `dark`(**默认**) | view / 教学演示科技感 | +| `light` | 浅底文档打印 | +| `bw` | 无彩色、高对比 | + +作者面:`draw theme=dark|light|bw`(中文 `主题=`);缺省 `dark`。 + +### 3.2 Dark 色板(默认) + +| 令牌 | 色 | 用途 | +|------|-----|------| +| `bg` | `#0a0e14` → `#141c28` 渐变 | SVG 圆角底板 | +| `wire` | `#6b7f96` | 比特线(双层描边) | +| `label` / `chip` | `#e8eef6` / `#1e2a3a` | `q0` 芯片标签(线不穿字) | +| `gate.clifford` | 面 `#4c6fff` / 字 `#f2f6ff` | H、X、Y、CX、SWAP… | +| `gate.phase` | 面 `#2de2e6` / 字 `#042024` | S、T、Rz、CZ… | +| `gate.rotation` | 面 `#3dd6c6` / 字 `#041a18` | Rx、Ry | +| `gate.measure` | 面 `#8fa3b8` / 字 `#0a1018` | MEASURE | +| `barrier` | `#9aafc0` 虚线 | BARRIER | +| `ctrl` | `#f0f5ff` | 控制点 / ⊕ | + +Light / bw 在实现里各给一套平行表;金样以 dark 主断言(SVG 含 `data-theme="dark"` 与背景色)。 + +### 3.3 布局(消灭粘连) + +```text +| pad | label_col | gutter | col0 | … | colN | pad | + ^q0 文字居中 ^导线从此开始(不穿过文字) +``` + +| 常量 | 建议值 | +|------|--------| +| `LABEL_W` | 36 | +| `GUTTER` | 10(标签区右缘 → 第一门中心前的空档) | +| `PAD_X` / `PAD_Y` | 16 / 20 | +| `COL_W` | 64 | +| `ROW_H` | 48 | +| 门盒 | 32×32,`rx=6` | +| 线宽 | 导线 1.75;门描边 1.25;控制竖线 2 | + +标签:`text-anchor="end"`,落在标签列右缘内侧;`dominant-baseline="middle"`;导线 `x1 = LABEL_W + GUTTER`。 + +### 3.4 门族映射 + +| 族 | 门名(归一化后) | +|----|------------------| +| clifford | I X Y Z H CX CNOT SWAP | +| phase | S T RZ CZ | +| rotation | RX RY | +| measure | MEASURE M | +| barrier | BARRIER | +| custom / U | clifford 色或中性 `#546e7a` | + +--- + +## 4. 作者面(增量,向后兼容) + +```markdown +*`svg` = > `qc`.draw kind="circuit" theme="dark" * +*`svg` = > `qc`.draw kind="probs" theme="light" * +``` + +| 参数 | 默认 | 说明 | +|------|------|------| +| `kind` | `circuit` | 既有枚举不变 | +| `theme` | `dark` | 新增;非法值报错 | +| `path` | — | 既有 | + +中文:`主题=dark|light|bw`。ABI:`quantum_draw_circuit` 增可选 `theme`;`quantum_density_draw` / `quantum_gate_draw` 同步。 + +--- + +## 5. 分期 + +| 子阶段 | 内容 | 验收 | +|--------|------|------| +| **Q8a** | 电路轨线:布局 gutter + dark/light/bw 令牌 + 门族分色 | 标签不与线相交;SVG 含 `data-theme`;更新 draw smoke | +| **Q8b** | probs / bloch / gate heatmap 共用令牌 | 柱/球/热力与电路同族色 | +| **Q8c** | hinton / city / qsphere / paulivec / multibloch 换肤 | 高级图不「脱节」;viz-advanced smoke 仍绿 | + +--- + +## 6. 实现约束 + +1. 仅改 `plugins/quantum` 绘图 + L1 透传 `theme`;**不**改 Marqdo 核心。 +2. SVG **内联**颜色与字体栈(`ui-sans-serif, system-ui, …`);无 `@import` / CDN。 +3. view 仍走 `record_plot`;底板自带圆角矩形,避免白底卡片上「漂浮黑线」。 +4. 金样:断言结构标记(`data-theme`、`data-gate-family`)+ 既有 kind;不像素比对。 + +--- + +## 7. 非目标 + +- 复制 Qiskit matplotlib 像素级一致 +- 动画 / 3D 电路 +- 用户自定义完整 JSON 主题文件(可 Q9) + +--- + +## 8. 一句话 + +**先把字从线上挪开,再给门族涂上实验室色——默认 dark tech,打印用 light,论文用 bw。** diff --git a/doc/roadmap/ext-quantum.md b/doc/roadmap/ext-quantum.md index ccea280..f09c1d4 100644 --- a/doc/roadmap/ext-quantum.md +++ b/doc/roadmap/ext-quantum.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Q0–Q7 完结**(高阶线性代数 + 高级可视化 + 纠缠示例) | +| 状态 | **Q0–Q7 完结 · Q8a/Q8b 完结 · Q8c 待做** | | 日期 | 2026-08-28 | | **锁定设计** | [design/ext-quantum.md](../design/ext-quantum.md) | | 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-math.md](../design/stdlib-math.md) · [view.md](../design/view.md) | @@ -33,6 +33,9 @@ | **Q7a** | 密度矩阵 / Kronecker / 部分迹 / Hermitian 谱 / Schmidt / Pauli 期望 / 纯度·保真度 — [ext-quantum-q7.md](../design/ext-quantum-q7.md) | **done** | | **Q7b** | 高级 SVG:hinton / city / density / paulivec / qsphere / multibloch | **done** | | **Q7c** | 纠缠示例 + 用户文档 / skill 摘要 | **done** | +| **Q8a** | 电路 SVG:标签 gutter + dark/light/bw 门族分色 — [ext-quantum-viz-style.md](../design/ext-quantum-viz-style.md) | **done** | +| **Q8b** | probs / bloch / heatmap 共用令牌 | **done** (probs/bloch;heatmap → Q8c) | +| **Q8c** | 高级态图(hinton/city/…)换肤 | **pending** | 验收金样:既有 `tests/ext/quantum-*-smoke.mq.md`;Q7:`quantum-linalg-smoke`、`quantum-viz-advanced-smoke`。示例:`examples/quantum-bell/`、`examples/quantum-entanglement/`。 diff --git a/ext/quantum/quantum.mq.md b/ext/quantum/quantum.mq.md index 24bab25..fbaa186 100644 --- a/ext/quantum/quantum.mq.md +++ b/ext/quantum/quantum.mq.md @@ -191,10 +191,11 @@ Sample computational-basis shots (deterministic with `seed=`). Applies circuit ` + `path`=None + `kind`=circuit + `qubit`=0 + + `theme`=dark -Circuit rail / probability bars / Bloch / advanced state plots (`kind=circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`). Records into view/CLI plots via host `record_plot`. +Circuit rail / probability bars / Bloch / advanced state plots (`kind=circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`). Theme `dark` (default tech lab) / `light` / `bw`. Records into view/CLI plots via host `record_plot`. -**> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit`** +**> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit` theme=`theme`** ## density diff --git a/ext/quantum/量子.mq.md b/ext/quantum/量子.mq.md index 1c46f80..a393b0a 100644 --- a/ext/quantum/量子.mq.md +++ b/ext/quantum/量子.mq.md @@ -189,10 +189,11 @@ import json:lib/json.mq.md + `路径`=None + `种类`=circuit + `比特`=0 + + `主题`=dark -电路轨线 / 概率条 / 布洛赫 / 高级态图(种类 circuit、probs、bloch、hinton、city、density、paulivec、qsphere、multibloch)。经 record_plot 进入 view/CLI plots。 +电路轨线 / 概率条 / 布洛赫 / 高级态图(种类 circuit、probs、bloch、hinton、city、density、paulivec、qsphere、multibloch)。主题 dark(默认科技感)/ light / bw。经 record_plot 进入 view/CLI plots。 -**> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特`** +**> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特` theme=`主题`** ## 密度 diff --git a/plugins/quantum/src/draw.rs b/plugins/quantum/src/draw.rs index b8e88a7..734dc6c 100644 --- a/plugins/quantum/src/draw.rs +++ b/plugins/quantum/src/draw.rs @@ -1,17 +1,160 @@ -//! Circuit rail SVG (design §7.4). +//! Circuit rail SVG (design §7.4 + Q8 viz style). use serde_json::Value; use crate::sim::{parse_ops, C, Op}; -const COL_W: f64 = 56.0; -const ROW_H: f64 = 40.0; -const PAD_X: f64 = 48.0; -const PAD_Y: f64 = 24.0; -const WIRE: &str = "#1a1a1a"; +const COL_W: f64 = 80.0; +const ROW_H: f64 = 64.0; +const PAD_X: f64 = 24.0; +const PAD_Y: f64 = 36.0; +const LABEL_W: f64 = 52.0; +const GUTTER: f64 = 20.0; +const FONT_MONO: &str = "ui-monospace,Menlo,Consolas,monospace"; +const GATE_W: f64 = 40.0; +const GATE_H: f64 = 40.0; + +/// Legacy aliases used by older advanced-viz helpers until Q8c. const BOX: &str = "#f7f4ef"; const STROKE: &str = "#1a1a1a"; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ThemeName { + Dark, + Light, + Bw, +} + +impl ThemeName { + pub fn parse(raw: &str) -> Result { + match raw.trim().to_ascii_lowercase().as_str() { + "dark" | "暗" => Ok(Self::Dark), + "light" | "亮" | "浅" => Ok(Self::Light), + "bw" | "mono" | "黑白" => Ok(Self::Bw), + other => Err(format!("unknown theme `{other}` (dark|light|bw)")), + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Dark => "dark", + Self::Light => "light", + Self::Bw => "bw", + } + } +} + +#[derive(Clone, Copy)] +struct Theme { + name: ThemeName, + bg: &'static str, + bg2: &'static str, + panel: &'static str, + wire: &'static str, + label: &'static str, + chip: &'static str, + clifford_fill: &'static str, + clifford_ink: &'static str, + phase_fill: &'static str, + phase_ink: &'static str, + rotation_fill: &'static str, + rotation_ink: &'static str, + measure_fill: &'static str, + measure_ink: &'static str, + barrier: &'static str, + ctrl: &'static str, + accent: &'static str, + muted: &'static str, + axis: &'static str, + glow: &'static str, +} + +impl Theme { + fn of(name: ThemeName) -> Self { + match name { + ThemeName::Dark => Self { + name, + bg: "#0a0e14", + bg2: "#141c28", + panel: "#1a2433", + wire: "#6b7f96", + label: "#e8eef6", + chip: "#1e2a3a", + clifford_fill: "#4c6fff", + clifford_ink: "#f2f6ff", + phase_fill: "#2de2e6", + phase_ink: "#042024", + rotation_fill: "#3dd6c6", + rotation_ink: "#041a18", + measure_fill: "#8fa3b8", + measure_ink: "#0a1018", + barrier: "#9aafc0", + ctrl: "#f0f5ff", + accent: "#5b7cfa", + muted: "#93a4b8", + axis: "#7d8fa3", + glow: "#4c6fff", + }, + ThemeName::Light => Self { + name, + bg: "#eef3f9", + bg2: "#ffffff", + panel: "#e2eaf3", + wire: "#4a5a6a", + label: "#15202b", + chip: "#ffffff", + clifford_fill: "#3d5afe", + clifford_ink: "#ffffff", + phase_fill: "#00838f", + phase_ink: "#ffffff", + rotation_fill: "#00897b", + rotation_ink: "#ffffff", + measure_fill: "#546e7a", + measure_ink: "#ffffff", + barrier: "#78909c", + ctrl: "#1a237e", + accent: "#3d5afe", + muted: "#5a6a7a", + axis: "#4a5560", + glow: "#3d5afe", + }, + ThemeName::Bw => Self { + name, + bg: "#ffffff", + bg2: "#f7f7f7", + panel: "#eeeeee", + wire: "#222222", + label: "#111111", + chip: "#f0f0f0", + clifford_fill: "#ffffff", + clifford_ink: "#111111", + phase_fill: "#eeeeee", + phase_ink: "#111111", + rotation_fill: "#f5f5f5", + rotation_ink: "#111111", + measure_fill: "#e8e8e8", + measure_ink: "#111111", + barrier: "#666666", + ctrl: "#111111", + accent: "#333333", + muted: "#555555", + axis: "#222222", + glow: "#888888", + }, + } + } + + fn family_colors(self, family: &str) -> (&'static str, &'static str) { + match family { + "phase" => (self.phase_fill, self.phase_ink), + "rotation" => (self.rotation_fill, self.rotation_ink), + "measure" => (self.measure_fill, self.measure_ink), + "neutral" => (self.measure_fill, self.measure_ink), + _ => (self.clifford_fill, self.clifford_ink), + } + } +} + fn esc(s: &str) -> String { s.replace('&', "&") .replace('<', "<") @@ -19,6 +162,17 @@ fn esc(s: &str) -> String { .replace('"', """) } +fn gate_family(gate: &str) -> &'static str { + match gate { + "I" | "X" | "Y" | "Z" | "H" | "HADAMARD" | "CX" | "CNOT" | "CN" | "SWAP" => "clifford", + "S" | "T" | "RZ" | "CZ" => "phase", + "RX" | "RY" => "rotation", + "MEASURE" | "M" => "measure", + "BARRIER" => "barrier", + _ => "neutral", + } +} + fn gate_label(op: &Op) -> String { match op.gate.as_str() { "RX" => op @@ -39,16 +193,21 @@ fn gate_label(op: &Op) -> String { } } +fn rail_x0() -> f64 { + PAD_X + LABEL_W + GUTTER +} + fn y_of(q: usize) -> f64 { PAD_Y + q as f64 * ROW_H } fn x_of(col: usize) -> f64 { - PAD_X + col as f64 * COL_W + rail_x0() + (col as f64 + 0.5) * COL_W } /// Draw a circuit diagram as standalone SVG. -pub fn circuit_svg(circuit: &Value) -> Result { +pub fn circuit_svg(circuit: &Value, theme: ThemeName) -> Result { + let th = Theme::of(theme); let qubits = circuit .get("qubits") .or_else(|| circuit.get("比特数")) @@ -56,23 +215,53 @@ pub fn circuit_svg(circuit: &Value) -> Result { .ok_or_else(|| "circuit missing qubits".to_string())? as usize; let ops = parse_ops(circuit)?; let cols = ops.len().max(1); - let width = PAD_X + cols as f64 * COL_W + 32.0; - let height = PAD_Y * 2.0 + (qubits.saturating_sub(1).max(0) as f64) * ROW_H + 8.0; - let height = height.max(PAD_Y * 2.0 + 24.0); + let width = (rail_x0() + cols as f64 * COL_W + PAD_X).max(320.0); + let height = PAD_Y * 2.0 + (qubits.saturating_sub(1) as f64) * ROW_H; + let height = height.max(PAD_Y * 2.0 + GATE_H + 8.0); let mut body = String::new(); - // wires + body.push_str(&svg_defs(&th)); + body.push_str(&format!( + r##" +"##, + w = width, + h = height, + wi = width - 3.0, + hi = height - 3.0, + panel = th.panel, + )); + + let wire_x0 = rail_x0(); + let wire_x1 = width - PAD_X; + let label_x = PAD_X + LABEL_W - 6.0; for q in 0..qubits { let y = y_of(q); + // dual-tone wire for depth body.push_str(&format!( - r#""#, - x0 = 8.0, - x1 = width - 8.0, + r##" +"##, + x0 = wire_x0, + x1 = wire_x1, y = y, + wire = th.wire, )); + // label chip — wire never crosses text + let chip_w = 38.0; + let chip_h = 22.0; body.push_str(&format!( - r#"q{q}"#, - ty = y + 4.0, + r##" +q{q}"##, + rx = label_x - chip_w / 2.0, + ry = y - chip_h / 2.0, + chip_w = chip_w, + chip_h = chip_h, + chip = th.chip, + panel = th.panel, + lx = label_x, + y = y, + font = FONT_MONO, + fill = th.label, + q = q, )); } @@ -80,7 +269,7 @@ pub fn circuit_svg(circuit: &Value) -> Result { let x = x_of(col); match op.gate.as_str() { "BARRIER" => { - draw_barrier(&mut body, x, qubits); + draw_barrier(&mut body, x, qubits, &th); } "MEASURE" | "M" => { let qs = if op.qubits.is_empty() { @@ -89,145 +278,180 @@ pub fn circuit_svg(circuit: &Value) -> Result { op.qubits.clone() }; for q in qs { - draw_measure(&mut body, x, q); + draw_measure(&mut body, x, q, &th); } } "CX" | "CNOT" | "CN" if op.qubits.len() >= 2 => { - draw_cx(&mut body, x, op.qubits[0], op.qubits[1]); + draw_cx(&mut body, x, op.qubits[0], op.qubits[1], &th); } "CZ" if op.qubits.len() >= 2 => { - draw_cz(&mut body, x, op.qubits[0], op.qubits[1]); + draw_cz(&mut body, x, op.qubits[0], op.qubits[1], &th); } "SWAP" if op.qubits.len() >= 2 => { - draw_swap(&mut body, x, op.qubits[0], op.qubits[1]); + draw_swap(&mut body, x, op.qubits[0], op.qubits[1], &th); } _ => { let q = *op.qubits.first().unwrap_or(&0); - draw_box(&mut body, x, q, &gate_label(op)); + let fam = gate_family(&op.gate); + draw_box(&mut body, x, q, &gate_label(op), fam, &th); } } } Ok(format!( - r#"{body}"#, + r##"{body}"##, w = width, h = height, + theme = th.name.as_str(), body = body, )) } -fn draw_box(out: &mut String, x: f64, q: usize, label: &str) { +fn svg_defs(th: &Theme) -> String { + format!( + r##" + + + + + + + + + + + + +"##, + bg = th.bg, + bg2 = th.bg2, + glow = th.glow, + ) +} + +fn draw_box(out: &mut String, x: f64, q: usize, label: &str, family: &str, th: &Theme) { let y = y_of(q); - let w = 28.0; - let h = 28.0; + let w = GATE_W; + let h = GATE_H; + let (fill, ink) = th.family_colors(family); out.push_str(&format!( - r#""#, + r##" +{label}"##, rx = x - w / 2.0, ry = y - h / 2.0, - )); - out.push_str(&format!( - r#"{label}"#, - ty = y + 4.0, + w = w, + h = h, + fill = fill, + ink = ink, + fam = family, + x = x, + y = y, + font = FONT_MONO, label = esc(label), )); } -fn draw_barrier(out: &mut String, x: f64, qubits: usize) { - let y0 = y_of(0) - 14.0; - let y1 = y_of(qubits.saturating_sub(1)) + 14.0; +fn draw_barrier(out: &mut String, x: f64, qubits: usize, th: &Theme) { + let y0 = y_of(0) - 20.0; + let y1 = y_of(qubits.saturating_sub(1)) + 20.0; out.push_str(&format!( - r#""# + r##""##, + x = x, + y0 = y0, + y1 = y1, + c = th.barrier, )); } -fn draw_measure(out: &mut String, x: f64, q: usize) { +fn draw_measure(out: &mut String, x: f64, q: usize, th: &Theme) { let y = y_of(q); - let w = 28.0; - let h = 28.0; + let w = GATE_W; + let h = GATE_H; + let (fill, ink) = th.family_colors("measure"); out.push_str(&format!( - r#""#, + r##" + +"##, rx = x - w / 2.0, ry = y - h / 2.0, - )); - // meter arc + dial - out.push_str(&format!( - r#""#, - x0 = x - 8.0, - y0 = y + 2.0, - x1 = x + 8.0, - )); - out.push_str(&format!( - r#""#, - y1 = y + 2.0, - x2 = x + 6.0, - y2 = y - 6.0, + w = w, + h = h, + fill = fill, + ink = ink, + x0 = x - 11.0, + y0 = y + 4.0, + x1 = x + 11.0, + x = x, + y1 = y + 4.0, + x2 = x + 8.0, + y2 = y - 8.0, )); } -fn draw_cx(out: &mut String, x: f64, control: usize, target: usize) { +fn draw_cx(out: &mut String, x: f64, control: usize, target: usize, th: &Theme) { + let yc = y_of(control); + let yt = y_of(target); + let (fill, _) = th.family_colors("clifford"); + let r = 13.0; + out.push_str(&format!( + r##" + + + +"##, + x = x, + yc = yc, + yt = yt, + ctrl = th.ctrl, + fill = fill, + r = r, + a = yt - r, + b = yt + r, + a2 = x - r, + b2 = x + r, + )); +} + +fn draw_cz(out: &mut String, x: f64, control: usize, target: usize, th: &Theme) { let yc = y_of(control); let yt = y_of(target); out.push_str(&format!( - r#""# - )); - out.push_str(&format!( - r#""# - )); - out.push_str(&format!( - r#""# - )); - out.push_str(&format!( - r#""#, - a = yt - 10.0, - b = yt + 10.0, - )); - out.push_str(&format!( - r#""#, - a = x - 10.0, - b = x + 10.0, + r##" + +"##, + x = x, + yc = yc, + yt = yt, + c = th.phase_fill, )); } -fn draw_cz(out: &mut String, x: f64, control: usize, target: usize) { - let yc = y_of(control); - let yt = y_of(target); - out.push_str(&format!( - r#""# - )); - out.push_str(&format!( - r#""# - )); - out.push_str(&format!( - r#""# - )); -} - -fn draw_swap(out: &mut String, x: f64, a: usize, b: usize) { +fn draw_swap(out: &mut String, x: f64, a: usize, b: usize, th: &Theme) { let ya = y_of(a); let yb = y_of(b); out.push_str(&format!( - r#""# + r##""##, + x = x, + ya = ya, + yb = yb, + c = th.ctrl, )); for y in [ya, yb] { out.push_str(&format!( - r#""#, - x0 = x - 8.0, - y0 = y - 8.0, - x1 = x + 8.0, - y1 = y + 8.0, - )); - out.push_str(&format!( - r#""#, - x0 = x - 8.0, - y0 = y + 8.0, - x1 = x + 8.0, - y1 = y - 8.0, + r##" +"##, + x0 = x - 10.0, + y0 = y - 10.0, + x1 = x + 10.0, + y1 = y + 10.0, + c = th.ctrl, )); } } /// Probability histogram from basis-label → probability map. -pub fn probs_svg(probs: &serde_json::Map) -> String { +pub fn probs_svg(probs: &serde_json::Map, theme: ThemeName) -> String { + let th = Theme::of(theme); let mut entries: Vec<(String, f64)> = probs .iter() .filter_map(|(k, v)| v.as_f64().map(|p| (k.clone(), p))) @@ -242,89 +466,108 @@ pub fn probs_svg(probs: &serde_json::Map) -> String { let chart_h = 120.0; let pad_l = 40.0; let pad_b = 36.0; - let pad_t = 20.0; + let pad_t = 24.0; let pad_r = 16.0; let width = pad_l + n as f64 * (bar_w + gap) + pad_r; let height = pad_t + chart_h + pad_b; let mut body = String::new(); - // axis + body.push_str(&svg_defs(&th)); body.push_str(&format!( - r#""#, + r##""##, + w = width, + h = height, + )); + body.push_str(&format!( + r##""##, x0 = pad_l - 4.0, x1 = width - pad_r, y = pad_t + chart_h, + axis = th.axis, )); body.push_str(&format!( - r#""#, + r##""##, x = pad_l - 4.0, y0 = pad_t, y1 = pad_t + chart_h, + axis = th.axis, )); body.push_str(&format!( - r#"1"#, + r##"1"##, ty = pad_t + 4.0, + font = FONT_MONO, + lab = th.label, )); body.push_str(&format!( - r#"0"#, + r##"0"##, ty = pad_t + chart_h + 4.0, + font = FONT_MONO, + lab = th.label, )); for (i, (label, p)) in entries.iter().enumerate() { let p = (*p).clamp(0.0, 1.0); let h = p * chart_h; let x = pad_l + i as f64 * (bar_w + gap); let y = pad_t + chart_h - h; - let bar_fill = "#4a6fa5"; - let muted = "#555"; body.push_str(&format!( - r#""#, + r##""##, x = x, y = y, bar_w = bar_w, - h = h, - bar_fill = bar_fill, - STROKE = STROKE, + h = h.max(0.5), + fill = th.accent, + ink = th.ctrl, )); body.push_str(&format!( - r#"{lab}"#, + r##"{lab_t}"##, cx = x + bar_w / 2.0, - ty = pad_t + chart_h + 16.0, - lab = esc(label), - STROKE = STROKE, + ty = pad_t + chart_h + 18.0, + font = FONT_MONO, + lab = th.label, + lab_t = esc(label), )); body.push_str(&format!( - r#"{pval:.2}"#, + r##"{pval:.2}"##, cx = x + bar_w / 2.0, - ty = y - 4.0, + ty = y - 5.0, + font = FONT_MONO, + muted = th.muted, pval = p, - muted = muted, )); } format!( - r#"{body}"#, + r##"{body}"##, w = width, h = height, + theme = th.name.as_str(), body = body, ) } /// 2D Bloch sphere projection with state arrow. -pub fn bloch_svg(x: f64, y: f64, z: f64) -> String { - let cx = 110.0; - let cy = 110.0; - let r = 70.0; - let width = 220.0; - let height = 240.0; +pub fn bloch_svg(x: f64, y: f64, z: f64, theme: ThemeName) -> String { + let th = Theme::of(theme); + let cx = 130.0; + let cy = 125.0; + let r = 82.0; + let width = 280.0; + let height = 290.0; // Project: X right, Z up, Y into page (slight oblique). let px = |vx: f64, vy: f64, _vz: f64| cx + r * (vx * 0.85 + vy * 0.35); let py = |_vx: f64, vy: f64, vz: f64| cy - r * (vz * 0.9 - vy * 0.25); let mut body = String::new(); + body.push_str(&svg_defs(&th)); body.push_str(&format!( - r#""#, + r##""##, + w = width, + h = height, + )); + body.push_str(&format!( + r##""##, cx = cx, cy = cy, r = r, - fill = BOX, - STROKE = STROKE, + fill = th.clifford_fill, + stroke = th.wire, )); // axes let axes = [ @@ -340,19 +583,20 @@ pub fn bloch_svg(x: f64, y: f64, z: f64) -> String { let x2 = px(vx, vy, vz); let y2 = py(vx, vy, vz); body.push_str(&format!( - r#""#, + r##""##, x1 = x1, y1 = y1, x2 = x2, y2 = y2, - axis = "#888", + axis = th.axis, )); body.push_str(&format!( - r#"{lab}"#, + r##"{lab}"##, tx = x2 + 4.0, ty = y2 + 3.0, + font = FONT_MONO, + lab_c = th.label, lab = lab, - STROKE = STROKE, )); } // state vector @@ -360,9 +604,9 @@ pub fn bloch_svg(x: f64, y: f64, z: f64) -> String { let sy = py(x, y, z); let ox = px(0.0, 0.0, 0.0); let oy = py(0.0, 0.0, 0.0); - let arrow = "#c0392b"; + let arrow = th.phase_fill; body.push_str(&format!( - r#""#, + r##""##, ox = ox, oy = oy, sx = sx, @@ -370,23 +614,26 @@ pub fn bloch_svg(x: f64, y: f64, z: f64) -> String { arrow = arrow, )); body.push_str(&format!( - r#""#, + r##""##, sx = sx, sy = sy, arrow = arrow, + ctrl = th.ctrl, )); body.push_str(&format!( - r#"⟨X⟩={bx:.3} ⟨Y⟩={by:.3} ⟨Z⟩={bz:.3}"#, + r##"⟨X⟩={bx:.3} ⟨Y⟩={by:.3} ⟨Z⟩={bz:.3}"##, hy = height - 12.0, + font = FONT_MONO, + lab = th.label, bx = x, by = y, bz = z, - STROKE = STROKE, )); format!( - r#"{body}"#, + r##"{body}"##, w = width, h = height, + theme = th.name.as_str(), body = body, ) } @@ -806,8 +1053,7 @@ pub fn multibloch_svg(amps: &[C], qubits: usize) -> Result { body.push_str(r##"multibloch"##); for q in 0..qubits { let (x, y, z) = crate::sim::bloch_vector(amps, qubits, q)?; - let svg = bloch_svg(x, y, z); - // extract inner content roughly by offsetting — simpler: draw mini sphere + // Mini sphere (Q8c will share Theme tokens fully). let ox = 8.0 + q as f64 * sphere_w; let cx = ox + 60.0; let cy = 90.0; @@ -841,7 +1087,7 @@ pub fn multibloch_svg(amps: &[C], qubits: usize) -> Result { px = px, py = py, )); - let _ = (y, svg); + let _ = y; } Ok(format!( r#"{body}"#, diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs index 4a275f8..72081af 100644 --- a/plugins/quantum/src/lib.rs +++ b/plugins/quantum/src/lib.rs @@ -415,6 +415,17 @@ q_ffi!(quantum_state, |args: &Value| { })) }); +fn draw_theme_of(args: &Value) -> Result { + match args + .get("theme") + .or_else(|| args.get("主题")) + .and_then(|v| v.as_str()) + { + None => Ok(draw::ThemeName::Dark), + Some(s) => draw::ThemeName::parse(s), + } +} + q_ffi!(quantum_draw_circuit, |args: &Value| { let c = circuit_of(args)?; let kind = args @@ -423,6 +434,7 @@ q_ffi!(quantum_draw_circuit, |args: &Value| { .and_then(|v| v.as_str()) .unwrap_or("circuit") .to_ascii_lowercase(); + let theme = draw_theme_of(args)?; let qubit = arg_u(args, "qubit") .or_else(|_| arg_u(args, "比特")) .unwrap_or(0); @@ -433,16 +445,16 @@ q_ffi!(quantum_draw_circuit, |args: &Value| { .filter(|s| !s.is_empty()); let (kind_out, svg) = match kind.as_str() { - "circuit" | "" => ("circuit", draw::circuit_svg(c)?), + "circuit" | "" => ("circuit", draw::circuit_svg(c, theme)?), "probs" | "probabilities" | "概率" => { let (qubits, amps) = sim::simulate_circuit(c)?; let probs = sim::probabilities(&s, qubits); - ("probs", draw::probs_svg(&probs)) + ("probs", draw::probs_svg(&probs, theme)) } "bloch" | "布洛赫" => { let (qubits, amps) = sim::simulate_circuit(c)?; let (x, y, z) = sim::bloch_vector(&s, qubits, qubit)?; - ("bloch", draw::bloch_svg(x, y, z)) + ("bloch", draw::bloch_svg(x, y, z, theme)) } "hinton" | "欣顿" => { let (n, amps) = sim::simulate_circuit(c)?; diff --git a/src/view/html.rs b/src/view/html.rs index 18631e6..8b7ae98 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -1074,11 +1074,22 @@ section.block > h2 { display: flex; justify-content: center; } +.plot:has(svg[data-theme="dark"]) { + background: #070b10; + border-color: #1c2838; + padding: 1.1rem 1.25rem; +} +.plot:has(svg[data-theme="light"]), +.plot:has(svg[data-theme="bw"]) { + background: #f7f9fc; + border-color: #d5dde8; +} .plot svg { display: block; max-width: 100%; height: auto; margin-inline: auto; + min-width: min(100%, 28rem); } .comment-text { color: var(--muted); diff --git a/tests/gold.rs b/tests/gold.rs index c0d2c84..2123de4 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -2430,8 +2430,13 @@ fn ext_quantum_steps_smoke() { let svg_path = "tests/ext/quantum-steps-draw.svg"; let svg = std::fs::read_to_string(svg_path).unwrap_or_default(); assert!( - svg.contains("