From 60d570756f32622b5518123b905cb1811de69739 Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 12 Aug 2026 13:46:56 +0800 Subject: [PATCH] Add quantum Q5 teaching noise and finish author-facing circuit APIs. Barrier/measure/append/state plus bitflip/depolarizing run trajectories let docs show noisy sampling without a full open-system simulator. Co-authored-by: Cursor --- doc/design/ext-quantum-q5.md | 69 +++++ doc/design/ext-quantum.md | 6 +- doc/roadmap/ext-quantum.md | 6 +- ext/quantum/quantum.mq.md | 40 ++- ext/quantum/量子.mq.md | 40 ++- plugins/quantum/src/draw.rs | 45 +++ plugins/quantum/src/lib.rs | 80 ++++++ plugins/quantum/src/sim.rs | 337 ++++++++++++++++++++--- public/features/05-extensions.mq.md | 2 +- public/features/05-扩展.mq.md | 2 +- tests/ext/quantum-author-api-smoke.mq.md | 37 +++ tests/ext/quantum-noise-smoke.mq.md | 18 ++ tests/gold.rs | 32 +++ 13 files changed, 663 insertions(+), 51 deletions(-) create mode 100644 doc/design/ext-quantum-q5.md create mode 100644 tests/ext/quantum-author-api-smoke.mq.md create mode 100644 tests/ext/quantum-noise-smoke.mq.md diff --git a/doc/design/ext-quantum-q5.md b/doc/design/ext-quantum-q5.md new file mode 100644 index 0000000..72a0195 --- /dev/null +++ b/doc/design/ext-quantum-q5.md @@ -0,0 +1,69 @@ +# `ext/quantum` Q5 — 最小噪声(教学用) + +| | | +|---|---| +| 状态 | **Accepted · 最小实现已落地** | +| 日期 | 2026-08-12 | +| 父设计 | [ext-quantum.md](ext-quantum.md) | +| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | + +--- + +## 1. 目标 + +在 **不** 引入完整开放系统 / 云后端的前提下,让教学文档能写「带噪声的采样」,金样可复现。 + +**刻意不做(本 Q5 切片):** 任意 Kraus 组、振幅阻尼完整表、>12 qubits 张量网络、噪声参数学习。 + +--- + +## 2. 作者面 + +电路上可选噪声字段(方法链设置,返回新句柄): + +```markdown +*`qc` = > `qc`.noise kind=bitflip p=0.05 * +# 或 +*`qc` = > `qc`.noise kind=depolarizing p=0.02 * +``` + +| 参数 | 含义 | +|------|------| +| `kind` | `bitflip` \| `depolarizing`(中文:`比特翻转` / `退极化`) | +| `p` | 每比特、每个非 `barrier`/`measure` 门后的错误概率,`0…1` | + +`simulate` / `probabilities`:**忽略噪声**(仍为理想酉演化),避免概率图被蒙特卡洛抖动。 +`run shots= seed=`:**启用噪声**(若 `p>0`):按轨迹采样,结果可复现。 + +--- + +## 3. 模拟语义(轨迹) + +每个 shot: + +1. 从 `|0…0⟩` 施电路门(跳过 `BARRIER`;`MEASURE` 不改变酉演化)。 +2. 每施一个会改态的门后,对**该门涉及的每个比特**独立: + - `bitflip`:以概率 `p` 施 `X`; + - `depolarizing`:以概率 `p` 均匀随机施 `X`/`Y`/`Z` 之一。 +3. 若电路含 `MEASURE` 标记:只对标记比特做计算基采样;否则测全部比特。 + +RNG:与现有 `run seed=` 同一 SplitMix64 流(门后噪声与最终采样共用)。 + +--- + +## 4. 与作者面补齐的关系 + +| API | 行为 | +|-----|------| +| `barrier` | 仅可视化;模拟跳过 | +| `measure` | 可视化测量符号;决定 `run` 读出哪些比特 | +| `append` | 追加另一 `circuit` 的 `ops`(或单门) | +| `state` | 等价于当前理想 `simulate` 结果(`quantum_state`) | + +--- + +## 5. 验收 + +- 金样:理想 Bell `run` 不变;`noise kind=bitflip p=1` 在已知电路上计数偏离理想(`seed=` 固定)。 +- `barrier`/`measure` 出现在 `draw kind=circuit` SVG。 +- 中英 L1 对称;仍无 `host_*` 于 `ext/**`。 diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md index 1407d39..2a7f533 100644 --- a/doc/design/ext-quantum.md +++ b/doc/design/ext-quantum.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Accepted · Q0–Q4 已落地**(概率/布洛赫/`matches_matrix`/用户文档;Q5+ 见路线图) | +| 状态 | **Accepted · Q0–Q5 最小切片已落地**(教学噪声 + barrier/measure/append/state;完整开放系统另文) | | 日期 | 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,8 +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 ← **done** -Q5 (可选,另文)噪声/密度矩阵;>12 qubits 张量网络——不挡 Accepted +Q5 教学噪声 + barrier/measure/append/state — 见 [ext-quantum-q5.md](ext-quantum-q5.md) ← **done(最小)** ``` | 阶段 | 交付物 | 验收 | @@ -325,6 +324,7 @@ Q5 (可选,另文)噪声/密度矩阵;>12 qubits 张量网络——不 | **Q2** | 旋转门 + `run seed=` 计数稳定 | 中英双金样 | | **Q3** | `steps=` 表;`draw` SVG 在 `view` HTML 含 ` quantum_swap circuit=`self` a=`a` b=`b`** +## barrier + +Visual separator only (no state change). + +**> quantum_barrier circuit=`self`** + +## measure + + `qubits`=None + +Mark computational-basis readout (`None` / empty = all qubits). Affects which bits `run` reports. + +**> quantum_measure circuit=`self` qubits=`qubits`** + +## append + + `op` + +Append another circuit's ops or a `{gate,qubits}` op map. + +**> quantum_append circuit=`self` op=`op`** + +## noise + + `kind` + + `p` + +Teaching noise for `run` trajectories (`bitflip` / `depolarizing`). Ignored by `simulate` / `probabilities`. + +**> quantum_noise circuit=`self` kind=`kind` p=`p`** + ## simulate -Return state vector amplitudes `{re,im}`. +Return state vector amplitudes `{re,im}` (ideal; no noise). **> quantum_simulate circuit=`self`** +## state + +Ideal state vector (same amplitudes as `simulate`). + +**> quantum_state circuit=`self`** + ## probabilities -Return map of basis label → probability (qubit 0 = rightmost bit). +Return map of basis label → probability (qubit 0 = rightmost bit). Ideal; ignores noise. **> quantum_probabilities circuit=`self`** @@ -114,7 +148,7 @@ Return map of basis label → probability (qubit 0 = rightmost bit). + `shots`=1024 + `seed`=1 -Sample computational-basis shots (deterministic with `seed=`). +Sample computational-basis shots (deterministic with `seed=`). Applies circuit `noise` if set. **> quantum_run circuit=`self` shots=`shots` seed=`seed`** diff --git a/ext/quantum/量子.mq.md b/ext/quantum/量子.mq.md index 1d7ed12..9e98fef 100644 --- a/ext/quantum/量子.mq.md +++ b/ext/quantum/量子.mq.md @@ -98,13 +98,49 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。 **> quantum_swap circuit=`self` a=`比特甲` b=`比特乙`** +## 屏障 + +仅可视化分隔(不改态)。 + +**> quantum_barrier circuit=`self`** + +## 测量 + + `比特`=None + +标记计算基读出(空 = 全部比特)。影响 `运行` 报告哪些位。 + +**> quantum_measure circuit=`self` qubits=`比特`** + +## 追加 + + `操作` + +追加另一电路的 ops,或 `{gate,qubits}` 操作表。 + +**> quantum_append circuit=`self` op=`操作`** + +## 噪声 + + `种类` + + `概率` + +教学噪声,供 `运行` 轨迹使用(`bitflip` / `depolarizing` 或中文名)。`模拟` / `概率` 忽略。 + +**> quantum_noise circuit=`self` kind=`种类` p=`概率`** + ## 模拟 +返回态矢量振幅 `{re,im}`(理想;无噪声)。 + **> quantum_simulate circuit=`self`** +## 态 + +理想态矢量(与 `模拟` 相同振幅)。 + +**> quantum_state circuit=`self`** + ## 概率 -基矢标签 → 概率(qubit 0 为最右侧比特)。 +基矢标签 → 概率(qubit 0 为最右侧比特)。理想;忽略噪声。 **> quantum_probabilities circuit=`self`** @@ -112,7 +148,7 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。 + `次数`=1024 + `种子`=1 -计算基采样(`种子=` 可复现)。 +计算基采样(`种子=` 可复现)。若设置了电路噪声则启用。 **> quantum_run circuit=`self` shots=`次数` seed=`种子`** diff --git a/plugins/quantum/src/draw.rs b/plugins/quantum/src/draw.rs index c4b0a42..196f1af 100644 --- a/plugins/quantum/src/draw.rs +++ b/plugins/quantum/src/draw.rs @@ -79,6 +79,19 @@ pub fn circuit_svg(circuit: &Value) -> Result { for (col, op) in ops.iter().enumerate() { let x = x_of(col); match op.gate.as_str() { + "BARRIER" => { + draw_barrier(&mut body, x, qubits); + } + "MEASURE" | "M" => { + let qs = if op.qubits.is_empty() { + (0..qubits).collect::>() + } else { + op.qubits.clone() + }; + for q in qs { + draw_measure(&mut body, x, q); + } + } "CX" | "CNOT" | "CN" if op.qubits.len() >= 2 => { draw_cx(&mut body, x, op.qubits[0], op.qubits[1]); } @@ -119,6 +132,38 @@ fn draw_box(out: &mut String, x: f64, q: usize, label: &str) { )); } +fn draw_barrier(out: &mut String, x: f64, qubits: usize) { + let y0 = y_of(0) - 14.0; + let y1 = y_of(qubits.saturating_sub(1)) + 14.0; + out.push_str(&format!( + r#""# + )); +} + +fn draw_measure(out: &mut String, x: f64, q: usize) { + let y = y_of(q); + let w = 28.0; + let h = 28.0; + out.push_str(&format!( + r#""#, + rx = x - w / 2.0, + ry = y - h / 2.0, + )); + // meter arc + dial + out.push_str(&format!( + r#""#, + x0 = x - 8.0, + y0 = y + 2.0, + x1 = x + 8.0, + )); + out.push_str(&format!( + r#""#, + y1 = y + 2.0, + x2 = x + 6.0, + y2 = y - 6.0, + )); +} + fn draw_cx(out: &mut String, x: f64, control: usize, target: usize) { let yc = y_of(control); let yt = y_of(target); diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs index ee92f5d..e74282b 100644 --- a/plugins/quantum/src/lib.rs +++ b/plugins/quantum/src/lib.rs @@ -343,6 +343,77 @@ q_ffi!(quantum_run, |args: &Value| { sim::run_circuit(c, shots, seed) }); +q_ffi!(quantum_barrier, |args: &Value| { + let c = circuit_of(args)?; + sim::push_op(c, "BARRIER", vec![], None) +}); + +q_ffi!(quantum_measure, |args: &Value| { + let c = circuit_of(args)?; + let qs = match args.get("qubits").or_else(|| args.get("比特")) { + None | Some(Value::Null) => vec![], + Some(Value::Array(a)) => a + .iter() + .map(|v| { + v.as_u64() + .or_else(|| v.as_i64().map(|i| i as u64)) + .ok_or_else(|| "bad qubit".to_string()) + .map(|u| u as usize) + }) + .collect::, _>>()?, + Some(Value::Number(n)) => { + vec![n.as_u64().or_else(|| n.as_i64().map(|i| i as u64)).unwrap() as usize] + } + Some(Value::String(s)) => { + if s.trim().is_empty() { + vec![] + } else { + s.split(|c| c == ',' || c == ' ' || c == ',') + .filter(|t| !t.is_empty()) + .map(|t| { + t.trim() + .parse::() + .map_err(|_| format!("bad qubit `{t}`")) + }) + .collect::, _>>()? + } + } + _ => return Err("bad qubits for measure".into()), + }; + sim::push_op(c, "MEASURE", qs, None) +}); + +q_ffi!(quantum_append, |args: &Value| { + let c = circuit_of(args)?; + let op = args + .get("op") + .or_else(|| args.get("操作")) + .ok_or_else(|| "append needs `op`".to_string())?; + sim::append(c, op) +}); + +q_ffi!(quantum_noise, |args: &Value| { + let c = circuit_of(args)?; + let kind = args + .get("kind") + .or_else(|| args.get("种类")) + .and_then(|v| v.as_str()) + .ok_or_else(|| "noise needs `kind`".to_string())?; + let p = arg_f(args, "p").or_else(|_| arg_f(args, "概率"))?; + sim::set_noise(c, kind, p) +}); + +q_ffi!(quantum_state, |args: &Value| { + let c = circuit_of(args)?; + let (qubits, amps) = sim::simulate_circuit(c)?; + Ok(json!({ + "_type": "quantum_state", + "qubits": qubits, + "dim": amps.len(), + "amplitudes": sim::amps_to_json(&s), + })) +}); + q_ffi!(quantum_draw_circuit, |args: &Value| { let c = circuit_of(args)?; let kind = args @@ -552,6 +623,15 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int quantum_probabilities as PluginFn, ), ("quantum_run", "circuit,shots,seed", quantum_run as PluginFn), + ("quantum_barrier", "circuit", quantum_barrier as PluginFn), + ( + "quantum_measure", + "circuit,qubits", + quantum_measure as PluginFn, + ), + ("quantum_append", "circuit,op", quantum_append as PluginFn), + ("quantum_noise", "circuit,kind,p", quantum_noise as PluginFn), + ("quantum_state", "circuit", quantum_state as PluginFn), ( "quantum_draw_circuit", "circuit,path,kind,qubit", diff --git a/plugins/quantum/src/sim.rs b/plugins/quantum/src/sim.rs index 2a2582b..9c68e35 100644 --- a/plugins/quantum/src/sim.rs +++ b/plugins/quantum/src/sim.rs @@ -320,11 +320,20 @@ pub fn parse_ops(circuit: &Value) -> Result, String> { let u = n.as_u64().or_else(|| n.as_i64().map(|i| i as u64)).unwrap() as usize; vec![u] } - Some(Value::String(s)) => parse_qubit_list(s)?, - _ => { - if let Some(q) = row + Some(Value::String(s)) => { + let t = s.trim(); + if t.is_empty() { + vec![] + } else { + parse_qubit_list(s)? + } + } + Some(Value::Null) => vec![], + None => { + if is_meta_gate(&gate) { + vec![] + } else if let Some(q) = row .get("qubit") - .or_else(|| row.get("比特")) .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) { vec![q as usize] @@ -341,6 +350,7 @@ pub fn parse_ops(circuit: &Value) -> Result, String> { return Err(format!("op `{gate}` missing qubits")); } } + _ => return Err(format!("op `{gate}` bad qubits")), }; let theta = row .get("theta") @@ -370,74 +380,177 @@ pub fn apply_op(amps: &mut [C], qubits: usize, op: &Op) -> Result<(), String> { } } match op.gate.as_str() { + "BARRIER" | "MEASURE" | "M" => Ok(()), "I" | "ID" | "IDENTITY" => { let q = *op.qubits.first().ok_or("I needs qubit")?; apply_i(amps, q); + Ok(()) } "X" | "NOT" => { let q = *op.qubits.first().ok_or("X needs qubit")?; apply_x(amps, q); + Ok(()) } "Y" => { let q = *op.qubits.first().ok_or("Y needs qubit")?; apply_y(amps, q); + Ok(()) } "Z" => { let q = *op.qubits.first().ok_or("Z needs qubit")?; apply_z(amps, q); + Ok(()) } "S" => { let q = *op.qubits.first().ok_or("S needs qubit")?; apply_s(amps, q); + Ok(()) } "T" => { let q = *op.qubits.first().ok_or("T needs qubit")?; apply_t(amps, q); + Ok(()) } "H" | "HADAMARD" => { let q = *op.qubits.first().ok_or("H needs qubit")?; apply_h(amps, q); + Ok(()) } "RX" => { let q = *op.qubits.first().ok_or("Rx needs qubit")?; let th = op.theta.ok_or("Rx needs theta")?; apply_rx(amps, q, th); + Ok(()) } "RY" => { let q = *op.qubits.first().ok_or("Ry needs qubit")?; let th = op.theta.ok_or("Ry needs theta")?; apply_ry(amps, q, th); + Ok(()) } "RZ" => { let q = *op.qubits.first().ok_or("Rz needs qubit")?; let th = op.theta.ok_or("Rz needs theta")?; apply_rz(amps, q, th); + Ok(()) } "CX" | "CNOT" | "CN" => { if op.qubits.len() < 2 { return Err("CX needs control and target".into()); } apply_cx(amps, op.qubits[0], op.qubits[1]); + Ok(()) } "CZ" => { if op.qubits.len() < 2 { return Err("CZ needs control and target".into()); } apply_cz(amps, op.qubits[0], op.qubits[1]); + Ok(()) } "SWAP" => { if op.qubits.len() < 2 { return Err("SWAP needs two qubits".into()); } apply_swap(amps, op.qubits[0], op.qubits[1]); + Ok(()) } + other => Err(format!( + "unsupported gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP/BARRIER/MEASURE)" + )), + } +} + +pub fn is_meta_gate(gate: &str) -> bool { + matches!( + gate.to_ascii_uppercase().as_str(), + "BARRIER" | "MEASURE" | "M" + ) +} + +pub fn is_unitary_op(op: &Op) -> bool { + !is_meta_gate(&op.gate) +} + +#[derive(Clone, Debug)] +pub struct NoiseSpec { + pub kind: String, // bitflip | depolarizing + pub p: f64, +} + +pub fn parse_noise(circuit: &Value) -> Result, String> { + let kind = circuit + .get("noise_kind") + .or_else(|| circuit.get("噪声种类")) + .and_then(|v| v.as_str()) + .map(|s| s.to_ascii_lowercase()); + let p = circuit + .get("noise_p") + .or_else(|| circuit.get("噪声概率")) + .and_then(|v| v.as_f64()); + match (kind, p) { + (None, None) => Ok(None), + (Some(k), Some(p)) => { + if !(0.0..=1.0).contains(&p) { + return Err("noise p must be in [0,1]".into()); + } + let kind = match k.as_str() { + "bitflip" | "bit_flip" | "比特翻转" => "bitflip".into(), + "depolarizing" | "depolarise" | "退极化" => "depolarizing".into(), + other => { + return Err(format!( + "unknown noise kind `{other}` (bitflip|depolarizing)" + )); + } + }; + Ok(Some(NoiseSpec { kind, p })) + } + _ => Err("noise needs both kind and p".into()), + } +} + +pub fn set_noise(circuit: &Value, kind: &str, p: f64) -> Result { + if !(0.0..=1.0).contains(&p) { + return Err("noise p must be in [0,1]".into()); + } + let k = match kind.trim().to_ascii_lowercase().as_str() { + "bitflip" | "bit_flip" | "比特翻转" => "bitflip", + "depolarizing" | "depolarise" | "退极化" => "depolarizing", other => { return Err(format!( - "unsupported gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP)" + "unknown noise kind `{other}` (bitflip|depolarizing)" )); } + }; + let mut obj = circuit.as_object().cloned().unwrap_or_default(); + obj.insert("noise_kind".into(), json!(k)); + obj.insert("noise_p".into(), json!(p)); + Ok(Value::Object(obj)) +} + +/// Qubits to read out: union of MEASURE ops; empty MEASURE list = all qubits; no MEASURE = all. +pub fn measure_targets(ops: &[Op], n: usize) -> Vec { + let mut measured = Vec::new(); + let mut any = false; + for op in ops { + let g = op.gate.to_ascii_uppercase(); + if g == "MEASURE" || g == "M" { + any = true; + if op.qubits.is_empty() { + return (0..n).collect(); + } + for &q in &op.qubits { + if !measured.contains(&q) { + measured.push(q); + } + } + } } - Ok(()) + if !any { + return (0..n).collect(); + } + measured.sort_unstable(); + measured } struct Rng { @@ -447,7 +560,11 @@ struct Rng { impl Rng { fn new(seed: u64) -> Self { Self { - state: if seed == 0 { 0x9e37_79b9_7f4a_7c15 } else { seed }, + state: if seed == 0 { + 0x9e37_79b9_7f4a_7c15 + } else { + seed + }, } } fn next_u64(&mut self) -> u64 { @@ -463,8 +580,33 @@ impl Rng { } } -/// Sample computational-basis shots; returns counts map. -pub fn sample_counts(amps: &[C], qubits: usize, shots: usize, seed: u64) -> Map { +fn apply_noise_on_qubits( + amps: &mut [C], + qs: &[usize], + noise: &NoiseSpec, + rng: &mut Rng, +) { + if noise.p <= 0.0 { + return; + } + for &q in qs { + if rng.next_f64() >= noise.p { + continue; + } + match noise.kind.as_str() { + "bitflip" => apply_x(amps, q), + "depolarizing" => match rng.next_u64() % 3 { + 0 => apply_x(amps, q), + 1 => apply_y(amps, q), + _ => apply_z(amps, q), + }, + _ => {} + } + } +} + +fn sample_label(amps: &[C], n: usize, targets: &[usize], rng: &mut Rng) -> String { + // Build CDF over full basis, then project bits onto targets (ascending, LSB = targets[0]). let mut cdf = Vec::with_capacity(amps.len()); let mut acc = 0.0; for a in amps { @@ -472,31 +614,41 @@ pub fn sample_counts(amps: &[C], qubits: usize, shots: usize, seed: u64) -> Map< cdf.push(acc); } if acc <= 0.0 { - return Map::new(); + return "0".repeat(targets.len().max(1)); } - // normalize cdf tail to 1 let inv = 1.0 / acc; for x in &mut cdf { *x *= inv; } + let r = rng.next_f64(); + let mut idx = 0usize; + for (i, &c) in cdf.iter().enumerate() { + if r <= c { + idx = i; + break; + } + idx = i; + } + if targets.len() == n { + return basis_label(idx, n); + } + let mut bits = String::with_capacity(targets.len()); + // label: targets[0] is rightmost (LSB of the label string) + for &q in targets.iter().rev() { + bits.push(if bit(idx, q) { '1' } else { '0' }); + } + bits +} + +/// Sample computational-basis shots; returns counts map. +#[allow(dead_code)] +pub fn sample_counts(amps: &[C], qubits: usize, shots: usize, seed: u64) -> Map { + let targets: Vec = (0..qubits).collect(); let mut counts: Map = Map::new(); let mut rng = Rng::new(seed); for _ in 0..shots { - let r = rng.next_f64(); - let mut idx = 0usize; - for (i, &c) in cdf.iter().enumerate() { - if r <= c { - idx = i; - break; - } - idx = i; - } - let label = basis_label(idx, qubits); - let n = counts - .get(&label) - .and_then(|v| v.as_u64()) - .unwrap_or(0) - + 1; + let label = sample_label(amps, qubits, &targets, &mut rng); + let n = counts.get(&label).and_then(|v| v.as_u64()).unwrap_or(0) + 1; counts.insert(label, json!(n)); } counts @@ -506,14 +658,51 @@ pub fn run_circuit(circuit: &Value, shots: usize, seed: u64) -> Result= 1".into()); } - let (qubits, amps) = simulate_circuit(circuit)?; - let counts = sample_counts(&s, qubits, shots, seed); - Ok(json!({ + let qubits = circuit + .get("qubits") + .or_else(|| circuit.get("比特数")) + .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) + .ok_or_else(|| "circuit missing qubits".to_string())? as usize; + check_qubits(qubits)?; + let ops = parse_ops(circuit)?; + let noise = parse_noise(circuit)?; + let targets = measure_targets(&ops, qubits); + let mut counts: Map = Map::new(); + let mut rng = Rng::new(seed); + + for _ in 0..shots { + let mut amps = zero_state(qubits); + for op in &ops { + if !is_unitary_op(op) { + continue; + } + apply_op(&mut amps, qubits, op)?; + if let Some(ref nspec) = noise { + if nspec.p > 0.0 { + apply_noise_on_qubits(&mut amps, &op.qubits, nspec, &mut rng); + } + } + } + renormalize(&mut amps); + let label = sample_label(&s, qubits, &targets, &mut rng); + let c = counts.get(&label).and_then(|v| v.as_u64()).unwrap_or(0) + 1; + counts.insert(label, json!(c)); + } + + let mut out = json!({ "qubits": qubits, "shots": shots, "seed": seed, "counts": counts, - })) + "measure": targets, + }); + if let Some(nspec) = noise { + out.as_object_mut().unwrap().insert( + "noise".into(), + json!({ "kind": nspec.kind, "p": nspec.p }), + ); + } + Ok(out) } pub fn simulate_circuit(circuit: &Value) -> Result<(usize, Vec), String> { @@ -650,12 +839,17 @@ fn op_from_step_row(row: &Value) -> Result { .and_then(|v| v.as_str()) .ok_or_else(|| "step row missing `gate` / `门`".to_string())? .to_ascii_uppercase(); - let qs = row + let qubits = match row .get("qubits") .or_else(|| row.get("qubit")) .or_else(|| row.get("比特")) - .ok_or_else(|| "step row missing `qubits` / `比特`".to_string())?; - let qubits = qubits_from_cell(qs)?; + { + None if is_meta_gate(&gate) => vec![], + None => { + return Err("step row missing `qubits` / `比特`".into()); + } + Some(v) => qubits_from_cell(v)?, + }; let theta = row .get("theta") .or_else(|| row.get("参数")) @@ -672,6 +866,7 @@ fn op_from_step_row(row: &Value) -> Result { fn qubits_from_cell(v: &Value) -> Result, String> { match v { + Value::Null => Ok(vec![]), Value::Array(a) => a .iter() .map(|x| { @@ -688,7 +883,13 @@ fn qubits_from_cell(v: &Value) -> Result, String> { .ok_or_else(|| "bad qubit index".to_string())? as usize; Ok(vec![u]) } - Value::String(s) => parse_qubit_list(s), + Value::String(s) => { + if s.trim().is_empty() { + Ok(vec![]) + } else { + parse_qubit_list(s) + } + } _ => Err("bad qubits cell".into()), } } @@ -743,11 +944,19 @@ pub fn push_op(circuit: &Value, gate: &str, qubits: Vec, theta: Option= n { - return Err(format!("qubit {q} out of range for n={n}")); + let g = gate.to_ascii_uppercase(); + if !is_meta_gate(&g) || !qubits.is_empty() { + for &q in &qubits { + if q >= n { + return Err(format!("qubit {q} out of range for n={n}")); + } } } + if is_meta_gate(&g) { + // ok with empty qubits (barrier / measure-all) + } else if qubits.is_empty() { + return Err(format!("gate `{g}` needs qubits")); + } let mut obj = circuit.as_object().cloned().unwrap_or_default(); let mut ops = obj .get("ops") @@ -755,7 +964,7 @@ pub fn push_op(circuit: &Value, gate: &str, qubits: Vec, theta: Option, theta: Option Result { + let n = circuit + .get("qubits") + .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) + .ok_or_else(|| "circuit missing qubits".to_string())? as usize; + let mut obj = circuit.as_object().cloned().unwrap_or_default(); + let mut ops = obj + .get("ops") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + + if let Some(arr) = op.get("ops").and_then(|v| v.as_array()) { + let other_n = op + .get("qubits") + .and_then(|v| v.as_u64()) + .unwrap_or(n as u64) as usize; + if other_n > n { + return Err(format!( + "append: other circuit qubits={other_n} exceeds this n={n}" + )); + } + for row in arr { + ops.push(row.clone()); + } + } else if op.get("gate").or_else(|| op.get("门")).is_some() { + let parsed = parse_ops(&json!({ "ops": [op] }))?; + for p in parsed { + for &q in &p.qubits { + if q >= n { + return Err(format!("append qubit {q} out of range for n={n}")); + } + } + let mut row = json!({ "gate": p.gate, "qubits": p.qubits }); + if let Some(t) = p.theta { + row.as_object_mut() + .unwrap() + .insert("theta".into(), json!(t)); + } + ops.push(row); + } + } else if op.get("name").or_else(|| op.get("名")).is_some() { + return Err("append gate handle needs an op with qubits; pass a circuit or {{gate,qubits}}".into()); + } else { + return Err("append needs a circuit (ops) or op {{gate,qubits}}".into()); + } + + 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 { diff --git a/public/features/05-extensions.mq.md b/public/features/05-extensions.mq.md index 82740a7..1be312c 100644 --- a/public/features/05-extensions.mq.md +++ b/public/features/05-extensions.mq.md @@ -9,7 +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 +- ext/quantum — state-vector circuits, `steps=` tables, `draw kind=circuit|probs|bloch`, named `gate` + `matches_matrix`, teaching `noise`, `barrier`/`measure`/`append`/`state`. Design: doc/design/ext-quantum.md · Q5: doc/design/ext-quantum-q5.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 diff --git a/public/features/05-扩展.mq.md b/public/features/05-扩展.mq.md index d66f629..689ba01 100644 --- a/public/features/05-扩展.mq.md +++ b/public/features/05-扩展.mq.md @@ -9,7 +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 +- ext/quantum(ext/量子)— 态向量电路、`步骤=` 表、`绘图 种类=circuit|probs|bloch`、具名「门」与「匹配矩阵」、教学「噪声」、`屏障`/`测量`/`追加`/`态`。设计:doc/design/ext-quantum.md · Q5:doc/design/ext-quantum-q5.md - 安装器:marqdo ext list / add / remove — doc/design/ext-cli.md - 通用原生插件:lib/plugin + include/marqdo_abi.h — doc/design/ext-abi.md diff --git a/tests/ext/quantum-author-api-smoke.mq.md b/tests/ext/quantum-author-api-smoke.mq.md new file mode 100644 index 0000000..d4a32ed --- /dev/null +++ b/tests/ext/quantum-author-api-smoke.mq.md @@ -0,0 +1,37 @@ +--- +title: quantum author API smoke +description: barrier, measure, append, state, draw meters. +> ext/quantum/quantum.mq.md +--- + +# main + +*`qc` = > quantum.circuit qubits=2 * +*`qc` = > `qc`.h qubit=0 * +*`qc` = > `qc`.barrier * +*`qc` = > `qc`.cx control=0 target=1 * +*`qc` = > `qc`.measure * + +*`st` = > `qc`.state * +*`dim` = `st`[^dim] * +1. `dim` == 4 + > print text=state-ok +2. * + > print text=state-fail + +*`img` = > `qc`.draw path=quantum-author-draw.svg * +*`kind` = `img`[^kind] * +1. `kind` == circuit + > print text=draw-ok +2. * + > print text=draw-fail + +*`other` = > quantum.circuit qubits=2 * +*`other` = > `other`.x qubit=1 * +*`qc2` = > `qc`.append op=`other` * +*`ops` = `qc2`[^ops] * +*`n` = > len `ops` * +1. `n` == 5 + > print text=append-ok +2. * + > print text=append-fail diff --git a/tests/ext/quantum-noise-smoke.mq.md b/tests/ext/quantum-noise-smoke.mq.md new file mode 100644 index 0000000..151d932 --- /dev/null +++ b/tests/ext/quantum-noise-smoke.mq.md @@ -0,0 +1,18 @@ +--- +title: quantum noise smoke +description: bitflip p=1 after I flips |0> to |1| for all shots. +> ext/quantum/quantum.mq.md +--- + +# main + +*`qc` = > quantum.circuit qubits=1 * +*`qc` = > `qc`.i qubit=0 * +*`qc` = > `qc`.noise kind=bitflip p=1 * +*`r` = > `qc`.run shots=32 seed=3 * +*`c1` = `r`[^counts][^1] * + +1. `c1` == 32 + > print text=noise-ok +2. * + > print text=noise-fail diff --git a/tests/gold.rs b/tests/gold.rs index dfa4c6d..c02829b 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1526,6 +1526,38 @@ fn ext_quantum_gate_matrix_smoke() { ); } +#[test] +fn ext_quantum_author_api_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-author-api-smoke.mq.md", + "state-ok\ndraw-ok\nappend-ok", + ); + let svg_path = "tests/ext/quantum-author-draw.svg"; + let svg = std::fs::read_to_string(svg_path).unwrap_or_default(); + assert!( + svg.contains("