feat(quantum): Q7 density linear algebra and advanced SVG viz
Add density-matrix ops (partial trace, Hermitian eig, Schmidt, Pauli expect, purity/fidelity, kron) and hinton/city/qsphere/paulivec/multibloch draw kinds via plugins/quantum ABI, with EN/ZH L1 and gold smokes. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
4956460773
commit
88fe076216
13 files changed
+1871
-8
No files matched your search
@@ -6,6 +6,7 @@
|
||||
- **`ext/web` 样式装配(`web_style` / `网页.样式装配`)**: 样式即数据表格 —— GFM 样式表(`|选择器|属性|值|`,可用 `|媒体|` 列分组进 `@media` 块)经 `样式装配` 函数转成 CSS 文本,再拼装成完整主题。替代"整段手写 CSS 字符串"的写法,贯彻 文档即代码。见 [marqdo-blog](examples/marqdo-blog/styles/theme.mq.md)。
|
||||
- **网络能力调研(`doc/design/web-net-capabilities.md`)**: 盘点 `ext/web` + `plugins/web` + `lib/net` 现状,对照主流语言网络栈(FastAPI / Express / Flask / axum),给出「开发一个完整 Web 项目」所需能力的差距清单与分波次补强路线(W1–W7 + P3,**2026-08-28 已全部落地**)。
|
||||
- **AI Skill + 文档(ext/web 完结复核)**: `skills/marqdo/` 与 `.cursor/skills/marqdo/` 增加 **ext/web 动态站** 专节(硬规则、API 摘要、§13 最小站点样例);`doc/design/web-net-capabilities.md` 结论/对照表与 W7+P3 实现对齐;`doc/design/ai-skill.md` 更新用途说明。
|
||||
- **`ext/quantum` Q7(高阶线性代数 + 高级可视化)**: 密度矩阵 / 部分迹 / Hermitian 谱 / Schmidt / Pauli 期望 / 纯度;SVG:hinton、city、density、paulivec、qsphere、multibloch。全部经 `plugins/quantum` ABI。设计 [ext-quantum-q7.md](doc/design/ext-quantum-q7.md);金样 `quantum-linalg-smoke`、`quantum-viz-advanced-smoke`。
|
||||
|
||||
### Changed
|
||||
- **Frontmatter import syntax**: `import bind:target` / `导入 bind:target` (file `.mq.md` or short name `lib.member`). Removed legacy `> path.mq.md` / `> use` imports. See [module-namespace.md](doc/design/module-namespace.md).
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
# `ext/quantum` Q7 — 高阶线性代数 + 高级可视化
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted · Q7a/Q7b 已落地**(Q7c 示例/文档摘要可跟进) |
|
||||
| 日期 | 2026-08-28 |
|
||||
| 父设计 | [ext-quantum.md](ext-quantum.md) |
|
||||
| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
|
||||
| 对照 | [IBM Quantum state plots](https://quantum.cloud.ibm.com/docs/en/guides/plot-quantum-states) · [QuTiP visualization](https://qutip.readthedocs.io/en/latest/guide/guide-visualization.html) · Cirq `plot_density_matrix` |
|
||||
|
||||
---
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
在 **Q0–Q6 态向量教学模拟**之上,补齐两块「教科书级」能力:
|
||||
|
||||
1. **高阶线性代数**(密度矩阵、Kronecker、部分迹、Hermitian 谱分解、Schmidt / SVD、Pauli 期望值)
|
||||
2. **高级静态 SVG 展示**(Hinton / City / Pauli 向量 / QSphere 风格 / 多比特布洛赫)
|
||||
|
||||
全部经 **`plugins/quantum` ABI**;`ext/quantum/**` 只做 L1 表包装,**禁止** `host_*`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 动机与业界对照(联网调研 2026-08)
|
||||
|
||||
### 1.1 为何现在做
|
||||
|
||||
| 已有(Q0–Q6) | 缺口 |
|
||||
|---------------|------|
|
||||
| 纯态态向量 + 施门 + 采样 | 混态 / 约化子系统无法一等公民表达 |
|
||||
| `bloch` 单比特约化 | 纠缠与多比特关联只能猜 |
|
||||
| `gate.draw kind=matrix` 热力图 | 无密度矩阵 / Pauli 分解 / 球面振幅布局 |
|
||||
| 内部 `apply_unitary` / Kronecker | **未**暴露为作者面 API |
|
||||
|
||||
教学文档写「贝尔态纠缠」时,读者需要:**约化密度矩阵 → 纯度 < 1 → Schmidt 系数 → Hinton/QSphere 图**。这些正是 Qiskit / QuTiP / Cirq 的标配。
|
||||
|
||||
### 1.2 可视化对标(只取可静态 SVG 落地的子集)
|
||||
|
||||
| 业界 | 含义 | Q7 决策 |
|
||||
|------|------|---------|
|
||||
| Qiskit `plot_state_hinton` | 元大小表示幅值,色表示正负 | ✅ `kind=hinton` |
|
||||
| Qiskit `plot_state_city` | Re/Im 三维条 | ✅ **2.5D 等轴测 SVG**(非 Matplotlib) |
|
||||
| Qiskit `plot_state_paulivec` | Pauli 串期望值柱 | ✅ `kind=paulivec` |
|
||||
| Qiskit `plot_state_qsphere` | 振幅点在球面上,色=相位 | ✅ `kind=qsphere`(教学投影) |
|
||||
| Qiskit `plot_bloch_multivector` | 每比特一球 | ✅ `kind=multibloch` |
|
||||
| Cirq density Argand 格 | 每元幅值圆 + 相位针 | ✅ 并入 `kind=density`(默认) |
|
||||
| QuTiP Wigner / 过程层析 | 连续相空间 / χ 矩阵 | ❌ 本切片不做 |
|
||||
|
||||
### 1.3 线性代数对标(经典模拟侧,非量子算法)
|
||||
|
||||
| 能力 | 教学用途 | Q7 |
|
||||
|------|----------|-----|
|
||||
| ρ = \|ψ⟩⟨ψ\| | 纯→密度 | ✅ |
|
||||
| Kronecker / 张量积 | 复合系统 | ✅ |
|
||||
| 部分迹 | 约化、纠缠证据 | ✅ |
|
||||
| Hermitian 本征分解 | 谱 / 测量可观测量 | ✅(小维) |
|
||||
| Schmidt(纯态二分)= 整形 SVD | 纠缠熵入口 | ✅ |
|
||||
| Pauli 期望 ⟨P⟩ | 布洛赫 / paulivec 数据源 | ✅ |
|
||||
| 纯度 Tr(ρ²)、保真度 | 混态度量 | ✅ 最小 |
|
||||
| 量子奇异值变换 / VQSVD / 云后端 | 算法研究 | ❌ |
|
||||
|
||||
---
|
||||
|
||||
## 2. 硬约束(沿用 + 本切片追加)
|
||||
|
||||
1. **仅 ABI**:新 FFI 全部注册在 `marqdo_plugin_init`;L1 经 `plugin.load`。
|
||||
2. **`ext/**` 无 `host_*`**。
|
||||
3. **中英分文件**,禁止混 API。
|
||||
4. **维数上限**:
|
||||
- 态向量模拟:仍 ≤ 12 qubits(既有)。
|
||||
- **密度矩阵稠密运算**(部分迹结果展示、谱分解、Hinton/City):默认 **≤ 6 qubits**(dim ≤ 64);超限显式报错。
|
||||
5. **无新核心依赖**:插件内手写复数矩阵 + Jacobi / 薄 SVD;**不**捆绑 BLAS / nalgebra(可后续再议)。
|
||||
6. **view**:仍走 `host_query("record_plot")` + `quantum_svg`;无外链字体/CDN。
|
||||
|
||||
---
|
||||
|
||||
## 3. 新运行时类型
|
||||
|
||||
| `_type`(英) | 中文 | 字段(锁定) |
|
||||
|---------------|------|----------------|
|
||||
| `quantum_state` | `量子态` | 既有:`qubits`, `amplitudes:[{re,im}]` |
|
||||
| `quantum_density` | `密度矩阵` | `qubits`, `dim`, `matrix`(dim×dim 嵌套 `{re,im}`) |
|
||||
| `quantum_spectrum` | `谱` | `eigenvalues:[f64]`, `eigenvectors`(列向量嵌套 list) |
|
||||
| `quantum_schmidt` | `施密特` | `coeffs:[f64]`, `ua`, `ub`(局域基),`entropy`(可选) |
|
||||
| `quantum_svg` | — | 既有;`kind` 扩展见 §5 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 作者面 API
|
||||
|
||||
### 4.1 英文(`ext/quantum/quantum.mq.md`)
|
||||
|
||||
在既有 `# circuit` / `# gate` 之外增加(或扩展方法):
|
||||
|
||||
```markdown
|
||||
# density
|
||||
+ `state`=None # quantum_state 或 circuit(先 simulate)
|
||||
+ `matrix`=None # 直接给定 ρ
|
||||
|
||||
## matrix # → 嵌套 list
|
||||
## purity # Tr(ρ²)
|
||||
## expect
|
||||
+ `obs` # Pauli 串 "ZI" / "XX" 或门矩阵
|
||||
## partial_trace
|
||||
+ `keep` # 保留的比特列表(LSB=0)
|
||||
## eig # Hermitian 谱 → quantum_spectrum
|
||||
## draw
|
||||
+ `kind`=hinton # hinton|city|density|paulivec
|
||||
+ `path`=None
|
||||
|
||||
# linop # 自由线性代数(也可挂在 quantum.* 模块函数)
|
||||
## kron
|
||||
+ `a`
|
||||
+ `b` # 矩阵或态 → 张量积
|
||||
## schmidt
|
||||
+ `state`
|
||||
+ `cut`=1 # 前 cut 个比特为 A,其余为 B
|
||||
## fidelity
|
||||
+ `a`
|
||||
+ `b` # 两态或两密度(纯态公式优先)
|
||||
```
|
||||
|
||||
**电路侧便捷方法**(返回新句柄,不改旧对象):
|
||||
|
||||
```markdown
|
||||
## density # simulate 后 ρ=|ψ⟩⟨ψ|
|
||||
## expect
|
||||
+ `obs`
|
||||
## schmidt
|
||||
+ `cut`=1
|
||||
## draw
|
||||
+ `kind`=… # 扩展:hinton|city|density|paulivec|qsphere|multibloch
|
||||
```
|
||||
|
||||
### 4.2 中文对称
|
||||
|
||||
| 英文 | 中文 |
|
||||
|------|------|
|
||||
| `density` | `密度` |
|
||||
| `partial_trace` | `部分迹` |
|
||||
| `purity` | `纯度` |
|
||||
| `expect` | `期望` |
|
||||
| `eig` | `本征` |
|
||||
| `kron` | `张量积` |
|
||||
| `schmidt` | `施密特` |
|
||||
| `fidelity` | `保真度` |
|
||||
| `hinton` / `city` / `paulivec` / `qsphere` / `multibloch` | 同音译或 `欣顿`/`城市`/`泡利向量`/`球`/`多布洛赫`(L1 锁定中英别名表) |
|
||||
|
||||
### 4.3 ABI 函数名(稳定英文)
|
||||
|
||||
| FFI | 作用 |
|
||||
|-----|------|
|
||||
| `quantum_density_from_state` | 态 / 电路 → `quantum_density` |
|
||||
| `quantum_density_from_matrix` | 校验 Hermitian / 维数 → 句柄 |
|
||||
| `quantum_density_matrix` | 取出嵌套矩阵 |
|
||||
| `quantum_density_purity` | Tr(ρ²) |
|
||||
| `quantum_density_partial_trace` | keep 列表 |
|
||||
| `quantum_density_eig` | Jacobi Hermitian |
|
||||
| `quantum_density_expect` | Pauli 串或矩阵 |
|
||||
| `quantum_density_draw` | hinton/city/density/paulivec |
|
||||
| `quantum_kron` | 两矩阵或两态振幅 |
|
||||
| `quantum_schmidt` | 纯态二分 |
|
||||
| `quantum_fidelity` | 两态 |
|
||||
| `quantum_draw_circuit` | **扩展** kind 枚举(向后兼容) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 高级绘图语义
|
||||
|
||||
| `kind` | 输入 | SVG 要点 |
|
||||
|--------|------|----------|
|
||||
| `hinton` | ρ | 网格方块;边长 ∝ √\|ρᵢⱼ\|;正 Re 浅 / 负深;小 dim 可标数值 |
|
||||
| `city` | ρ | 等轴测「楼宇」:左 Re、右 Im 两城,或单城双色柱 |
|
||||
| `density` | ρ | Cirq 风格:每格幅值圆 + 相位线段;对角概率矩形 |
|
||||
| `paulivec` | 态或 ρ | 全 Pauli 基(n≤3)或用户 `ops=` 列表;柱高 = ⟨P⟩ |
|
||||
| `qsphere` | 纯态 | 基矢点映射到球/圆;半径∝振幅,色相∝arg;n≤4 推荐 |
|
||||
| `multibloch` | 纯态 | 每比特约化布洛赫并排 |
|
||||
|
||||
既有 `circuit|probs|bloch|gate|matrix` **不变**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 数值语义(锁定)
|
||||
|
||||
| 项 | 规则 |
|
||||
|----|------|
|
||||
| 比特序 | **qubit 0 = LSB**(与既有概率标签一致) |
|
||||
| `partial_trace keep=` | 保留比特升序组成新系统的 LSB…MSB |
|
||||
| Pauli 串 | 左→右 = **高位→低位** 或文档写死「左=qubit n-1」——**锁定:字符串左端 = 最高比特(qubit n−1)**,与 Qiskit 习惯一致;文档 + 金样双锁 |
|
||||
| Hermitian 检查 | ‖ρ−ρ†‖_F < 1e-8,否则报错 |
|
||||
| 谱 | 实特征值降序;特征向量列归一 |
|
||||
| Schmidt | 将 \|ψ⟩ 整形为 `2^cut × 2^(n-cut)` 复矩阵做薄 SVD;奇异值 = Schmidt 系数 |
|
||||
| 纯度 | 纯态 ≈ 1;最大混态 = 1/dim |
|
||||
|
||||
---
|
||||
|
||||
## 7. 分期交付
|
||||
|
||||
| 子阶段 | 内容 | 验收 |
|
||||
|--------|------|------|
|
||||
| **Q7a** | density / kron / partial_trace / eig / schmidt / expect / purity / fidelity + L1 中英 | `tests/ext/quantum-linalg-smoke.mq.md`(+ zh) |
|
||||
| **Q7b** | draw kinds:hinton, city, density, paulivec, qsphere, multibloch | `tests/ext/quantum-viz-advanced-smoke.mq.md`(SVG 含关键标记) |
|
||||
| **Q7c** | 示例页 + 用户站短页 + skill/reference 摘要 | `examples/quantum-entanglement/` 或扩展 bell |
|
||||
|
||||
---
|
||||
|
||||
## 8. 刻意不做(本 Q7)
|
||||
|
||||
- 任意 Kraus / 完整 CPTP 通道库(仍用 Q5 轨迹噪声)
|
||||
- >6 qubit 稠密 ρ 的谱 / Hinton(请用态向量 API)
|
||||
- Matplotlib / WebGL / 交互拖拽
|
||||
- 量子线性系统算法(HHL)、QSVT 电路构造
|
||||
- 把线性代数并入 `lib/math`
|
||||
|
||||
---
|
||||
|
||||
## 9. 评审清单
|
||||
|
||||
1. 密度矩阵上限 6 qubits 是否可接受?
|
||||
2. Pauli 串左右端比特约定是否锁定为「左=高比特」?
|
||||
3. City 用 2.5D SVG 而非真 3D 是否足够?
|
||||
4. `# density` 独立类 vs 仅 `circuit.density` —— **两者都提供**(类用于给定矩阵;电路方法便捷)?
|
||||
|
||||
评审默认:**全部锁定为上文**;实现按 Q7a → Q7b → Q7c。
|
||||
|
||||
---
|
||||
|
||||
## 10. 一句话
|
||||
|
||||
**Q7 让 Marqdo 量子文档能「算清纠缠、画清态」:线性代数在 ABI 里跑,高级图用自绘 SVG 进 view——仍是代码即文档。**
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Accepted · Q0–Q5.5 已落地**(教学噪声含振幅阻尼;完整开放系统另文) |
|
||||
| 日期 | 2026-08-12 |
|
||||
| 状态 | **Accepted · Q0–Q6 已落地 · Q7 进行中**([ext-quantum-q7.md](ext-quantum-q7.md):高阶线性代数 + 高级可视化) |
|
||||
| 日期 | 2026-08-12(初版)· 2026-08-28(Q7) |
|
||||
| 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [ext-web.md](ext-web.md) · [view.md](view.md) · [stdlib-i18n.md](stdlib-i18n.md) · [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
|
||||
| 安装(目标) | `marqdo ext add quantum`(中英:`quantum` / `量子`) |
|
||||
| 本文目的 | 锁定**作者面**、**模拟语义**、**view 可视化**与**分期**;指导 ABI 插件实现 |
|
||||
@@ -323,6 +323,8 @@ Q5 教学噪声 + barrier/measure/append/state — 见 [ext-quantum-q5.md](ext-
|
||||
| **Q3** | `steps=` 表;`draw` SVG 在 `view` HTML 含 `<svg` | 与 math-plot 同级断言 |
|
||||
| **Q4** | 概率图 + 布洛赫;`matches_matrix`;用户文档页 | `quantum-draw-smoke` / `quantum-gate-matrix-smoke`;`view output` 可浏览示例 |
|
||||
| **Q5** | `noise` 轨迹;`barrier`/`measure`/`append`/`state` | `quantum-noise-smoke` / `quantum-author-api-smoke` |
|
||||
| **Q6** | 公式/`matrix=` 自定义门 | [ext-quantum-custom-gate.md](ext-quantum-custom-gate.md) |
|
||||
| **Q7** | 密度矩阵线性代数 + Hinton/City/QSphere 等 SVG | [ext-quantum-q7.md](ext-quantum-q7.md) |
|
||||
|
||||
实现路线图跟踪见 [roadmap/ext-quantum.md](../roadmap/ext-quantum.md)。
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Q0–Q6 已落地**(含公式自定义门;更大 n / 完整开放系统另文) |
|
||||
| 日期 | 2026-08-12 |
|
||||
| 状态 | **Q0–Q7b 已落地 · Q7c 待补**(高阶线性代数 + 高级可视化) |
|
||||
| 日期 | 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) |
|
||||
| 安装 | `marqdo ext add quantum`(`quantum` / `量子`) |
|
||||
@@ -30,8 +30,11 @@
|
||||
| **Q5** | 教学噪声 + barrier/measure/append/state — [ext-quantum-q5.md](../design/ext-quantum-q5.md) | **done(最小)** |
|
||||
| **Q5.5** | `amplitude_damping` 轨迹 — [ext-quantum-q5.5.md](../design/ext-quantum-q5.5.md) | **done** |
|
||||
| **Q6** | 公式/`matrix=` 自定义门 + `apply` — [ext-quantum-custom-gate.md](../design/ext-quantum-custom-gate.md) | **done** |
|
||||
| **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 摘要 | **pending** |
|
||||
|
||||
验收金样:`tests/ext/quantum-bell-smoke.mq.md`、`quantum-draw-smoke.mq.md`、`quantum-gate-matrix-smoke.mq.md`、`quantum-gate-heatmap-smoke.mq.md`、`quantum-author-api-smoke.mq.md`、`quantum-noise-smoke.mq.md`、`quantum-amp-damp-smoke.mq.md`、`quantum-custom-gate-smoke.mq.md`、中文对称样例。
|
||||
验收金样:既有 `tests/ext/quantum-*-smoke.mq.md`;Q7 新增 `quantum-linalg-smoke`、`quantum-viz-advanced-smoke`(及中文对称)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -18,6 +18,33 @@ Load the ABI v2 `quantum` plugin once.
|
||||
> sys.exit code=1
|
||||
****
|
||||
|
||||
## kron
|
||||
+ `a`
|
||||
+ `b`
|
||||
|
||||
Tensor product of two states or square matrices.
|
||||
|
||||
> ensure_plugin
|
||||
**> quantum_kron a=`a` b=`b`**
|
||||
|
||||
## schmidt
|
||||
+ `state`
|
||||
+ `cut`=1
|
||||
|
||||
Schmidt decomposition of a pure state / circuit across `cut` (subsystem A = low qubits).
|
||||
|
||||
> ensure_plugin
|
||||
**> quantum_schmidt state=`state` cut=`cut`**
|
||||
|
||||
## fidelity
|
||||
+ `a`
|
||||
+ `b`
|
||||
|
||||
Pure-state fidelity |⟨a|b⟩|².
|
||||
|
||||
> ensure_plugin
|
||||
**> quantum_fidelity a=`a` b=`b`**
|
||||
|
||||
# circuit
|
||||
+ `qubits`=1
|
||||
+ `steps`=None
|
||||
@@ -165,10 +192,30 @@ Sample computational-basis shots (deterministic with `seed=`). Applies circuit `
|
||||
+ `kind`=circuit
|
||||
+ `qubit`=0
|
||||
|
||||
Circuit rail / probability bars / Bloch sphere SVG (`kind=circuit|probs|bloch`). 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`). Records into view/CLI plots via host `record_plot`.
|
||||
|
||||
**> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit`**
|
||||
|
||||
## density
|
||||
|
||||
Pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulate.
|
||||
|
||||
**> density state=`self`**
|
||||
|
||||
## expect
|
||||
+ `obs`
|
||||
|
||||
Pauli string (left = high bit) or matrix expectation on the ideal state.
|
||||
|
||||
**> quantum_density_expect density=`self` obs=`obs`**
|
||||
|
||||
## schmidt
|
||||
+ `cut`=1
|
||||
|
||||
Schmidt / singular values across a bipartition (`cut` = qubits in subsystem A, low bits).
|
||||
|
||||
**> quantum_schmidt state=`self` cut=`cut`**
|
||||
|
||||
# gate
|
||||
+ `name`=None
|
||||
+ `theta`=None
|
||||
@@ -196,3 +243,51 @@ Named built-in gate (`name=H`) or custom unitary from `matrix=` (nested list or
|
||||
Gate glyph or complex-matrix heatmap (`kind=gate|matrix`). Records via host `record_plot`.
|
||||
|
||||
**> quantum_gate_draw gate=`self` path=`path` kind=`kind`**
|
||||
|
||||
# density
|
||||
+ `state`=None
|
||||
+ `matrix`=None
|
||||
|
||||
Density matrix from a state/circuit (`state=`) or an explicit Hermitian `matrix=` (≤6 qubits).
|
||||
|
||||
> ensure_plugin
|
||||
1. `matrix`
|
||||
**> quantum_density_from_matrix matrix=`matrix`**
|
||||
2. *
|
||||
**> quantum_density_from_state state=`state`**
|
||||
|
||||
## matrix
|
||||
|
||||
**> quantum_density_matrix density=`self`**
|
||||
|
||||
## purity
|
||||
|
||||
Tr(ρ²).
|
||||
|
||||
**> quantum_density_purity density=`self`**
|
||||
|
||||
## partial_trace
|
||||
+ `keep`
|
||||
|
||||
Keep listed qubits (LSB=0); trace out the rest.
|
||||
|
||||
**> quantum_density_partial_trace density=`self` keep=`keep`**
|
||||
|
||||
## eig
|
||||
|
||||
Hermitian spectrum → `{eigenvalues, eigenvectors}`.
|
||||
|
||||
**> quantum_density_eig density=`self`**
|
||||
|
||||
## expect
|
||||
+ `obs`
|
||||
|
||||
**> quantum_density_expect density=`self` obs=`obs`**
|
||||
|
||||
## draw
|
||||
+ `path`=None
|
||||
+ `kind`=hinton
|
||||
|
||||
Hinton / city / density-cells / Pauli vector SVG (`kind=hinton` or city or density or paulivec).
|
||||
|
||||
**> quantum_density_draw density=`self` path=`path` kind=`kind`**
|
||||
+94
-1
@@ -18,6 +18,31 @@ import json:lib/json.mq.md
|
||||
> sys.exit code=1
|
||||
****
|
||||
|
||||
## 张量积
|
||||
+ `左`
|
||||
+ `右`
|
||||
|
||||
两态或方阵的张量积。
|
||||
|
||||
> 确保插件
|
||||
**> quantum_kron a=`左` b=`右`**
|
||||
|
||||
## 施密特分解
|
||||
+ `态`
|
||||
+ `分割`=1
|
||||
|
||||
> 确保插件
|
||||
**> quantum_schmidt state=`态` cut=`分割`**
|
||||
|
||||
## 保真度
|
||||
+ `左`
|
||||
+ `右`
|
||||
|
||||
纯态保真度 |⟨a|b⟩|²。
|
||||
|
||||
> 确保插件
|
||||
**> quantum_fidelity a=`左` b=`右`**
|
||||
|
||||
# 电路
|
||||
+ `比特数`=1
|
||||
+ `步骤`=None
|
||||
@@ -165,10 +190,30 @@ import json:lib/json.mq.md
|
||||
+ `种类`=circuit
|
||||
+ `比特`=0
|
||||
|
||||
电路轨线 / 概率条 / 布洛赫球(种类 circuit、probs 或 bloch)。经 record_plot 进入 view/CLI plots。
|
||||
电路轨线 / 概率条 / 布洛赫 / 高级态图(种类 circuit、probs、bloch、hinton、city、density、paulivec、qsphere、multibloch)。经 record_plot 进入 view/CLI plots。
|
||||
|
||||
**> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特`**
|
||||
|
||||
## 密度
|
||||
|
||||
理想模拟后的纯态密度矩阵 ρ=|ψ⟩⟨ψ|。
|
||||
|
||||
**> 密度 态=`self`**
|
||||
|
||||
## 期望
|
||||
+ `可观测量`
|
||||
|
||||
Pauli 串(左端=高比特)或矩阵期望值。
|
||||
|
||||
**> quantum_density_expect density=`self` obs=`可观测量`**
|
||||
|
||||
## 施密特
|
||||
+ `分割`=1
|
||||
|
||||
二分施密特分解(`分割`=子系统 A 的比特数,低位)。
|
||||
|
||||
**> quantum_schmidt state=`self` cut=`分割`**
|
||||
|
||||
# 门
|
||||
+ `名`=None
|
||||
+ `参数`=None
|
||||
@@ -196,3 +241,51 @@ import json:lib/json.mq.md
|
||||
门符号或复矩阵热力图(`种类=gate|matrix`)。经 `record_plot` 记录。
|
||||
|
||||
**> quantum_gate_draw gate=`self` path=`路径` kind=`种类`**
|
||||
|
||||
# 密度
|
||||
+ `态`=None
|
||||
+ `矩阵`=None
|
||||
|
||||
由态/电路(`态=`)或显式厄米 `矩阵=` 构造密度矩阵(≤6 比特)。
|
||||
|
||||
> 确保插件
|
||||
1. `矩阵`
|
||||
**> quantum_density_from_matrix matrix=`矩阵`**
|
||||
2. *
|
||||
**> quantum_density_from_state state=`态`**
|
||||
|
||||
## 矩阵
|
||||
|
||||
**> quantum_density_matrix density=`self`**
|
||||
|
||||
## 纯度
|
||||
|
||||
Tr(ρ²)。
|
||||
|
||||
**> quantum_density_purity density=`self`**
|
||||
|
||||
## 部分迹
|
||||
+ `保留`
|
||||
|
||||
保留所列比特(LSB=0),对其余求迹。
|
||||
|
||||
**> quantum_density_partial_trace density=`self` keep=`保留`**
|
||||
|
||||
## 本征
|
||||
|
||||
厄米谱 → `{eigenvalues, eigenvectors}`。
|
||||
|
||||
**> quantum_density_eig density=`self`**
|
||||
|
||||
## 期望
|
||||
+ `可观测量`
|
||||
|
||||
**> quantum_density_expect density=`self` obs=`可观测量`**
|
||||
|
||||
## 绘图
|
||||
+ `路径`=None
|
||||
+ `种类`=hinton
|
||||
|
||||
Hinton / 城市 / 密度格 / 泡利向量 SVG(`种类=hinton` 或 city / density / paulivec)。
|
||||
|
||||
**> quantum_density_draw density=`self` path=`路径` kind=`种类`**
|
||||
@@ -496,3 +496,357 @@ pub fn matrix_heatmap_svg(m: &[Vec<C>], title: &str) -> String {
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
fn phase_hue(arg: f64) -> String {
|
||||
// map [-π,π] → hue degrees
|
||||
let h = ((arg + std::f64::consts::PI) / (2.0 * std::f64::consts::PI) * 360.0) % 360.0;
|
||||
format!("hsl({h:.0},70%,45%)")
|
||||
}
|
||||
|
||||
/// Hinton diagram for density matrix (Q7b).
|
||||
pub fn hinton_svg(m: &[Vec<C>], title: &str) -> String {
|
||||
let n = m.len().max(1);
|
||||
let cell = if n <= 2 { 56.0 } else if n <= 4 { 44.0 } else { 32.0 };
|
||||
let left = 40.0;
|
||||
let top = 28.0;
|
||||
let width = left + cell * n as f64 + 16.0;
|
||||
let height = top + cell * n as f64 + 24.0;
|
||||
let mut max_a: f64 = 1e-12;
|
||||
for row in m {
|
||||
for c in row {
|
||||
max_a = max_a.max(mag(*c));
|
||||
}
|
||||
}
|
||||
let mut body = String::new();
|
||||
body.push_str(&format!(
|
||||
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title}</text>"#,
|
||||
title = esc(title),
|
||||
STROKE = STROKE,
|
||||
));
|
||||
body.push_str(&format!(
|
||||
r##"<rect x="{left}" y="{top}" width="{w}" height="{h}" fill="#f0eee8" stroke="{STROKE}" stroke-width="1"/>"##,
|
||||
left = left,
|
||||
top = top,
|
||||
w = cell * n as f64,
|
||||
h = cell * n as f64,
|
||||
STROKE = STROKE,
|
||||
));
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero());
|
||||
let a = mag(c) / max_a;
|
||||
let side = (cell * 0.85 * a.sqrt()).max(1.0);
|
||||
let cx = left + (j as f64 + 0.5) * cell;
|
||||
let cy = top + (i as f64 + 0.5) * cell;
|
||||
let fill = if c.re >= 0.0 { "#f5f5f5" } else { "#1a1a1a" };
|
||||
let stroke = if c.re >= 0.0 { STROKE } else { "#f5f5f5" };
|
||||
body.push_str(&format!(
|
||||
r#"<rect x="{x}" y="{y}" width="{side}" height="{side}" fill="{fill}" stroke="{stroke}" stroke-width="0.8" data-hinton="1"/>"#,
|
||||
x = cx - side * 0.5,
|
||||
y = cy - side * 0.5,
|
||||
side = side,
|
||||
fill = fill,
|
||||
stroke = stroke,
|
||||
));
|
||||
}
|
||||
}
|
||||
format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0}" height="{h:.0}" viewBox="0 0 {w:.1} {h:.1}" role="img" aria-label="hinton">{body}</svg>"#,
|
||||
w = width,
|
||||
h = height,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
/// Cirq-inspired density: magnitude disk + phase needle; diagonal probability bars.
|
||||
pub fn density_cells_svg(m: &[Vec<C>], title: &str) -> String {
|
||||
let n = m.len().max(1);
|
||||
let cell = if n <= 2 { 64.0 } else if n <= 4 { 48.0 } else { 36.0 };
|
||||
let left = 36.0;
|
||||
let top = 28.0;
|
||||
let width = left + cell * n as f64 + 16.0;
|
||||
let height = top + cell * n as f64 + 20.0;
|
||||
let mut max_a: f64 = 1e-12;
|
||||
for row in m {
|
||||
for c in row {
|
||||
max_a = max_a.max(mag(*c));
|
||||
}
|
||||
}
|
||||
let mut body = String::new();
|
||||
body.push_str(&format!(
|
||||
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title}</text>"#,
|
||||
title = esc(title),
|
||||
STROKE = STROKE,
|
||||
));
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero());
|
||||
let x0 = left + j as f64 * cell;
|
||||
let y0 = top + i as f64 * cell;
|
||||
body.push_str(&format!(
|
||||
r##"<rect x="{x0}" y="{y0}" width="{cell}" height="{cell}" fill="#eeeeee" stroke="#ccc" stroke-width="0.5"/>"##,
|
||||
x0 = x0,
|
||||
y0 = y0,
|
||||
cell = cell,
|
||||
));
|
||||
let cx = x0 + cell * 0.5;
|
||||
let cy = y0 + cell * 0.5;
|
||||
if i == n - 1 - j || i == j {
|
||||
// soft diagonal highlight for probability (i==j)
|
||||
}
|
||||
if i == j {
|
||||
let p = c.re.clamp(0.0, 1.0);
|
||||
let bw = cell * 0.7 * p;
|
||||
body.push_str(&format!(
|
||||
r##"<rect x="{x}" y="{y}" width="{bw}" height="6" fill="#3a6ea5" data-density-diag="1"/>"##,
|
||||
x = cx - cell * 0.35,
|
||||
y = y0 + cell - 10.0,
|
||||
bw = bw,
|
||||
));
|
||||
}
|
||||
let r = cell * 0.35 * (mag(c) / max_a).sqrt();
|
||||
let arg = c.im.atan2(c.re);
|
||||
body.push_str(&format!(
|
||||
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="{fill}" fill-opacity="0.35" stroke="{fill}" stroke-width="1.2" data-density="1"/>"#,
|
||||
cx = cx,
|
||||
cy = cy,
|
||||
r = r.max(0.5),
|
||||
fill = phase_hue(arg),
|
||||
));
|
||||
let nx = cx + r * arg.cos();
|
||||
let ny = cy - r * arg.sin();
|
||||
body.push_str(&format!(
|
||||
r#"<line x1="{cx}" y1="{cy}" x2="{nx}" y2="{ny}" stroke="{STROKE}" stroke-width="1.2"/>"#,
|
||||
cx = cx,
|
||||
cy = cy,
|
||||
nx = nx,
|
||||
ny = ny,
|
||||
STROKE = STROKE,
|
||||
));
|
||||
}
|
||||
}
|
||||
format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0}" height="{h:.0}" viewBox="0 0 {w:.1} {h:.1}" role="img" aria-label="density">{body}</svg>"#,
|
||||
w = width,
|
||||
h = height,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
/// 2.5D cityscape: Re (left) and Im (right) bar grids.
|
||||
pub fn city_svg(m: &[Vec<C>], title: &str) -> String {
|
||||
let n = m.len().max(1);
|
||||
let cell = 28.0;
|
||||
let left = 40.0;
|
||||
let top = 40.0;
|
||||
let gap = 24.0;
|
||||
let grid_w = cell * n as f64;
|
||||
let width = left + grid_w * 2.0 + gap + 24.0;
|
||||
let max_h = 80.0;
|
||||
let mut max_re: f64 = 1e-12;
|
||||
let mut max_im: f64 = 1e-12;
|
||||
for row in m {
|
||||
for c in row {
|
||||
max_re = max_re.max(c.re.abs());
|
||||
max_im = max_im.max(c.im.abs());
|
||||
}
|
||||
}
|
||||
let height = top + max_h + cell * n as f64 * 0.35 + 40.0;
|
||||
let mut body = String::new();
|
||||
body.push_str(&format!(
|
||||
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title} (city)</text>"#,
|
||||
title = esc(title),
|
||||
STROKE = STROKE,
|
||||
));
|
||||
body.push_str(r##"<text x="40" y="34" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="#666">Re</text>"##);
|
||||
body.push_str(&format!(
|
||||
r##"<text x="{x}" y="34" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="#666">Im</text>"##,
|
||||
x = left + grid_w + gap,
|
||||
));
|
||||
let draw_city = |body: &mut String, origin_x: f64, use_re: bool| {
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero());
|
||||
let val = if use_re { c.re } else { c.im };
|
||||
let denom = if use_re { max_re } else { max_im };
|
||||
let h = (val.abs() / denom) * max_h;
|
||||
let iso_x = origin_x + (j as f64 - i as f64) * cell * 0.5;
|
||||
let iso_y = top + (i as f64 + j as f64) * cell * 0.28 + (max_h - h);
|
||||
let fill = if use_re { "#3a6ea5" } else { "#c45c26" };
|
||||
body.push_str(&format!(
|
||||
r#"<rect x="{iso_x}" y="{iso_y}" width="{w}" height="{h}" fill="{fill}" fill-opacity="0.85" stroke="{STROKE}" stroke-width="0.4" data-city="1"/>"#,
|
||||
iso_x = iso_x,
|
||||
iso_y = iso_y,
|
||||
w = cell * 0.45,
|
||||
h = h.max(0.5),
|
||||
fill = fill,
|
||||
STROKE = STROKE,
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
draw_city(&mut body, left + grid_w * 0.35, true);
|
||||
draw_city(&mut body, left + grid_w + gap + grid_w * 0.35, false);
|
||||
format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0}" height="{h:.0}" viewBox="0 0 {w:.1} {h:.1}" role="img" aria-label="city">{body}</svg>"#,
|
||||
w = width,
|
||||
h = height,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
/// Pauli expectation bar chart.
|
||||
pub fn paulivec_svg(labels: &[String], values: &[f64], title: &str) -> String {
|
||||
let n = labels.len().max(1);
|
||||
let bar_w = 28.0;
|
||||
let gap = 8.0;
|
||||
let left = 48.0;
|
||||
let top = 28.0;
|
||||
let chart_h = 120.0;
|
||||
let width = left + n as f64 * (bar_w + gap) + 16.0;
|
||||
let height = top + chart_h + 40.0;
|
||||
let mid_y = top + chart_h * 0.5;
|
||||
let mut body = String::new();
|
||||
body.push_str(&format!(
|
||||
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title}</text>"#,
|
||||
title = esc(title),
|
||||
STROKE = STROKE,
|
||||
));
|
||||
body.push_str(&format!(
|
||||
r##"<line x1="{left}" y1="{mid_y}" x2="{x2}" y2="{mid_y}" stroke="#888" stroke-width="1"/>"##,
|
||||
left = left,
|
||||
mid_y = mid_y,
|
||||
x2 = width - 8.0,
|
||||
));
|
||||
for (i, (lab, val)) in labels.iter().zip(values.iter()).enumerate() {
|
||||
let x = left + i as f64 * (bar_w + gap);
|
||||
let h = val.abs().clamp(0.0, 1.0) * (chart_h * 0.45);
|
||||
let y = if *val >= 0.0 { mid_y - h } else { mid_y };
|
||||
body.push_str(&format!(
|
||||
r##"<rect x="{x}" y="{y}" width="{bar_w}" height="{h}" fill="#2f6f4e" data-paulivec="1"/>"##,
|
||||
x = x,
|
||||
y = y,
|
||||
bar_w = bar_w,
|
||||
h = h.max(0.5),
|
||||
));
|
||||
body.push_str(&format!(
|
||||
r#"<text x="{tx}" y="{ty}" text-anchor="middle" font-family="ui-monospace,Menlo,monospace" font-size="9" fill="{STROKE}">{lab}</text>"#,
|
||||
tx = x + bar_w * 0.5,
|
||||
ty = top + chart_h + 14.0,
|
||||
lab = esc(lab),
|
||||
STROKE = STROKE,
|
||||
));
|
||||
}
|
||||
format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0}" height="{h:.0}" viewBox="0 0 {w:.1} {h:.1}" role="img" aria-label="paulivec">{body}</svg>"#,
|
||||
w = width,
|
||||
h = height,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
/// QSphere-style: amplitudes on a circle (phase→angle, amp→radius of marker).
|
||||
pub fn qsphere_svg(amps: &[C], qubits: usize) -> String {
|
||||
let dim = amps.len();
|
||||
let cx = 160.0;
|
||||
let cy = 160.0;
|
||||
let r = 110.0;
|
||||
let width = 320.0;
|
||||
let height = 320.0;
|
||||
let mut body = String::new();
|
||||
body.push_str(&format!(
|
||||
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{STROKE}" stroke-width="1.5"/>"#,
|
||||
cx = cx,
|
||||
cy = cy,
|
||||
r = r,
|
||||
STROKE = STROKE,
|
||||
));
|
||||
body.push_str(r##"<text x="12" y="20" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="#1a1a1a">qsphere</text>"##);
|
||||
for (i, a) in amps.iter().enumerate() {
|
||||
let amp = mag(*a);
|
||||
if amp < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
// latitude from Hamming weight, longitude from index
|
||||
let wt = (i as u32).count_ones() as f64;
|
||||
let lat = if qubits == 0 {
|
||||
0.0
|
||||
} else {
|
||||
std::f64::consts::PI * (wt / qubits as f64 - 0.5)
|
||||
};
|
||||
let lon = 2.0 * std::f64::consts::PI * (i as f64) / (dim as f64);
|
||||
let rr = r * lat.cos();
|
||||
let x = cx + rr * lon.cos();
|
||||
let y = cy - r * lat.sin();
|
||||
let rad = 4.0 + 14.0 * amp;
|
||||
let arg = a.im.atan2(a.re);
|
||||
body.push_str(&format!(
|
||||
r#"<circle cx="{x}" cy="{y}" r="{rad}" fill="{fill}" stroke="{STROKE}" stroke-width="1" data-qsphere="1"/>"#,
|
||||
x = x,
|
||||
y = y,
|
||||
rad = rad,
|
||||
fill = phase_hue(arg),
|
||||
STROKE = STROKE,
|
||||
));
|
||||
}
|
||||
format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0}" height="{h:.0}" viewBox="0 0 {w:.1} {h:.1}" role="img" aria-label="qsphere">{body}</svg>"#,
|
||||
w = width,
|
||||
h = height,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
/// Side-by-side Bloch spheres for each qubit.
|
||||
pub fn multibloch_svg(amps: &[C], qubits: usize) -> Result<String, String> {
|
||||
let sphere_w = 140.0;
|
||||
let width = 16.0 + qubits as f64 * sphere_w;
|
||||
let height = 160.0;
|
||||
let mut body = String::new();
|
||||
body.push_str(r##"<text x="8" y="16" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="#1a1a1a">multibloch</text>"##);
|
||||
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
|
||||
let ox = 8.0 + q as f64 * sphere_w;
|
||||
let cx = ox + 60.0;
|
||||
let cy = 90.0;
|
||||
let r = 40.0;
|
||||
body.push_str(&format!(
|
||||
r##"<text x="{ox}" y="32" font-family="ui-monospace,Menlo,monospace" font-size="11" fill="#1a1a1a">q{q}</text>"##,
|
||||
ox = ox + 8.0,
|
||||
q = q,
|
||||
));
|
||||
body.push_str(&format!(
|
||||
r##"<ellipse cx="{cx}" cy="{cy}" rx="{r}" ry="{ry}" fill="#f7f4ef" stroke="{STROKE}" stroke-width="1.2"/>"##,
|
||||
cx = cx,
|
||||
cy = cy,
|
||||
r = r,
|
||||
ry = r * 0.55,
|
||||
STROKE = STROKE,
|
||||
));
|
||||
body.push_str(&format!(
|
||||
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{STROKE}" stroke-width="1.2"/>"#,
|
||||
cx = cx,
|
||||
cy = cy,
|
||||
r = r,
|
||||
STROKE = STROKE,
|
||||
));
|
||||
let px = cx + x * r;
|
||||
let py = cy - z * r * 0.85;
|
||||
body.push_str(&format!(
|
||||
r##"<line x1="{cx}" y1="{cy}" x2="{px}" y2="{py}" stroke="#c45c26" stroke-width="2" data-multibloch="1"/>"##,
|
||||
cx = cx,
|
||||
cy = cy,
|
||||
px = px,
|
||||
py = py,
|
||||
));
|
||||
let _ = (y, svg);
|
||||
}
|
||||
Ok(format!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w:.0}" height="{h:.0}" viewBox="0 0 {w:.1} {h:.1}" role="img" aria-label="multibloch">{body}</svg>"#,
|
||||
w = width,
|
||||
h = height,
|
||||
body = body,
|
||||
))
|
||||
}
|
||||
+329
-1
@@ -1,6 +1,7 @@
|
||||
//! Marqdo quantum plugin (C ABI v2): state-vector circuit simulation.
|
||||
|
||||
mod draw;
|
||||
mod linalg;
|
||||
mod sim;
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
@@ -443,9 +444,46 @@ q_ffi!(quantum_draw_circuit, |args: &Value| {
|
||||
let (x, y, z) = sim::bloch_vector(&s, qubits, qubit)?;
|
||||
("bloch", draw::bloch_svg(x, y, z))
|
||||
}
|
||||
"hinton" | "欣顿" => {
|
||||
let (n, amps) = sim::simulate_circuit(c)?;
|
||||
let (_, rho) = linalg::density_from_amps(&s, n)?;
|
||||
let nested = linalg::flat_to_nested(&rho, 1 << n);
|
||||
("hinton", draw::hinton_svg(&nested, "ρ hinton"))
|
||||
}
|
||||
"city" | "城市" => {
|
||||
let (n, amps) = sim::simulate_circuit(c)?;
|
||||
let (_, rho) = linalg::density_from_amps(&s, n)?;
|
||||
let nested = linalg::flat_to_nested(&rho, 1 << n);
|
||||
("city", draw::city_svg(&nested, "ρ"))
|
||||
}
|
||||
"density" | "密度图" => {
|
||||
let (n, amps) = sim::simulate_circuit(c)?;
|
||||
let (_, rho) = linalg::density_from_amps(&s, n)?;
|
||||
let nested = linalg::flat_to_nested(&rho, 1 << n);
|
||||
("density", draw::density_cells_svg(&nested, "ρ"))
|
||||
}
|
||||
"paulivec" | "泡利向量" => {
|
||||
let (n, amps) = sim::simulate_circuit(c)?;
|
||||
let (_, rho) = linalg::density_from_amps(&s, n)?;
|
||||
let dim = 1 << n;
|
||||
let labels = linalg::all_pauli_labels(n)?;
|
||||
let mut vals = Vec::with_capacity(labels.len());
|
||||
for lab in &labels {
|
||||
vals.push(linalg::expect_pauli(&rho, dim, n, lab)?);
|
||||
}
|
||||
("paulivec", draw::paulivec_svg(&labels, &vals, "Pauli"))
|
||||
}
|
||||
"qsphere" | "球" => {
|
||||
let (n, amps) = sim::simulate_circuit(c)?;
|
||||
("qsphere", draw::qsphere_svg(&s, n))
|
||||
}
|
||||
"multibloch" | "多布洛赫" => {
|
||||
let (n, amps) = sim::simulate_circuit(c)?;
|
||||
("multibloch", draw::multibloch_svg(&s, n)?)
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"unknown draw kind `{other}` (circuit|probs|bloch)"
|
||||
"unknown draw kind `{other}` (circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch)"
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -587,6 +625,249 @@ q_ffi!(quantum_apply, |args: &Value| {
|
||||
sim::apply_gate(c, gate, qubits)
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_from_state, |args: &Value| {
|
||||
let src = args
|
||||
.get("state")
|
||||
.or_else(|| args.get("态"))
|
||||
.or_else(|| args.get("circuit"))
|
||||
.or_else(|| args.get("电路"))
|
||||
.ok_or_else(|| "density needs `state` or `circuit`".to_string())?;
|
||||
let (n, amps) = linalg::amps_from_state_or_circuit(src)?;
|
||||
let (_, rho) = linalg::density_from_amps(&s, n)?;
|
||||
Ok(linalg::density_handle(n, &rho))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_from_matrix, |args: &Value| {
|
||||
let matrix = args
|
||||
.get("matrix")
|
||||
.or_else(|| args.get("矩阵"))
|
||||
.ok_or_else(|| "missing `matrix`".to_string())?;
|
||||
let bag = json!({ "matrix": matrix });
|
||||
let (n, rho) = linalg::parse_density(&bag)?;
|
||||
Ok(linalg::density_handle(n, &rho))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_matrix, |args: &Value| {
|
||||
let d = args
|
||||
.get("density")
|
||||
.or_else(|| args.get("密度"))
|
||||
.ok_or_else(|| "missing `density`".to_string())?;
|
||||
let (n, rho) = linalg::parse_density(d)?;
|
||||
let dim = 1 << n;
|
||||
Ok(sim::matrix_to_json(&linalg::flat_to_nested(&rho, dim)))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_purity, |args: &Value| {
|
||||
let d = args
|
||||
.get("density")
|
||||
.or_else(|| args.get("密度"))
|
||||
.ok_or_else(|| "missing `density`".to_string())?;
|
||||
let (n, rho) = linalg::parse_density(d)?;
|
||||
let dim = 1 << n;
|
||||
Ok(json!(linalg::purity(&rho, dim)))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_partial_trace, |args: &Value| {
|
||||
let d = args
|
||||
.get("density")
|
||||
.or_else(|| args.get("密度"))
|
||||
.ok_or_else(|| "missing `density`".to_string())?;
|
||||
let keep_v = args
|
||||
.get("keep")
|
||||
.or_else(|| args.get("保留"))
|
||||
.ok_or_else(|| "missing `keep`".to_string())?;
|
||||
let keep = parse_usize_list(keep_v)?;
|
||||
let (n, rho) = linalg::parse_density(d)?;
|
||||
let (k, out) = linalg::partial_trace(&rho, n, &keep)?;
|
||||
Ok(linalg::density_handle(k, &out))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_eig, |args: &Value| {
|
||||
let d = args
|
||||
.get("density")
|
||||
.or_else(|| args.get("密度"))
|
||||
.ok_or_else(|| "missing `density`".to_string())?;
|
||||
let (n, rho) = linalg::parse_density(d)?;
|
||||
let dim = 1 << n;
|
||||
let (evals, evecs) = linalg::hermite_eig(&rho, dim)?;
|
||||
Ok(linalg::spectrum_handle(&evals, &evecs))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_expect, |args: &Value| {
|
||||
let d = args
|
||||
.get("density")
|
||||
.or_else(|| args.get("密度"))
|
||||
.or_else(|| args.get("state"))
|
||||
.or_else(|| args.get("态"))
|
||||
.or_else(|| args.get("circuit"))
|
||||
.or_else(|| args.get("电路"))
|
||||
.ok_or_else(|| "expect needs density/state/circuit".to_string())?;
|
||||
let (n, rho) = if d.get("amplitudes").is_some()
|
||||
|| d.get("_type").and_then(|t| t.as_str()) == Some("quantum_state")
|
||||
|| d.get("ops").is_some()
|
||||
{
|
||||
let (qn, amps) = linalg::amps_from_state_or_circuit(d)?;
|
||||
let (_, r) = linalg::density_from_amps(&s, qn)?;
|
||||
(qn, r)
|
||||
} else {
|
||||
linalg::parse_density(d)?
|
||||
};
|
||||
let dim = 1 << n;
|
||||
let obs = args
|
||||
.get("obs")
|
||||
.or_else(|| args.get("可观测量"))
|
||||
.ok_or_else(|| "missing `obs`".to_string())?;
|
||||
let val = if let Some(s) = obs.as_str() {
|
||||
linalg::expect_pauli(&rho, dim, n, s)?
|
||||
} else {
|
||||
let (_od, om) = linalg::value_as_matrix(obs)?;
|
||||
linalg::expect_matrix(&rho, dim, &om, dim)?
|
||||
};
|
||||
Ok(json!(val))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_density_draw, |args: &Value| {
|
||||
let d = args
|
||||
.get("density")
|
||||
.or_else(|| args.get("密度"))
|
||||
.ok_or_else(|| "missing `density`".to_string())?;
|
||||
let kind = args
|
||||
.get("kind")
|
||||
.or_else(|| args.get("种类"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("hinton")
|
||||
.to_ascii_lowercase();
|
||||
let path = args
|
||||
.get("path")
|
||||
.or_else(|| args.get("路径"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty());
|
||||
let (n, rho) = linalg::parse_density(d)?;
|
||||
let dim = 1 << n;
|
||||
let nested = linalg::flat_to_nested(&rho, dim);
|
||||
let (kind_out, svg) = match kind.as_str() {
|
||||
"hinton" | "欣顿" => ("hinton", draw::hinton_svg(&nested, "ρ hinton")),
|
||||
"city" | "城市" => ("city", draw::city_svg(&nested, "ρ")),
|
||||
"density" | "密度图" => ("density", draw::density_cells_svg(&nested, "ρ")),
|
||||
"paulivec" | "泡利向量" => {
|
||||
let labels = linalg::all_pauli_labels(n)?;
|
||||
let mut vals = Vec::with_capacity(labels.len());
|
||||
for lab in &labels {
|
||||
vals.push(linalg::expect_pauli(&rho, dim, n, lab)?);
|
||||
}
|
||||
("paulivec", draw::paulivec_svg(&labels, &vals, "Pauli"))
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"unknown density draw kind `{other}` (hinton|city|density|paulivec)"
|
||||
));
|
||||
}
|
||||
};
|
||||
record_plot(&svg, path)?;
|
||||
Ok(json!({
|
||||
"_type": "quantum_svg",
|
||||
"kind": kind_out,
|
||||
"qubits": n,
|
||||
"svg": svg,
|
||||
}))
|
||||
});
|
||||
|
||||
q_ffi!(quantum_kron, |args: &Value| {
|
||||
let a = args
|
||||
.get("a")
|
||||
.or_else(|| args.get("左"))
|
||||
.ok_or_else(|| "kron needs `a`".to_string())?;
|
||||
let b = args
|
||||
.get("b")
|
||||
.or_else(|| args.get("右"))
|
||||
.ok_or_else(|| "kron needs `b`".to_string())?;
|
||||
if (a.get("amplitudes").is_some()
|
||||
|| a.get("_type").and_then(|t| t.as_str()) == Some("quantum_state"))
|
||||
&& (b.get("amplitudes").is_some()
|
||||
|| b.get("_type").and_then(|t| t.as_str()) == Some("quantum_state"))
|
||||
{
|
||||
let (na, aa) = linalg::amps_from_state_or_circuit(a)?;
|
||||
let (nb, bb) = linalg::amps_from_state_or_circuit(b)?;
|
||||
let out = linalg::kronecker_amps(&aa, &bb);
|
||||
return Ok(json!({
|
||||
"_type": "quantum_state",
|
||||
"qubits": na + nb,
|
||||
"dim": out.len(),
|
||||
"amplitudes": sim::amps_to_json(&out),
|
||||
}));
|
||||
}
|
||||
let (_na, ma) = linalg::value_as_matrix(a)?;
|
||||
let (_nb, mb) = linalg::value_as_matrix(b)?;
|
||||
let da = (ma.len() as f64).sqrt() as usize;
|
||||
let db = (mb.len() as f64).sqrt() as usize;
|
||||
if da * da != ma.len() || db * db != mb.len() {
|
||||
return Err("kron: matrices must be square".into());
|
||||
}
|
||||
let out = linalg::kronecker(&ma, da, &mb, db);
|
||||
let dim = da * db;
|
||||
let qubits_f = (dim as f64).log2();
|
||||
if (qubits_f - qubits_f.round()).abs() < 1e-9 {
|
||||
let qubits = qubits_f.round() as usize;
|
||||
Ok(linalg::density_handle(qubits, &out))
|
||||
} else {
|
||||
Ok(json!({
|
||||
"_type": "quantum_density",
|
||||
"dim": dim,
|
||||
"matrix": sim::matrix_to_json(&linalg::flat_to_nested(&out, dim)),
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
q_ffi!(quantum_schmidt, |args: &Value| {
|
||||
let src = args
|
||||
.get("state")
|
||||
.or_else(|| args.get("态"))
|
||||
.or_else(|| args.get("circuit"))
|
||||
.or_else(|| args.get("电路"))
|
||||
.ok_or_else(|| "schmidt needs `state` or `circuit`".to_string())?;
|
||||
let cut = arg_u(args, "cut")
|
||||
.or_else(|_| arg_u(args, "分割"))
|
||||
.unwrap_or(1);
|
||||
let (n, amps) = linalg::amps_from_state_or_circuit(src)?;
|
||||
linalg::schmidt_decompose(&s, n, cut)
|
||||
});
|
||||
|
||||
q_ffi!(quantum_fidelity, |args: &Value| {
|
||||
let a = args
|
||||
.get("a")
|
||||
.or_else(|| args.get("左"))
|
||||
.ok_or_else(|| "fidelity needs `a`".to_string())?;
|
||||
let b = args
|
||||
.get("b")
|
||||
.or_else(|| args.get("右"))
|
||||
.ok_or_else(|| "fidelity needs `b`".to_string())?;
|
||||
let (_, aa) = linalg::amps_from_state_or_circuit(a)?;
|
||||
let (_, bb) = linalg::amps_from_state_or_circuit(b)?;
|
||||
Ok(json!(linalg::fidelity_pure(&aa, &bb)?))
|
||||
});
|
||||
|
||||
fn parse_usize_list(v: &Value) -> Result<Vec<usize>, String> {
|
||||
match v {
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.map(|x| {
|
||||
x.as_u64()
|
||||
.or_else(|| x.as_i64().map(|i| i as u64))
|
||||
.or_else(|| x.as_str().and_then(|s| s.trim().parse().ok()))
|
||||
.map(|u| u as usize)
|
||||
.ok_or_else(|| "bad keep list entry".to_string())
|
||||
})
|
||||
.collect(),
|
||||
Value::Number(n) => Ok(vec![n.as_u64().unwrap_or(0) as usize]),
|
||||
Value::String(s) => s
|
||||
.split(|c| c == ',' || c == ' ')
|
||||
.filter(|t| !t.is_empty())
|
||||
.map(|t| t.parse().map_err(|_| format!("bad keep `{t}`")))
|
||||
.collect(),
|
||||
_ => Err("keep must be list, number, or comma string".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
|
||||
let register = match host.register_fn {
|
||||
Some(f) => f,
|
||||
@@ -695,6 +976,53 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"circuit,gate,qubits",
|
||||
quantum_apply as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_from_state",
|
||||
"state",
|
||||
quantum_density_from_state as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_from_matrix",
|
||||
"matrix",
|
||||
quantum_density_from_matrix as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_matrix",
|
||||
"density",
|
||||
quantum_density_matrix as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_purity",
|
||||
"density",
|
||||
quantum_density_purity as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_partial_trace",
|
||||
"density,keep",
|
||||
quantum_density_partial_trace as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_eig",
|
||||
"density",
|
||||
quantum_density_eig as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_expect",
|
||||
"density,obs",
|
||||
quantum_density_expect as PluginFn,
|
||||
),
|
||||
(
|
||||
"quantum_density_draw",
|
||||
"density,path,kind",
|
||||
quantum_density_draw as PluginFn,
|
||||
),
|
||||
("quantum_kron", "a,b", quantum_kron as PluginFn),
|
||||
(
|
||||
"quantum_schmidt",
|
||||
"state,cut",
|
||||
quantum_schmidt as PluginFn,
|
||||
),
|
||||
("quantum_fidelity", "a,b", quantum_fidelity as PluginFn),
|
||||
];
|
||||
for (name, params, f) in regs {
|
||||
if register(host, name, params, f) != 0 {
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
//! Q7a: density matrix, Kronecker, partial trace, Hermitian eig, Schmidt, Pauli expect.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::sim::{
|
||||
amps_to_json, matrix_to_json, parse_matrix, simulate_circuit, C,
|
||||
};
|
||||
|
||||
pub const DENSITY_MAX_QUBITS: usize = 6;
|
||||
|
||||
fn check_density_qubits(n: usize) -> Result<(), String> {
|
||||
if n > DENSITY_MAX_QUBITS {
|
||||
return Err(format!(
|
||||
"density-matrix ops limited to {DENSITY_MAX_QUBITS} qubits (got {n}); use state-vector APIs for larger n"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dim_of(n: usize) -> usize {
|
||||
1usize << n
|
||||
}
|
||||
|
||||
/// Flat row-major dim×dim complex matrix.
|
||||
pub type Mat = Vec<C>;
|
||||
|
||||
pub fn mat_get(m: &Mat, dim: usize, i: usize, j: usize) -> C {
|
||||
m[i * dim + j]
|
||||
}
|
||||
|
||||
pub fn mat_set(m: &mut Mat, dim: usize, i: usize, j: usize, v: C) {
|
||||
m[i * dim + j] = v;
|
||||
}
|
||||
|
||||
pub fn mat_zeros(dim: usize) -> Mat {
|
||||
vec![C::zero(); dim * dim]
|
||||
}
|
||||
|
||||
pub fn nested_to_flat(m: &[Vec<C>]) -> Result<(usize, Mat), String> {
|
||||
if m.is_empty() {
|
||||
return Err("matrix is empty".into());
|
||||
}
|
||||
let dim = m.len();
|
||||
for (i, row) in m.iter().enumerate() {
|
||||
if row.len() != dim {
|
||||
return Err(format!("matrix row {i} length {} != {dim}", row.len()));
|
||||
}
|
||||
}
|
||||
let mut flat = Mat::with_capacity(dim * dim);
|
||||
for row in m {
|
||||
flat.extend_from_slice(row);
|
||||
}
|
||||
Ok((dim, flat))
|
||||
}
|
||||
|
||||
pub fn flat_to_nested(m: &Mat, dim: usize) -> Vec<Vec<C>> {
|
||||
let mut out = Vec::with_capacity(dim);
|
||||
for i in 0..dim {
|
||||
out.push(m[i * dim..(i + 1) * dim].to_vec());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn density_from_amps(amps: &[C], qubits: usize) -> Result<(usize, Mat), String> {
|
||||
check_density_qubits(qubits)?;
|
||||
let dim = dim_of(qubits);
|
||||
if amps.len() != dim {
|
||||
return Err(format!(
|
||||
"state dim {} != 2^{qubits}={dim}",
|
||||
amps.len()
|
||||
));
|
||||
}
|
||||
let mut rho = mat_zeros(dim);
|
||||
for i in 0..dim {
|
||||
for j in 0..dim {
|
||||
// ρ_ij = ψ_i * conj(ψ_j)
|
||||
mat_set(&mut rho, dim, i, j, amps[i].mul(amps[j].conj()));
|
||||
}
|
||||
}
|
||||
Ok((dim, rho))
|
||||
}
|
||||
|
||||
pub fn amps_from_state_or_circuit(v: &Value) -> Result<(usize, Vec<C>), String> {
|
||||
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_circuit")
|
||||
|| (v.get("qubits").is_some() && v.get("ops").is_some())
|
||||
{
|
||||
let (n, amps) = simulate_circuit(v)?;
|
||||
return Ok((n, amps));
|
||||
}
|
||||
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_state")
|
||||
|| v.get("amplitudes").is_some()
|
||||
{
|
||||
let qubits = v
|
||||
.get("qubits")
|
||||
.or_else(|| v.get("比特数"))
|
||||
.and_then(|x| x.as_u64().or_else(|| x.as_i64().map(|i| i as u64)))
|
||||
.ok_or_else(|| "state missing qubits".to_string())? as usize;
|
||||
let amps_v = v
|
||||
.get("amplitudes")
|
||||
.or_else(|| v.get("振幅"))
|
||||
.ok_or_else(|| "state missing amplitudes".to_string())?;
|
||||
let nested = match amps_v {
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.map(|c| match c {
|
||||
Value::Object(o) => Ok(C::new(
|
||||
o.get("re").and_then(|x| x.as_f64()).unwrap_or(0.0),
|
||||
o.get("im").and_then(|x| x.as_f64()).unwrap_or(0.0),
|
||||
)),
|
||||
_ => Err("amplitude cell must be {re,im}".into()),
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?,
|
||||
_ => return Err("amplitudes must be a list".into()),
|
||||
};
|
||||
return Ok((qubits, nested));
|
||||
}
|
||||
Err("expected quantum_state or quantum_circuit".into())
|
||||
}
|
||||
|
||||
pub fn density_handle(qubits: usize, rho: &Mat) -> Value {
|
||||
let dim = dim_of(qubits);
|
||||
json!({
|
||||
"_type": "density",
|
||||
"qubits": qubits,
|
||||
"dim": dim,
|
||||
"matrix": matrix_to_json(&flat_to_nested(rho, dim)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_density(v: &Value) -> Result<(usize, Mat), String> {
|
||||
if let Some(mat_v) = v.get("matrix").or_else(|| v.get("矩阵")) {
|
||||
let nested = parse_matrix(mat_v)?;
|
||||
let (dim, flat) = nested_to_flat(&nested)?;
|
||||
let qubits = (dim as f64).log2() as usize;
|
||||
if dim_of(qubits) != dim {
|
||||
return Err(format!("density dim {dim} is not a power of two"));
|
||||
}
|
||||
check_density_qubits(qubits)?;
|
||||
check_hermitian(&flat, dim)?;
|
||||
return Ok((qubits, flat));
|
||||
}
|
||||
let (n, amps) = amps_from_state_or_circuit(v)?;
|
||||
density_from_amps(&s, n)
|
||||
}
|
||||
|
||||
pub fn check_hermitian(m: &Mat, dim: usize) -> Result<(), String> {
|
||||
let mut err = 0.0;
|
||||
for i in 0..dim {
|
||||
for j in i..dim {
|
||||
let a = mat_get(m, dim, i, j);
|
||||
let b = mat_get(m, dim, j, i).conj();
|
||||
let d = a.sub(b);
|
||||
err += d.norm_sq();
|
||||
}
|
||||
}
|
||||
if err.sqrt() > 1e-8 {
|
||||
return Err(format!(
|
||||
"matrix is not Hermitian (‖ρ−ρ†‖_F ≈ {:.2e})",
|
||||
err.sqrt()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn purity(m: &Mat, dim: usize) -> f64 {
|
||||
// Tr(ρ²) = Σ_ij |ρ_ij|² for Hermitian ρ? Actually Tr(ρ²)=Σ_ij ρ_ij ρ_ji = Σ_ij |ρ_ij|² when Hermitian.
|
||||
let mut s = 0.0;
|
||||
for i in 0..dim {
|
||||
for j in 0..dim {
|
||||
s += mat_get(m, dim, i, j).norm_sq();
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
pub fn kronecker(a: &Mat, da: usize, b: &Mat, db: usize) -> Mat {
|
||||
let dim = da * db;
|
||||
let mut out = mat_zeros(dim);
|
||||
for i in 0..da {
|
||||
for j in 0..da {
|
||||
let aij = mat_get(a, da, i, j);
|
||||
for k in 0..db {
|
||||
for l in 0..db {
|
||||
let bij = mat_get(b, db, k, l);
|
||||
mat_set(
|
||||
&mut out,
|
||||
dim,
|
||||
i * db + k,
|
||||
j * db + l,
|
||||
aij.mul(bij),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn kronecker_amps(a: &[C], b: &[C]) -> Vec<C> {
|
||||
let mut out = Vec::with_capacity(a.len() * b.len());
|
||||
for &ai in a {
|
||||
for &bj in b {
|
||||
out.push(ai.mul(bj));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Keep listed qubits (LSB numbering). Trace out the rest.
|
||||
pub fn partial_trace(rho: &Mat, qubits: usize, keep: &[usize]) -> Result<(usize, Mat), String> {
|
||||
check_density_qubits(qubits)?;
|
||||
let mut keep_sorted = keep.to_vec();
|
||||
keep_sorted.sort_unstable();
|
||||
keep_sorted.dedup();
|
||||
for &q in &keep_sorted {
|
||||
if q >= qubits {
|
||||
return Err(format!("keep qubit {q} out of range for n={qubits}"));
|
||||
}
|
||||
}
|
||||
let k = keep_sorted.len();
|
||||
check_density_qubits(k)?;
|
||||
let dim = dim_of(qubits);
|
||||
let kdim = dim_of(k);
|
||||
let mut out = mat_zeros(kdim);
|
||||
|
||||
// Map full basis index -> kept subspace index
|
||||
let map_keep = |full: usize| -> usize {
|
||||
let mut idx = 0usize;
|
||||
for (bit_pos, &q) in keep_sorted.iter().enumerate() {
|
||||
if (full >> q) & 1 == 1 {
|
||||
idx |= 1 << bit_pos;
|
||||
}
|
||||
}
|
||||
idx
|
||||
};
|
||||
|
||||
let traced: Vec<usize> = (0..qubits).filter(|q| !keep_sorted.contains(q)).collect();
|
||||
|
||||
for i in 0..dim {
|
||||
for j in 0..dim {
|
||||
// Only contribute when traced bits of i and j match
|
||||
let mut same = true;
|
||||
for &q in &traced {
|
||||
if ((i >> q) & 1) != ((j >> q) & 1) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !same {
|
||||
continue;
|
||||
}
|
||||
let ik = map_keep(i);
|
||||
let jk = map_keep(j);
|
||||
let v = mat_get(rho, dim, i, j);
|
||||
let cur = mat_get(&out, kdim, ik, jk);
|
||||
mat_set(&mut out, kdim, ik, jk, cur.add(v));
|
||||
}
|
||||
}
|
||||
Ok((k, out))
|
||||
}
|
||||
|
||||
/// Jacobi eigenvalue algorithm for Hermitian matrices. Returns eigenvalues (desc) and eigenvectors as columns.
|
||||
pub fn hermite_eig(m: &Mat, dim: usize) -> Result<(Vec<f64>, Vec<Vec<C>>), String> {
|
||||
check_hermitian(m, dim)?;
|
||||
let mut a = m.clone();
|
||||
// Force diagonal imaginary parts to 0 (Hermitian)
|
||||
for i in 0..dim {
|
||||
let d = mat_get(&a, dim, i, i);
|
||||
mat_set(&mut a, dim, i, i, C::new(d.re, 0.0));
|
||||
}
|
||||
let mut v = mat_zeros(dim);
|
||||
for i in 0..dim {
|
||||
mat_set(&mut v, dim, i, i, C::one());
|
||||
}
|
||||
|
||||
let max_iter = 200 * dim * dim;
|
||||
for _ in 0..max_iter {
|
||||
let mut p = 0usize;
|
||||
let mut q = 1usize;
|
||||
let mut max_abs = 0.0;
|
||||
for i in 0..dim {
|
||||
for j in (i + 1)..dim {
|
||||
let mag = mat_get(&a, dim, i, j).norm_sq().sqrt();
|
||||
if mag > max_abs {
|
||||
max_abs = mag;
|
||||
p = i;
|
||||
q = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
if max_abs < 1e-14 {
|
||||
break;
|
||||
}
|
||||
|
||||
let app = mat_get(&a, dim, p, p).re;
|
||||
let aqq = mat_get(&a, dim, q, q).re;
|
||||
let apq = mat_get(&a, dim, p, q);
|
||||
let abs_apq = apq.norm_sq().sqrt();
|
||||
let phase = apq.scale(1.0 / abs_apq); // e^{iα}
|
||||
|
||||
// tan(2φ) = 2|apq| / (app - aqq)
|
||||
let diff = app - aqq;
|
||||
let (c, s_mag) = if abs_apq < 1e-30 {
|
||||
(1.0, 0.0)
|
||||
} else {
|
||||
let tau = diff / (2.0 * abs_apq);
|
||||
let t = if tau >= 0.0 {
|
||||
1.0 / (tau + (1.0 + tau * tau).sqrt())
|
||||
} else {
|
||||
-1.0 / (-tau + (1.0 + tau * tau).sqrt())
|
||||
};
|
||||
let cc = 1.0 / (1.0 + t * t).sqrt();
|
||||
(cc, t * cc)
|
||||
};
|
||||
let s = phase.scale(s_mag); // complex sine
|
||||
|
||||
// Apply Jacobi rotation to A (similarity J† A J)
|
||||
let mut row_p = vec![C::zero(); dim];
|
||||
let mut row_q = vec![C::zero(); dim];
|
||||
for i in 0..dim {
|
||||
let aip = mat_get(&a, dim, i, p);
|
||||
let aiq = mat_get(&a, dim, i, q);
|
||||
row_p[i] = aip.scale(c).add(aiq.mul(s));
|
||||
row_q[i] = aiq.scale(c).sub(aip.mul(s.conj()));
|
||||
}
|
||||
// Diagonals: phase = apq/|apq| ⇒ Re(conj(phase)*apq) = |apq|
|
||||
let new_app = c * c * app + s_mag * s_mag * aqq + 2.0 * c * s_mag * abs_apq;
|
||||
let new_aqq = c * c * aqq + s_mag * s_mag * app - 2.0 * c * s_mag * abs_apq;
|
||||
|
||||
for i in 0..dim {
|
||||
if i == p || i == q {
|
||||
continue;
|
||||
}
|
||||
mat_set(&mut a, dim, i, p, row_p[i]);
|
||||
mat_set(&mut a, dim, p, i, row_p[i].conj());
|
||||
mat_set(&mut a, dim, i, q, row_q[i]);
|
||||
mat_set(&mut a, dim, q, i, row_q[i].conj());
|
||||
}
|
||||
mat_set(&mut a, dim, p, p, C::new(new_app, 0.0));
|
||||
mat_set(&mut a, dim, q, q, C::new(new_aqq, 0.0));
|
||||
mat_set(&mut a, dim, p, q, C::zero());
|
||||
mat_set(&mut a, dim, q, p, C::zero());
|
||||
|
||||
// V ← V J
|
||||
for i in 0..dim {
|
||||
let vip = mat_get(&v, dim, i, p);
|
||||
let viq = mat_get(&v, dim, i, q);
|
||||
mat_set(&mut v, dim, i, p, vip.scale(c).add(viq.mul(s)));
|
||||
mat_set(
|
||||
&mut v,
|
||||
dim,
|
||||
i,
|
||||
q,
|
||||
viq.scale(c).sub(vip.mul(s.conj())),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut evals: Vec<(f64, usize)> = (0..dim)
|
||||
.map(|i| (mat_get(&a, dim, i, i).re, i))
|
||||
.collect();
|
||||
evals.sort_by(|x, y| y.0.partial_cmp(&x.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
|
||||
let mut eigenvalues = Vec::with_capacity(dim);
|
||||
let mut eigenvectors = Vec::with_capacity(dim);
|
||||
for &(ev, idx) in &evals {
|
||||
eigenvalues.push(ev);
|
||||
let mut col = Vec::with_capacity(dim);
|
||||
for row in 0..dim {
|
||||
col.push(mat_get(&v, dim, row, idx));
|
||||
}
|
||||
let nrm = col.iter().map(|c| c.norm_sq()).sum::<f64>().sqrt();
|
||||
if nrm > 1e-15 {
|
||||
for c in &mut col {
|
||||
*c = c.scale(1.0 / nrm);
|
||||
}
|
||||
}
|
||||
eigenvectors.push(col);
|
||||
}
|
||||
Ok((eigenvalues, eigenvectors))
|
||||
}
|
||||
|
||||
/// Thin SVD via eig of A†A for complex matrix rows×cols (rows = 2^cut, cols = 2^(n-cut)).
|
||||
pub fn schmidt_decompose(amps: &[C], qubits: usize, cut: usize) -> Result<Value, String> {
|
||||
if cut == 0 || cut >= qubits {
|
||||
return Err(format!("schmidt cut must be in 1..{} (got {cut})", qubits - 1));
|
||||
}
|
||||
check_density_qubits(qubits)?;
|
||||
let da = dim_of(cut);
|
||||
let db = dim_of(qubits - cut);
|
||||
if amps.len() != da * db {
|
||||
return Err("state dimension mismatch for schmidt".into());
|
||||
}
|
||||
// Build Gram G = M M† (da×da) where M[ia, ib] = ψ[(ib << cut) | ia] (A = low bits)
|
||||
let mut gram = mat_zeros(da);
|
||||
for ia in 0..da {
|
||||
for ja in 0..da {
|
||||
let mut s = C::zero();
|
||||
for ib in 0..db {
|
||||
let i = (ib << cut) | ia;
|
||||
let j = (ib << cut) | ja;
|
||||
s = s.add(amps[i].mul(amps[j].conj()));
|
||||
}
|
||||
mat_set(&mut gram, da, ia, ja, s);
|
||||
}
|
||||
}
|
||||
let (evals, evecs) = hermite_eig(&gram, da)?;
|
||||
let coeffs: Vec<f64> = evals
|
||||
.iter()
|
||||
.map(|e| e.max(0.0).sqrt())
|
||||
.collect();
|
||||
// entropy
|
||||
let mut entropy = 0.0;
|
||||
for &c in &coeffs {
|
||||
let p = c * c;
|
||||
if p > 1e-15 {
|
||||
entropy -= p * p.ln();
|
||||
}
|
||||
}
|
||||
// Keep significant coeffs
|
||||
let ua: Vec<Value> = evecs
|
||||
.iter()
|
||||
.map(|col| Value::Array(col.iter().map(|c| c.to_json()).collect()))
|
||||
.collect();
|
||||
|
||||
// For each singular vector u_k, v_k = M† u_k / σ_k
|
||||
let mut ub = Vec::new();
|
||||
for (k, sigma) in coeffs.iter().enumerate() {
|
||||
if *sigma < 1e-12 {
|
||||
ub.push(Value::Array(
|
||||
(0..db).map(|_| C::zero().to_json()).collect(),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let u = &evecs[k];
|
||||
let mut vk = vec![C::zero(); db];
|
||||
for ib in 0..db {
|
||||
let mut s = C::zero();
|
||||
for ia in 0..da {
|
||||
let idx = (ib << cut) | ia;
|
||||
// (M† u)_ib = Σ_ia conj(M_ia,ib) u_ia = Σ conj(ψ) u
|
||||
s = s.add(amps[idx].conj().mul(u[ia]));
|
||||
}
|
||||
vk[ib] = s.scale(1.0 / sigma);
|
||||
}
|
||||
ub.push(Value::Array(vk.iter().map(|c| c.to_json()).collect()));
|
||||
}
|
||||
|
||||
// Drop near-zero trailing for readability but keep all for determinism
|
||||
let _ = coeffs
|
||||
.iter()
|
||||
.position(|&c| c < 1e-10)
|
||||
.unwrap_or(coeffs.len());
|
||||
|
||||
Ok(json!({
|
||||
"_type": "quantum_schmidt",
|
||||
"cut": cut,
|
||||
"qubits": qubits,
|
||||
"coeffs": coeffs,
|
||||
"ua": ua,
|
||||
"ub": ub,
|
||||
"entropy": entropy,
|
||||
}))
|
||||
}
|
||||
|
||||
fn pauli_matrix(p: char) -> Result<[[C; 2]; 2], String> {
|
||||
match p.to_ascii_uppercase() {
|
||||
'I' => Ok([
|
||||
[C::one(), C::zero()],
|
||||
[C::zero(), C::one()],
|
||||
]),
|
||||
'X' => Ok([
|
||||
[C::zero(), C::one()],
|
||||
[C::one(), C::zero()],
|
||||
]),
|
||||
'Y' => Ok([
|
||||
[C::zero(), C::new(0.0, -1.0)],
|
||||
[C::new(0.0, 1.0), C::zero()],
|
||||
]),
|
||||
'Z' => Ok([
|
||||
[C::one(), C::zero()],
|
||||
[C::zero(), C::new(-1.0, 0.0)],
|
||||
]),
|
||||
other => Err(format!("unknown Pauli `{other}` (I/X/Y/Z)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pauli string: left = qubit n-1 (MSB), right = qubit 0 (LSB). Returns dim×dim.
|
||||
pub fn pauli_string_matrix(s: &str, qubits: usize) -> Result<(usize, Mat), String> {
|
||||
let t = s.trim();
|
||||
if t.len() != qubits {
|
||||
return Err(format!(
|
||||
"Pauli string length {} != qubits {qubits} (left=high bit)",
|
||||
t.len()
|
||||
));
|
||||
}
|
||||
let chars: Vec<char> = t.chars().collect();
|
||||
// chars[0] = qubit n-1
|
||||
let mut mat = {
|
||||
let p = pauli_matrix(chars[qubits - 1])?; // qubit 0 first in kron chain
|
||||
let mut m = mat_zeros(2);
|
||||
for i in 0..2 {
|
||||
for j in 0..2 {
|
||||
mat_set(&mut m, 2, i, j, p[i][j]);
|
||||
}
|
||||
}
|
||||
(2usize, m)
|
||||
};
|
||||
for q in 1..qubits {
|
||||
let ch = chars[qubits - 1 - q];
|
||||
let p = pauli_matrix(ch)?;
|
||||
let mut b = mat_zeros(2);
|
||||
for i in 0..2 {
|
||||
for j in 0..2 {
|
||||
mat_set(&mut b, 2, i, j, p[i][j]);
|
||||
}
|
||||
}
|
||||
// New = b ⊗ old so that higher qubit is left in kron...
|
||||
// Full basis: index bit q corresponds to qubit q.
|
||||
// Kronecker A⊗B means A on high subspace if we use (i<<logB)|j with j low.
|
||||
// We build from qubit0 (LSB) up: mat = P_{q} ⊗ mat
|
||||
let (da, a) = (2usize, b);
|
||||
let (db, ref bm) = mat;
|
||||
let out = kronecker(&a, da, bm, db);
|
||||
mat = (da * db, out);
|
||||
}
|
||||
Ok(mat)
|
||||
}
|
||||
|
||||
pub fn expect_pauli(rho: &Mat, dim: usize, qubits: usize, obs: &str) -> Result<f64, String> {
|
||||
let (od, op) = pauli_string_matrix(obs, qubits)?;
|
||||
if od != dim {
|
||||
return Err("observable dimension mismatch".into());
|
||||
}
|
||||
// ⟨P⟩ = Tr(ρ P) = Σ_ij ρ_ij P_ji
|
||||
let mut s = C::zero();
|
||||
for i in 0..dim {
|
||||
for j in 0..dim {
|
||||
s = s.add(mat_get(rho, dim, i, j).mul(mat_get(&op, dim, j, i)));
|
||||
}
|
||||
}
|
||||
if s.im.abs() > 1e-8 {
|
||||
return Err(format!("expectation has imaginary part {}", s.im));
|
||||
}
|
||||
Ok(s.re)
|
||||
}
|
||||
|
||||
pub fn expect_matrix(rho: &Mat, dim: usize, obs: &Mat, odim: usize) -> Result<f64, String> {
|
||||
if odim != dim {
|
||||
return Err("observable dimension mismatch".into());
|
||||
}
|
||||
let mut s = C::zero();
|
||||
for i in 0..dim {
|
||||
for j in 0..dim {
|
||||
s = s.add(mat_get(rho, dim, i, j).mul(mat_get(obs, dim, j, i)));
|
||||
}
|
||||
}
|
||||
Ok(s.re)
|
||||
}
|
||||
|
||||
pub fn fidelity_pure(a: &[C], b: &[C]) -> Result<f64, String> {
|
||||
if a.len() != b.len() {
|
||||
return Err("fidelity: state dimensions differ".into());
|
||||
}
|
||||
let mut s = C::zero();
|
||||
for i in 0..a.len() {
|
||||
s = s.add(a[i].conj().mul(b[i]));
|
||||
}
|
||||
Ok(s.norm_sq())
|
||||
}
|
||||
|
||||
pub fn all_pauli_labels(qubits: usize) -> Result<Vec<String>, String> {
|
||||
if qubits > 3 {
|
||||
return Err("paulivec default basis only for n≤3; pass explicit ops".into());
|
||||
}
|
||||
let letters = ['I', 'X', 'Y', 'Z'];
|
||||
let n = qubits;
|
||||
let total = 4usize.pow(n as u32);
|
||||
let mut out = Vec::with_capacity(total);
|
||||
for code in 0..total {
|
||||
let mut s = String::with_capacity(n);
|
||||
let mut c = code;
|
||||
// left = high qubit
|
||||
let mut chars = vec!['I'; n];
|
||||
for q in 0..n {
|
||||
chars[n - 1 - q] = letters[c % 4];
|
||||
c /= 4;
|
||||
}
|
||||
for ch in chars {
|
||||
s.push(ch);
|
||||
}
|
||||
out.push(s);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn spectrum_handle(evals: &[f64], evecs: &[Vec<C>]) -> Value {
|
||||
let eigenvectors: Vec<Value> = evecs
|
||||
.iter()
|
||||
.map(|col| Value::Array(col.iter().map(|c| c.to_json()).collect()))
|
||||
.collect();
|
||||
json!({
|
||||
"_type": "quantum_spectrum",
|
||||
"eigenvalues": evals,
|
||||
"eigenvectors": eigenvectors,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn value_as_matrix(v: &Value) -> Result<(usize, Mat), String> {
|
||||
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_density")
|
||||
|| v.get("_type").and_then(|t| t.as_str()) == Some("density")
|
||||
|| v.get("_type").and_then(|t| t.as_str()) == Some("密度")
|
||||
|| v.get("matrix").is_some()
|
||||
{
|
||||
return parse_density(v);
|
||||
}
|
||||
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_gate") {
|
||||
let nested = crate::sim::gate_matrix_of(v)?;
|
||||
let (dim, flat) = nested_to_flat(&nested)?;
|
||||
return Ok(((dim as f64).log2() as usize, flat));
|
||||
}
|
||||
// nested list
|
||||
let nested = parse_matrix(v)?;
|
||||
let (dim, flat) = nested_to_flat(&nested)?;
|
||||
Ok(((dim as f64).log2() as usize, flat))
|
||||
}
|
||||
|
||||
/// Helper for JSON amps list export (re-export style).
|
||||
pub fn amps_json(amps: &[C]) -> Value {
|
||||
amps_to_json(amps)
|
||||
}
|
||||
|
||||
pub fn density_map_insert_matrix(obj: &mut Map<String, Value>, rho: &Mat, dim: usize) {
|
||||
obj.insert(
|
||||
"matrix".into(),
|
||||
matrix_to_json(&flat_to_nested(rho, dim)),
|
||||
);
|
||||
}
|
||||
@@ -42,6 +42,18 @@ impl C {
|
||||
im: self.im * s,
|
||||
}
|
||||
}
|
||||
pub fn conj(self) -> C {
|
||||
C {
|
||||
re: self.re,
|
||||
im: -self.im,
|
||||
}
|
||||
}
|
||||
pub fn sub(self, o: C) -> C {
|
||||
C {
|
||||
re: self.re - o.re,
|
||||
im: self.im - o.im,
|
||||
}
|
||||
}
|
||||
pub fn to_json(self) -> Value {
|
||||
json!({ "re": self.re, "im": self.im })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: quantum linalg smoke
|
||||
description: Q7a density / partial_trace / expect / schmidt / purity
|
||||
import quantum:ext/quantum/quantum.mq.md
|
||||
import math:lib/math.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*qc = > quantum.circuit qubits=2*
|
||||
*qc = > `qc`.h qubit=0*
|
||||
*qc = > `qc`.cx control=0 target=1*
|
||||
|
||||
*rho = > `qc`.density*
|
||||
*pur = > `rho`.purity*
|
||||
*lo = > math.div a=9 b=10*
|
||||
1. `pur` > `lo`
|
||||
> print text=purity-ok
|
||||
2. *
|
||||
> print text=purity-fail
|
||||
|
||||
*red = > `rho`.partial_trace keep=0*
|
||||
*rpur = > `red`.purity*
|
||||
*half_lo = > math.div a=4 b=10*
|
||||
*half_hi = > math.div a=6 b=10*
|
||||
1. `rpur` > `half_lo`
|
||||
1. `rpur` < `half_hi`
|
||||
> print text=reduce-ok
|
||||
2. *
|
||||
> print text=reduce-fail
|
||||
2. *
|
||||
> print text=reduce-fail
|
||||
|
||||
*zz = "ZZ"*
|
||||
*ezz = > `qc`.expect obs=`zz`*
|
||||
*zzi = > math.div a=9 b=10*
|
||||
1. `ezz` > `zzi`
|
||||
> print text=expect-ok
|
||||
2. *
|
||||
> print text=expect-fail
|
||||
|
||||
*sch = > `qc`.schmidt cut=1*
|
||||
*ent = sch[^entropy]*
|
||||
*elo = > math.div a=1 b=2*
|
||||
1. `ent` > `elo`
|
||||
> print text=schmidt-ok
|
||||
2. *
|
||||
> print text=schmidt-fail
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: quantum viz advanced smoke
|
||||
description: Q7b hinton / qsphere / multibloch SVG markers
|
||||
import quantum:ext/quantum/quantum.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*qc = > quantum.circuit qubits=2*
|
||||
*qc = > `qc`.h qubit=0*
|
||||
*qc = > `qc`.cx control=0 target=1*
|
||||
|
||||
*h = > `qc`.draw kind="hinton" path="quantum-viz-hinton.svg"*
|
||||
*q = > `qc`.draw kind="qsphere" path="quantum-viz-qsphere.svg"*
|
||||
*m = > `qc`.draw kind="multibloch" path="quantum-viz-multibloch.svg"*
|
||||
|
||||
*rho = > `qc`.density*
|
||||
*c = > `rho`.draw kind="city" path="quantum-viz-city.svg"*
|
||||
|
||||
> print text=viz-ok
|
||||
@@ -2595,6 +2595,45 @@ fn ext_quantum_custom_gate_zh_smoke() {
|
||||
assert_out("tests/ext/quantum-custom-gate-zh-smoke.mq.md", "custom-ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_quantum_linalg_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "-p", "marqdo_plugin_quantum"])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.status()
|
||||
.expect("build quantum plugin");
|
||||
assert!(status.success(), "failed to build marqdo_plugin_quantum");
|
||||
assert_out(
|
||||
"tests/ext/quantum-linalg-smoke.mq.md",
|
||||
"purity-ok\nreduce-ok\nexpect-ok\nschmidt-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_quantum_viz_advanced_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "-p", "marqdo_plugin_quantum"])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.status()
|
||||
.expect("build quantum plugin");
|
||||
assert!(status.success(), "failed to build marqdo_plugin_quantum");
|
||||
assert_out("tests/ext/quantum-viz-advanced-smoke.mq.md", "viz-ok");
|
||||
for (p, marker) in [
|
||||
("tests/ext/quantum-viz-hinton.svg", "data-hinton"),
|
||||
("tests/ext/quantum-viz-qsphere.svg", "data-qsphere"),
|
||||
("tests/ext/quantum-viz-multibloch.svg", "data-multibloch"),
|
||||
("tests/ext/quantum-viz-city.svg", "data-city"),
|
||||
] {
|
||||
let svg = std::fs::read_to_string(p).unwrap_or_default();
|
||||
assert!(
|
||||
svg.contains("<svg") && svg.contains(marker),
|
||||
"expected {marker} in {p}, got {} bytes",
|
||||
svg.len()
|
||||
);
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_agent_framework_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
|
||||
Reference in new issue
Block a user