Land quantum Q4 visuals and gate Stream to LLM/agent imports.

Add probs/Bloch draw kinds and matches_matrix, plus feature docs; hide the view Stream panel unless llm/agent is imported, and stop rewriting method names like 绘图 through host_plot aliases.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-12 12:36:51 +08:00
1 parent 25b7be6739
commit eea6fe1a0e
20 files changed
+852 -23

No files matched your search

+3 -3
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Accepted · 实现中**(Q0–Q3:门集 + `run` + `steps=`/`draw`;Q4+ 见路线图) |
| 状态 | **Accepted · Q0–Q4 已落地**(概率/布洛赫/`matches_matrix`/用户文档;Q5+ 见路线图) |
| 日期 | 2026-08-12 |
| 相关 | [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` / `量子`) |
@@ -314,7 +314,7 @@ Q0 脚手架:CATALOG + plugins/quantum Hello + L1 ensure_plugin
Q1 态向量 + I/X/H/CX + simulate/probabilities;贝尔态 gold
Q2 Y/Z/S/T/Rx/Ry/Rz/CZ/SWAP + run(seed) + 中英 API 对齐
Q3 电路表 steps= + draw 电路 SVG + view record_plot/识别;examples/
Q4 概率/布洛赫图;matches_matrix;文档站 public/features
Q4 概率/布洛赫图;matches_matrix;文档站 public/features ← **done**
Q5 (可选,另文)噪声/密度矩阵;>12 qubits 张量网络——不挡 Accepted
```
@@ -324,7 +324,7 @@ Q5 (可选,另文)噪声/密度矩阵;>12 qubits 张量网络——不
| **Q1** | 贝尔态 `probabilities` ≈ 0.5/0.5 | `tests/ext/quantum-bell-smoke.mq.md` |
| **Q2** | 旋转门 + `run seed=` 计数稳定 | 中英双金样 |
| **Q3** | `steps=` 表;`draw` SVG 在 `view` HTML 含 `<svg` | 与 math-plot 同级断言 |
| **Q4** | 概率图 + 布洛赫;用户文档页 | `view output` 可浏览示例 |
| **Q4** | 概率图 + 布洛赫;`matches_matrix`;用户文档页 | `quantum-draw-smoke` / `quantum-gate-matrix-smoke`;`view output` 可浏览示例 |
实现路线图跟踪见 [roadmap/ext-quantum.md](../roadmap/ext-quantum.md)。
+2
View File
@@ -118,6 +118,8 @@ view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时
### 5.1 Stream 面板(对齐主流 LLM 呈现)
**仅当**当前文件 frontmatter 导入了 `ext/ai/llm` / `大模型` 或 `ext/ai/agent` / `智能体`(及等价路径)时,在 live Execution 区显示;普通脚本页不出现该组件。
参考常见助手产品(思考折叠 + 正文流式、工具/子步骤独立卡片):**不要**把所有 SSE 事件打成一条混色终端日志。
| 区块 | 事件 | 呈现 |
+3 -3
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Q0–Q3 已落地**(设计 Accepted;Q4+ 待做) |
| 状态 | **Q0–Q4 已落地**(设计 Accepted;Q5 可选噪声/更大 n 另文) |
| 日期 | 2026-08-12 |
| **锁定设计** | [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) |
@@ -26,10 +26,10 @@
| **Q1** | 态向量;I/X/H/CX;`simulate` / `probabilities`;贝尔态 gold | **done** |
| **Q2** | Y/Z/S/T/R\* /CZ/SWAP;`run seed=`;中英 API | **done** |
| **Q3** | `steps=` 电路表;`draw` 轨线 SVG;view `record_plot` 或值识别 | **done** |
| **Q4** | 概率条 / 布洛赫;`matches_matrix`;examples + 用户文档 | pending |
| **Q4** | 概率条 / 布洛赫;`matches_matrix`;examples + 用户文档 | **done** |
| **Q5** | (可选)噪声 / 更大 n —— 另文 | pending |
验收金样(目标):`tests/ext/quantum-bell-smoke.mq.md`、`quantum-draw-smoke.mq.md`、中文对称样例。
验收金样:`tests/ext/quantum-bell-smoke.mq.md`、`quantum-draw-smoke.mq.md`、`quantum-gate-matrix-smoke.mq.md`、中文对称样例。
---
+1
View File
@@ -22,5 +22,6 @@ H on qubit 0, then CNOT(0→1). Ideal measurement: |00⟩ and |11⟩ each with p
*`qc` = > quantum.circuit qubits=2 steps=`steps` *
*`p` = > `qc`.probabilities *
*`_` = > `qc`.draw path=bell.svg *
*`_` = > `qc`.draw kind=probs path=bell-probs.svg *
> print text=`p`
+28 -2
View File
@@ -120,7 +120,33 @@ Sample computational-basis shots (deterministic with `seed=`).
## draw
+ `path`=None
+ `kind`=circuit
+ `qubit`=0
Circuit rail SVG (`quantum_svg`). Records into view/CLI plots via host `record_plot`.
Circuit rail / probability bars / Bloch sphere SVG (`kind=circuit|probs|bloch`). Records into view/CLI plots via host `record_plot`.
**> quantum_draw_circuit circuit=`self` path=`path`**
**> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit`**
# gate
+ `name`
+ `theta`=None
Named gate handle (built-in unitary). Use `matches_matrix` to check an author-supplied matrix.
> ensure_plugin
**> quantum_gate_new name=`name` theta=`theta`**
## matrix
**> quantum_gate_matrix gate=`self`**
## matches_matrix
+ `matrix`
+ `tol`=0.000000001
**> quantum_gate_matches_matrix gate=`self` matrix=`matrix` tol=`tol`**
## draw
+ `path`=None
**> quantum_gate_draw gate=`self` path=`path`**
+28 -2
View File
@@ -118,7 +118,33 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。
## 绘图
+ `路径`=None
+ `种类`=circuit
+ `比特`=0
电路轨线 SVG(`quantum_svg`)。经 host `record_plot` 进入 view/CLI plots。
电路轨线 / 概率条 / 布洛赫球(种类 circuit、probs 或 bloch)。经 record_plot 进入 view/CLI plots。
**> quantum_draw_circuit circuit=`self` path=`路径`**
**> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特`**
# 门
+ `名`
+ `参数`=None
具名门句柄。用「匹配矩阵」核对作者给出的矩阵。
> 确保插件
**> quantum_gate_new name=`名` theta=`参数`**
## 矩阵
**> quantum_gate_matrix gate=`self`**
## 匹配矩阵
+ `矩阵`
+ `容差`=0.000000001
**> quantum_gate_matches_matrix gate=`self` matrix=`矩阵` tol=`容差`**
## 绘图
+ `路径`=None
**> quantum_gate_draw gate=`self` path=`路径`**
+180
View File
@@ -180,3 +180,183 @@ fn draw_swap(out: &mut String, x: f64, a: usize, b: usize) {
));
}
}
/// Probability histogram from basis-label → probability map.
pub fn probs_svg(probs: &serde_json::Map<String, Value>) -> String {
let mut entries: Vec<(String, f64)> = probs
.iter()
.filter_map(|(k, v)| v.as_f64().map(|p| (k.clone(), p)))
.collect();
entries.sort_by(|a, b| a.0.cmp(&b.0));
if entries.is_empty() {
entries.push(("∅".into(), 0.0));
}
let n = entries.len().max(1);
let bar_w = 36.0;
let gap = 12.0;
let chart_h = 120.0;
let pad_l = 40.0;
let pad_b = 36.0;
let pad_t = 20.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(&format!(
r#"<line x1="{x0}" y1="{y}" x2="{x1}" y2="{y}" stroke="{STROKE}" stroke-width="1.2"/>"#,
x0 = pad_l - 4.0,
x1 = width - pad_r,
y = pad_t + chart_h,
));
body.push_str(&format!(
r#"<line x1="{x}" y1="{y0}" x2="{x}" y2="{y1}" stroke="{STROKE}" stroke-width="1.2"/>"#,
x = pad_l - 4.0,
y0 = pad_t,
y1 = pad_t + chart_h,
));
body.push_str(&format!(
r#"<text x="6" y="{ty}" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="{STROKE}">1</text>"#,
ty = pad_t + 4.0,
));
body.push_str(&format!(
r#"<text x="6" y="{ty}" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="{STROKE}">0</text>"#,
ty = pad_t + chart_h + 4.0,
));
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#"<rect x="{x}" y="{y}" width="{bar_w}" height="{h}" fill="{bar_fill}" stroke="{STROKE}" stroke-width="1"/>"#,
x = x,
y = y,
bar_w = bar_w,
h = h,
bar_fill = bar_fill,
STROKE = STROKE,
));
body.push_str(&format!(
r#"<text x="{cx}" y="{ty}" text-anchor="middle" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="{STROKE}">{lab}</text>"#,
cx = x + bar_w / 2.0,
ty = pad_t + chart_h + 16.0,
lab = esc(label),
STROKE = STROKE,
));
body.push_str(&format!(
r#"<text x="{cx}" y="{ty}" text-anchor="middle" font-family="ui-monospace,Menlo,monospace" font-size="9" fill="{muted}">{pval:.2}</text>"#,
cx = x + bar_w / 2.0,
ty = y - 4.0,
pval = p,
muted = muted,
));
}
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="measurement probabilities">{body}</svg>"#,
w = width,
h = height,
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;
// 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(&format!(
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="{fill}" stroke="{STROKE}" stroke-width="1.5"/>"#,
cx = cx,
cy = cy,
r = r,
fill = BOX,
STROKE = STROKE,
));
// axes
let axes = [
("+X", 1.0, 0.0, 0.0),
("-X", -1.0, 0.0, 0.0),
("+Y", 0.0, 1.0, 0.0),
("+Z", 0.0, 0.0, 1.0),
("-Z", 0.0, 0.0, -1.0),
];
for (lab, vx, vy, vz) in axes {
let x1 = px(0.0, 0.0, 0.0);
let y1 = py(0.0, 0.0, 0.0);
let x2 = px(vx, vy, vz);
let y2 = py(vx, vy, vz);
body.push_str(&format!(
r#"<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{axis}" stroke-width="1" stroke-dasharray="3 2"/>"#,
x1 = x1,
y1 = y1,
x2 = x2,
y2 = y2,
axis = "#888",
));
body.push_str(&format!(
r#"<text x="{tx}" y="{ty}" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="{STROKE}">{lab}</text>"#,
tx = x2 + 4.0,
ty = y2 + 3.0,
lab = lab,
STROKE = STROKE,
));
}
// state vector
let sx = px(x, y, z);
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";
body.push_str(&format!(
r#"<line x1="{ox}" y1="{oy}" x2="{sx}" y2="{sy}" stroke="{arrow}" stroke-width="2.5"/>"#,
ox = ox,
oy = oy,
sx = sx,
sy = sy,
arrow = arrow,
));
body.push_str(&format!(
r#"<circle cx="{sx}" cy="{sy}" r="4" fill="{arrow}"/>"#,
sx = sx,
sy = sy,
arrow = arrow,
));
body.push_str(&format!(
r#"<text x="12" y="{hy}" font-family="ui-monospace,Menlo,monospace" font-size="11" fill="{STROKE}">⟨X⟩={bx:.3} ⟨Y⟩={by:.3} ⟨Z⟩={bz:.3}</text>"#,
hy = height - 12.0,
bx = x,
by = y,
bz = z,
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="Bloch sphere">{body}</svg>"#,
w = width,
h = height,
body = body,
)
}
/// Minimal single-gate glyph for `# gate`.draw.
pub fn gate_svg(name: &str) -> String {
let label = esc(name);
let width = 64.0;
let height = 48.0;
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="gate {label}"><rect x="12" y="8" width="40" height="32" rx="4" fill="{BOX}" stroke="{STROKE}" stroke-width="1.5"/><text x="32" y="29" text-anchor="middle" font-family="ui-monospace,Menlo,monospace" font-size="14" fill="{STROKE}">{label}</text></svg>"#,
w = width,
h = height,
label = label,
BOX = BOX,
STROKE = STROKE,
)
}
+134 -4
View File
@@ -345,13 +345,40 @@ q_ffi!(quantum_run, |args: &Value| {
q_ffi!(quantum_draw_circuit, |args: &Value| {
let c = circuit_of(args)?;
let svg = draw::circuit_svg(c)?;
let kind = args
.get("kind")
.or_else(|| args.get("种类"))
.and_then(|v| v.as_str())
.unwrap_or("circuit")
.to_ascii_lowercase();
let qubit = arg_u(args, "qubit")
.or_else(|_| arg_u(args, "比特"))
.unwrap_or(0);
let path = args
.get("path")
.or_else(|| args.get("路径"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
// Prefer view/CLI plots channel; still return structured value for authors.
let (kind_out, svg) = match kind.as_str() {
"circuit" | "" => ("circuit", draw::circuit_svg(c)?),
"probs" | "probabilities" | "概率" => {
let (qubits, amps) = sim::simulate_circuit(c)?;
let probs = sim::probabilities(&amps, qubits);
("probs", draw::probs_svg(&probs))
}
"bloch" | "布洛赫" => {
let (qubits, amps) = sim::simulate_circuit(c)?;
let (x, y, z) = sim::bloch_vector(&amps, qubits, qubit)?;
("bloch", draw::bloch_svg(x, y, z))
}
other => {
return Err(format!(
"unknown draw kind `{other}` (circuit|probs|bloch)"
));
}
};
record_plot(&svg, path)?;
let ops_n = c
.get("ops")
@@ -364,13 +391,100 @@ q_ffi!(quantum_draw_circuit, |args: &Value| {
.unwrap_or(0);
Ok(json!({
"_type": "quantum_svg",
"kind": "circuit",
"kind": kind_out,
"qubits": qubits,
"ops": ops_n,
"svg": svg,
}))
});
q_ffi!(quantum_gate_new, |args: &Value| {
let name = args
.get("name")
.or_else(|| args.get("名"))
.and_then(|v| v.as_str())
.ok_or_else(|| "gate needs `name`".to_string())?;
let theta = match args.get("theta").or_else(|| args.get("参数")) {
None | Some(Value::Null) => None,
Some(v) => Some(
v.as_f64()
.or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))
.ok_or_else(|| "bad theta".to_string())?,
),
};
sim::gate_new(name, theta)
});
q_ffi!(quantum_gate_matrix, |args: &Value| {
let gate = args
.get("gate")
.or_else(|| args.get("门"))
.ok_or_else(|| "missing `gate`".to_string())?;
let name = gate
.get("name")
.or_else(|| gate.get("名"))
.and_then(|v| v.as_str())
.ok_or_else(|| "gate missing name".to_string())?;
let theta = gate
.get("theta")
.or_else(|| gate.get("参数"))
.and_then(|v| v.as_f64());
let m = sim::named_gate_matrix(name, theta)?;
Ok(sim::matrix_to_json(&m))
});
q_ffi!(quantum_gate_matches_matrix, |args: &Value| {
let gate = args
.get("gate")
.or_else(|| args.get("门"))
.ok_or_else(|| "missing `gate`".to_string())?;
let name = gate
.get("name")
.or_else(|| gate.get("名"))
.and_then(|v| v.as_str())
.ok_or_else(|| "gate missing name".to_string())?;
let theta = gate
.get("theta")
.or_else(|| gate.get("参数"))
.and_then(|v| v.as_f64());
let matrix = args
.get("matrix")
.or_else(|| args.get("矩阵"))
.ok_or_else(|| "missing `matrix`".to_string())?;
let tol = args
.get("tol")
.or_else(|| args.get("容差"))
.and_then(|v| v.as_f64())
.unwrap_or(1e-9);
let expect = sim::named_gate_matrix(name, theta)?;
let got = sim::parse_matrix(matrix)?;
Ok(json!(sim::matrices_close(&expect, &got, tol)))
});
q_ffi!(quantum_gate_draw, |args: &Value| {
let gate = args
.get("gate")
.or_else(|| args.get("门"))
.ok_or_else(|| "missing `gate`".to_string())?;
let name = gate
.get("name")
.or_else(|| gate.get("名"))
.and_then(|v| v.as_str())
.unwrap_or("?");
let path = args
.get("path")
.or_else(|| args.get("路径"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
let svg = draw::gate_svg(name);
record_plot(&svg, path)?;
Ok(json!({
"_type": "quantum_svg",
"kind": "gate",
"svg": svg,
}))
});
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
let register = match host.register_fn {
Some(f) => f,
@@ -440,9 +554,25 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("quantum_run", "circuit,shots,seed", quantum_run as PluginFn),
(
"quantum_draw_circuit",
"circuit,path",
"circuit,path,kind,qubit",
quantum_draw_circuit as PluginFn,
),
("quantum_gate_new", "name,theta", quantum_gate_new as PluginFn),
(
"quantum_gate_matrix",
"gate",
quantum_gate_matrix as PluginFn,
),
(
"quantum_gate_matches_matrix",
"gate,matrix,tol",
quantum_gate_matches_matrix as PluginFn,
),
(
"quantum_gate_draw",
"gate,path",
quantum_gate_draw as PluginFn,
),
];
for (name, params, f) in regs {
if register(host, name, params, f) != 0 {
+274
View File
@@ -765,3 +765,277 @@ pub fn push_op(circuit: &Value, gate: &str, qubits: Vec<usize>, theta: Option<f6
obj.insert("ops".into(), Value::Array(ops));
Ok(Value::Object(obj))
}
/// Bloch vector (x,y,z) for reduced density of `qubit` (LSB = qubit 0).
pub fn bloch_vector(amps: &[C], qubits: usize, qubit: usize) -> Result<(f64, f64, f64), String> {
if qubit >= qubits {
return Err(format!("bloch qubit {qubit} out of range for n={qubits}"));
}
let mut rho00 = C::zero();
let mut rho01 = C::zero();
let mut rho11 = C::zero();
let dim = amps.len();
let mask = 1usize << qubit;
for i in 0..dim {
if i & mask != 0 {
continue;
}
let i0 = i;
let i1 = i | mask;
let a0 = amps[i0];
let a1 = amps[i1];
// ρ00 += |a0|², ρ11 += |a1|², ρ01 += a0 conj(a1)
rho00 = rho00.add(C::new(a0.norm_sq(), 0.0));
rho11 = rho11.add(C::new(a1.norm_sq(), 0.0));
rho01 = rho01.add(a0.mul(C::new(a1.re, -a1.im)));
}
let x = 2.0 * rho01.re;
let y = 2.0 * rho01.im;
let z = rho00.re - rho11.re;
Ok((x, y, z))
}
/// Named single-/two-qubit unitary as row-major nested list of `{re,im}`.
pub fn named_gate_matrix(name: &str, theta: Option<f64>) -> Result<Vec<Vec<C>>, String> {
let g = name.trim().to_ascii_uppercase();
let s = std::f64::consts::FRAC_1_SQRT_2;
let m = match g.as_str() {
"I" | "ID" | "IDENTITY" => vec![
vec![C::one(), C::zero()],
vec![C::zero(), C::one()],
],
"X" | "NOT" => vec![
vec![C::zero(), C::one()],
vec![C::one(), C::zero()],
],
"Y" => vec![
vec![C::zero(), C::new(0.0, -1.0)],
vec![C::new(0.0, 1.0), C::zero()],
],
"Z" => vec![
vec![C::one(), C::zero()],
vec![C::zero(), C::new(-1.0, 0.0)],
],
"S" => vec![
vec![C::one(), C::zero()],
vec![C::zero(), C::new(0.0, 1.0)],
],
"T" => vec![
vec![C::one(), C::zero()],
vec![C::zero(), C::new(s, s)],
],
"H" | "HADAMARD" => vec![
vec![C::new(s, 0.0), C::new(s, 0.0)],
vec![C::new(s, 0.0), C::new(-s, 0.0)],
],
"RX" => {
let th = theta.ok_or("Rx needs theta")?;
let half = th / 2.0;
let c = half.cos();
let sn = half.sin();
vec![
vec![C::new(c, 0.0), C::new(0.0, -sn)],
vec![C::new(0.0, -sn), C::new(c, 0.0)],
]
}
"RY" => {
let th = theta.ok_or("Ry needs theta")?;
let half = th / 2.0;
let c = half.cos();
let sn = half.sin();
vec![
vec![C::new(c, 0.0), C::new(-sn, 0.0)],
vec![C::new(sn, 0.0), C::new(c, 0.0)],
]
}
"RZ" => {
let th = theta.ok_or("Rz needs theta")?;
let half = th / 2.0;
vec![
vec![C::new((-half).cos(), (-half).sin()), C::zero()],
vec![C::zero(), C::new(half.cos(), half.sin())],
]
}
"CX" | "CNOT" | "CN" => vec![
vec![C::one(), C::zero(), C::zero(), C::zero()],
vec![C::zero(), C::one(), C::zero(), C::zero()],
vec![C::zero(), C::zero(), C::zero(), C::one()],
vec![C::zero(), C::zero(), C::one(), C::zero()],
],
"CZ" => vec![
vec![C::one(), C::zero(), C::zero(), C::zero()],
vec![C::zero(), C::one(), C::zero(), C::zero()],
vec![C::zero(), C::zero(), C::one(), C::zero()],
vec![C::zero(), C::zero(), C::zero(), C::new(-1.0, 0.0)],
],
"SWAP" => vec![
vec![C::one(), C::zero(), C::zero(), C::zero()],
vec![C::zero(), C::zero(), C::one(), C::zero()],
vec![C::zero(), C::one(), C::zero(), C::zero()],
vec![C::zero(), C::zero(), C::zero(), C::one()],
],
other => {
return Err(format!(
"unknown gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP)"
));
}
};
Ok(m)
}
pub fn matrix_to_json(m: &[Vec<C>]) -> Value {
Value::Array(
m.iter()
.map(|row| Value::Array(row.iter().map(|c| c.to_json()).collect()))
.collect(),
)
}
fn parse_complex_cell(v: &Value) -> Result<C, String> {
match v {
Value::Number(n) => Ok(C::new(
n.as_f64().ok_or_else(|| "bad matrix cell".to_string())?,
0.0,
)),
Value::Object(map) => {
let re = map
.get("re")
.and_then(|x| x.as_f64())
.ok_or_else(|| "complex cell needs `re`".to_string())?;
let im = map.get("im").and_then(|x| x.as_f64()).unwrap_or(0.0);
Ok(C::new(re, im))
}
Value::Array(a) if a.len() == 2 => {
let re = a[0]
.as_f64()
.ok_or_else(|| "complex pair needs numbers".to_string())?;
let im = a[1]
.as_f64()
.ok_or_else(|| "complex pair needs numbers".to_string())?;
Ok(C::new(re, im))
}
_ => Err("matrix cell must be number or {re,im}".into()),
}
}
/// Parse nested list / column-map table into matrix rows.
pub fn parse_matrix(v: &Value) -> Result<Vec<Vec<C>>, String> {
match v {
Value::Array(rows) => {
let mut out = Vec::with_capacity(rows.len());
for (i, row) in rows.iter().enumerate() {
match row {
Value::Array(cells) => {
let mut r = Vec::with_capacity(cells.len());
for c in cells {
r.push(parse_complex_cell(c)?);
}
out.push(r);
}
other => {
// Flat list of complexes → treat as single row only if nested fails.
// Prefer: list of row lists.
return Err(format!(
"matrix row {i}: expected list of cells, got {other}"
));
}
}
}
if out.is_empty() {
return Err("matrix is empty".into());
}
let w = out[0].len();
if w == 0 || out.iter().any(|r| r.len() != w) {
return Err("matrix rows must be non-empty and equal length".into());
}
Ok(out)
}
Value::Object(map) => {
// Column-oriented: keys are column names with list values → transpose to rows.
// Or single key holding nested arrays.
if let Some(Value::Array(rows)) = map.values().next() {
if rows.iter().all(|r| r.is_array()) && map.len() == 1 {
return parse_matrix(&Value::Array(rows.clone()));
}
}
// Horizontal 2-col map like | a | b | with list cells → one row per index
let cols: Vec<&Vec<Value>> = map
.values()
.filter_map(|v| v.as_array())
.collect();
if cols.is_empty() {
return Err("matrix map needs list columns".into());
}
let n = cols[0].len();
if cols.iter().any(|c| c.len() != n) {
return Err("matrix columns length mismatch".into());
}
let mut out = Vec::with_capacity(n);
for i in 0..n {
let mut row = Vec::with_capacity(cols.len());
for c in &cols {
row.push(parse_complex_cell(&c[i])?);
}
out.push(row);
}
Ok(out)
}
_ => Err("matrix must be nested list or table".into()),
}
}
pub fn matrices_close(a: &[Vec<C>], b: &[Vec<C>], tol: f64) -> bool {
if a.len() != b.len() {
return false;
}
for (ra, rb) in a.iter().zip(b.iter()) {
if ra.len() != rb.len() {
return false;
}
for (ca, cb) in ra.iter().zip(rb.iter()) {
if (ca.re - cb.re).abs() > tol || (ca.im - cb.im).abs() > tol {
return false;
}
}
}
true
}
pub fn gate_new(name: &str, theta: Option<f64>) -> Result<Value, String> {
let g = name.trim().to_ascii_uppercase();
// Validate known gate.
let _ = named_gate_matrix(&g, theta)?;
let mut out = json!({ "name": g });
if let Some(t) = theta {
out.as_object_mut()
.unwrap()
.insert("theta".into(), json!(t));
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn h_bloch_on_plus() {
let mut amps = zero_state(1);
apply_h(&mut amps, 0);
let (x, y, z) = bloch_vector(&amps, 1, 0).unwrap();
assert!((x - 1.0).abs() < 1e-9, "x={x}");
assert!(y.abs() < 1e-9, "y={y}");
assert!(z.abs() < 1e-9, "z={z}");
}
#[test]
fn h_matrix_matches() {
let m = named_gate_matrix("H", None).unwrap();
let s = std::f64::consts::FRAC_1_SQRT_2;
let expect = vec![
vec![C::new(s, 0.0), C::new(s, 0.0)],
vec![C::new(s, 0.0), C::new(-s, 0.0)],
];
assert!(matrices_close(&m, &expect, 1e-12));
}
}
+1
View File
@@ -9,6 +9,7 @@ ext/ holds official optional extensions. They are not part of lib/. Resolve via
- ext/llm — OpenAI-compatible chat object. Design: doc/design/ext-llm.md
- ext/agent — agent development framework (layout helpers today; compose with ext/llm for model-backed orchestration). Design: doc/design/ext-agent.md
- ext/quantum — state-vector circuits, `steps=` tables, `draw kind=circuit|probs|bloch`, named `gate` + `matches_matrix`. Design: doc/design/ext-quantum.md
- Installer: marqdo ext list / add / remove — doc/design/ext-cli.md
- Native plugins: lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md
+1
View File
@@ -9,6 +9,7 @@ ext/ 存放官方可选扩展,不属于 lib/。解析顺序:MARQDO_EXT、./e
- ext/llm(ext/大模型)— OpenAI 兼容聊天。设计:doc/design/ext-llm.md
- ext/agent(ext/智能体)— 智能体开发框架(当前含布局助手;与大模型组合做编排见路线)。设计:doc/design/ext-agent.md
- ext/quantum(ext/量子)— 态向量电路、`步骤=` 表、`绘图 种类=circuit|probs|bloch`、具名「门」与「匹配矩阵」。设计:doc/design/ext-quantum.md
- 安装器:marqdo ext list / add / remove — doc/design/ext-cli.md
- 通用原生插件:lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md
+25
View File
@@ -0,0 +1,25 @@
---
title: Quantum circuits (ext/quantum)
description: Official quantum simulator — tables, gates, probs/Bloch SVG
> ext/quantum/quantum.mq.md
---
# main
Optional package (not stdlib). Install: `marqdo ext add quantum` (or build `marqdo_plugin_quantum`).
Bell state: H then CX. Ideal |00⟩ / |11⟩ each ≈ 1/2. `draw kind=probs` embeds a probability bar chart in view.
`steps` =
| step | gate | qubits |
|------|------|--------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
*`qc` = > quantum.circuit qubits=2 steps=`steps` *
*`p` = > `qc`.probabilities *
*`_` = > `qc`.draw kind=probs *
> print text=`p`
> print text=quantum-feature-ok
+25
View File
@@ -0,0 +1,25 @@
---
title: 量子电路(ext/quantum)
description: 官方量子模拟 — 表、门、概率/布洛赫 SVG
> ext/quantum/量子.mq.md
---
# main
可选扩展(非 stdlib)。安装:`marqdo ext add quantum`(或编译 `marqdo_plugin_quantum`)。
贝尔态:先哈达玛再控非。理想 |00⟩ / |11⟩ 各约 1/2。`绘图 种类=probs` 在 view 嵌入概率条。
`步骤` =
| 步 | 门 | 比特 |
|----|----|------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
*`qc` = > 量子.电路 比特数=2 步骤=`步骤` *
*`p` = > `qc`.概率 *
*`_` = > `qc`.绘图 种类=probs *
> 打印 内容=`p`
> 打印 内容=量子特性-ok
+2 -1
View File
@@ -517,7 +517,8 @@ impl Interpreter {
call: &CallExpr,
) -> Result<Value> {
let mut call = call.clone();
if call.path.is_none() {
// Method callees keep author names (`绘图` on quantum ≠ math `host_plot`).
if call.path.is_none() && call.receiver.is_none() {
let callee = crate::aliases::normalize_call_callee_and_args(
&call.callee,
&mut call.args,
+9 -4
View File
@@ -1839,8 +1839,13 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
(
"pending",
"input",
"Fill preset input, then <strong>Run with input</strong> — output streams in the panel (no page reload)."
.to_string(),
if vm.show_stream {
"Fill preset input, then <strong>Run with input</strong> — output streams in the panel (no page reload)."
.to_string()
} else {
"Fill preset input, then <strong>Run with input</strong>."
.to_string()
},
)
} else if vm.auto_stream {
(
@@ -1949,7 +1954,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
};
let plan_card = plan_result_card(&vm.stdout, links);
let stream_panel = match links {
LinkMode::Live => r#"<div class="stream-panel">
LinkMode::Live if vm.show_stream => r#"<div class="stream-panel">
<div class="stream-head">
<strong>Stream</strong>
<button type="button" id="stream-run">Run</button>
@@ -1962,7 +1967,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
<button type="button" class="stream-jump" id="stream-jump" hidden>↓ Latest</button>
</div>"#
.to_string(),
LinkMode::Static { .. } => String::new(),
_ => String::new(),
};
let main = format!(
r#"
+12 -4
View File
@@ -25,7 +25,7 @@ use crate::view::debug_page::{build_debug_model, page_debug};
use crate::view::html::{escape, page_file, page_index, LinkMode};
use crate::view::render::{
collect_input_prompts, render_bindings_html, render_module_structure, render_right_rail,
FileViewModel,
uses_stream_panel, FileViewModel,
};
use crate::{run_file_capture, RunOptions};
@@ -329,9 +329,16 @@ pub(crate) fn build_file_view(
};
let effective = effective_stdin(&source, stdin_lines);
let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source);
// Live + has `input` + stdin ready → stream via client `/api/run` (no page-blocking capture).
let auto_stream =
live && !input_prompts.is_empty() && !awaiting_input && !stdin_lines.is_empty();
let show_stream = module_opt
.as_ref()
.map(uses_stream_panel)
.unwrap_or(false);
// Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`.
let auto_stream = live
&& show_stream
&& !input_prompts.is_empty()
&& !awaiting_input
&& !stdin_lines.is_empty();
// Same host caps as `marqdo run`. Soft exit + sleep clamp only.
let mut opts = RunOptions::default();
opts.stdin_lines = effective.clone();
@@ -397,6 +404,7 @@ pub(crate) fn build_file_view(
input_prompts,
awaiting_input,
auto_stream,
show_stream,
plots,
bindings_html: std::mem::take(&mut bindings_html),
})
+33
View File
@@ -39,6 +39,8 @@ pub struct FileViewModel {
pub awaiting_input: bool,
/// Live view: stdin present — skip blocking page-load run; client auto-starts Stream SSE.
pub auto_stream: bool,
/// Show the LLM/agent Stream panel (live view only; gated on ext llm/agent import).
pub show_stream: bool,
/// SVG plots from math lib (embedded in Execution).
pub plots: Vec<String>,
/// HTML for Variables panel (entry bindings after run).
@@ -54,6 +56,28 @@ pub fn collect_input_prompts(module: &Module) -> Vec<String> {
out
}
/// Stream panel is for LLM/agent token streaming — only when those ext packages are imported.
pub fn uses_stream_panel(module: &Module) -> bool {
module.imports.iter().any(|imp| import_enables_stream(&imp.path))
}
fn import_enables_stream(path: &str) -> bool {
let norm = path.replace('\\', "/");
let lower = norm.to_ascii_lowercase();
lower.contains("ext/ai/llm")
|| lower.contains("/llm.mq.md")
|| lower.ends_with("llm.mq.md")
|| lower.contains("ext/llm")
|| norm.contains("ext/ai/大模型")
|| norm.contains("大模型.mq.md")
|| lower.contains("ext/ai/agent")
|| lower.contains("/agent.mq.md")
|| lower.ends_with("agent.mq.md")
|| lower.contains("ext/agent")
|| norm.contains("ext/ai/智能体")
|| norm.contains("智能体.mq.md")
}
fn collect_input_prompts_fun(fun: &Function, out: &mut Vec<String>) {
for stmt in &fun.body {
collect_input_prompts_stmt(stmt, out);
@@ -1199,4 +1223,13 @@ mod tests {
assert!(html.contains("vars-table"), "{html}");
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
}
#[test]
fn stream_panel_gated_on_llm_or_agent_import() {
let hello = crate::parse::parse_source(include_str!("../../tests/structure/hello.mq.md"))
.unwrap();
assert!(!uses_stream_panel(&hello));
let llm = crate::parse::parse_source(include_str!("../../tests/ext/llm-import.mq.md")).unwrap();
assert!(uses_stream_panel(&llm));
}
}
+33
View File
@@ -0,0 +1,33 @@
---
title: quantum draw probs/bloch smoke
description: draw kind=probs and kind=bloch return matching kind tags.
> ext/quantum/quantum.mq.md
---
# main
`steps` =
| step | gate | qubits |
|------|------|--------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
*`qc` = > quantum.circuit qubits=2 steps=`steps` *
*`img` = > `qc`.draw kind=probs path=quantum-draw-probs.svg *
*`kind` = `img`[^kind] *
1. `kind` == probs
> print text=probs-ok
2. *
> print text=probs-fail
*`qc1` = > quantum.circuit qubits=1 *
*`qc1` = > `qc1`.h qubit=0 *
*`bloch` = > `qc1`.draw kind=bloch path=quantum-draw-bloch.svg *
*`bk` = `bloch`[^kind] *
1. `bk` == bloch
> print text=bloch-ok
2. *
> print text=bloch-fail
+25
View File
@@ -0,0 +1,25 @@
---
title: quantum gate matches_matrix smoke
description: Named H matches an explicit 2x2 nested list.
> ext/quantum/quantum.mq.md
> lib/json.mq.md
---
# main
*`H_matrix` = > json.parse text=[[0.7071067811865475,0.7071067811865475],[0.7071067811865475,-0.7071067811865475]] *
*`H` = > quantum.gate name=H *
*`ok` = > `H`.matches_matrix matrix=`H_matrix` *
1. `ok`
> print text=match-ok
2. *
> print text=match-fail
*`bad` = > json.parse text=[[1,0],[0,1]] *
*`no` = > `H`.matches_matrix matrix=`bad` *
1. not `no`
> print text=reject-ok
2. *
> print text=reject-fail
+33
View File
@@ -1493,6 +1493,39 @@ fn ext_quantum_steps_smoke() {
let _ = std::fs::remove_file(svg_path);
}
#[test]
fn ext_quantum_draw_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-draw-smoke.mq.md", "probs-ok\nbloch-ok");
for p in [
"tests/ext/quantum-draw-probs.svg",
"tests/ext/quantum-draw-bloch.svg",
] {
let svg = std::fs::read_to_string(p).unwrap_or_default();
assert!(svg.contains("<svg"), "expected svg at {p}");
let _ = std::fs::remove_file(p);
}
}
#[test]
fn ext_quantum_gate_matrix_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-gate-matrix-smoke.mq.md",
"match-ok\nreject-ok",
);
}
#[test]
fn ext_agent_framework_smoke() {
let status = Command::new("cargo")