diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md index 2a9a3b3..1407d39 100644 --- a/doc/design/ext-quantum.md +++ b/doc/design/ext-quantum.md @@ -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 含 ` 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` diff --git a/ext/quantum/quantum.mq.md b/ext/quantum/quantum.mq.md index 5c7de39..033cea2 100644 --- a/ext/quantum/quantum.mq.md +++ b/ext/quantum/quantum.mq.md @@ -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`** diff --git a/ext/quantum/量子.mq.md b/ext/quantum/量子.mq.md index de4ffef..1d7ed12 100644 --- a/ext/quantum/量子.mq.md +++ b/ext/quantum/量子.mq.md @@ -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=`路径`** diff --git a/plugins/quantum/src/draw.rs b/plugins/quantum/src/draw.rs index 0a748c7..c4b0a42 100644 --- a/plugins/quantum/src/draw.rs +++ b/plugins/quantum/src/draw.rs @@ -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 { + 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#""#, + x0 = pad_l - 4.0, + x1 = width - pad_r, + y = pad_t + chart_h, + )); + body.push_str(&format!( + r#""#, + x = pad_l - 4.0, + y0 = pad_t, + y1 = pad_t + chart_h, + )); + body.push_str(&format!( + r#"1"#, + ty = pad_t + 4.0, + )); + body.push_str(&format!( + r#"0"#, + 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#""#, + x = x, + y = y, + bar_w = bar_w, + h = h, + bar_fill = bar_fill, + STROKE = STROKE, + )); + body.push_str(&format!( + r#"{lab}"#, + cx = x + bar_w / 2.0, + ty = pad_t + chart_h + 16.0, + lab = esc(label), + STROKE = STROKE, + )); + body.push_str(&format!( + r#"{pval:.2}"#, + cx = x + bar_w / 2.0, + ty = y - 4.0, + pval = p, + muted = muted, + )); + } + format!( + r#"{body}"#, + 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#""#, + 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#""#, + x1 = x1, + y1 = y1, + x2 = x2, + y2 = y2, + axis = "#888", + )); + body.push_str(&format!( + r#"{lab}"#, + 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#""#, + ox = ox, + oy = oy, + sx = sx, + sy = sy, + arrow = arrow, + )); + body.push_str(&format!( + r#""#, + sx = sx, + sy = sy, + arrow = arrow, + )); + body.push_str(&format!( + r#"⟨X⟩={bx:.3} ⟨Y⟩={by:.3} ⟨Z⟩={bz:.3}"#, + hy = height - 12.0, + bx = x, + by = y, + bz = z, + STROKE = STROKE, + )); + format!( + r#"{body}"#, + 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#"{label}"#, + w = width, + h = height, + label = label, + BOX = BOX, + STROKE = STROKE, + ) +} diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs index 2348505..ee92f5d 100644 --- a/plugins/quantum/src/lib.rs +++ b/plugins/quantum/src/lib.rs @@ -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(&s, qubits); + ("probs", draw::probs_svg(&probs)) + } + "bloch" | "布洛赫" => { + let (qubits, amps) = sim::simulate_circuit(c)?; + let (x, y, z) = sim::bloch_vector(&s, qubits, qubit)?; + ("bloch", draw::bloch_svg(x, y, z)) + } + 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 { diff --git a/plugins/quantum/src/sim.rs b/plugins/quantum/src/sim.rs index 73a052c..2a2582b 100644 --- a/plugins/quantum/src/sim.rs +++ b/plugins/quantum/src/sim.rs @@ -765,3 +765,277 @@ pub fn push_op(circuit: &Value, gate: &str, qubits: Vec, theta: Option 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) -> Result>, 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]) -> 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 { + 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>, 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> = 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], b: &[Vec], 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) -> Result { + 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(&s, 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)); + } +} diff --git a/public/features/05-extensions.mq.md b/public/features/05-extensions.mq.md index ffb046c..82740a7 100644 --- a/public/features/05-extensions.mq.md +++ b/public/features/05-extensions.mq.md @@ -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 diff --git a/public/features/05-扩展.mq.md b/public/features/05-扩展.mq.md index ab9d759..d66f629 100644 --- a/public/features/05-扩展.mq.md +++ b/public/features/05-扩展.mq.md @@ -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 diff --git a/public/features/06-quantum.mq.md b/public/features/06-quantum.mq.md new file mode 100644 index 0000000..4cd4633 --- /dev/null +++ b/public/features/06-quantum.mq.md @@ -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 diff --git a/public/features/06-量子.mq.md b/public/features/06-量子.mq.md new file mode 100644 index 0000000..cd7e36c --- /dev/null +++ b/public/features/06-量子.mq.md @@ -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 diff --git a/src/interp.rs b/src/interp.rs index 40ff2da..4c254ce 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -517,7 +517,8 @@ impl Interpreter { call: &CallExpr, ) -> Result { 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, diff --git a/src/view/html.rs b/src/view/html.rs index 3c7715f..81da1bd 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -1839,8 +1839,13 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM ( "pending", "input", - "Fill preset input, then Run with input — output streams in the panel (no page reload)." - .to_string(), + if vm.show_stream { + "Fill preset input, then Run with input — output streams in the panel (no page reload)." + .to_string() + } else { + "Fill preset input, then Run with input." + .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#"
+ LinkMode::Live if vm.show_stream => r#"
Stream @@ -1962,7 +1967,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
"# .to_string(), - LinkMode::Static { .. } => String::new(), + _ => String::new(), }; let main = format!( r#" diff --git a/src/view/mod.rs b/src/view/mod.rs index 54c2dad..e482244 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -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), }) diff --git a/src/view/render.rs b/src/view/render.rs index fc2baf5..7aec60b 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -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, /// HTML for Variables panel (entry bindings after run). @@ -54,6 +56,28 @@ pub fn collect_input_prompts(module: &Module) -> Vec { 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) { 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)); + } } diff --git a/tests/ext/quantum-draw-smoke.mq.md b/tests/ext/quantum-draw-smoke.mq.md new file mode 100644 index 0000000..68d202f --- /dev/null +++ b/tests/ext/quantum-draw-smoke.mq.md @@ -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 diff --git a/tests/ext/quantum-gate-matrix-smoke.mq.md b/tests/ext/quantum-gate-matrix-smoke.mq.md new file mode 100644 index 0000000..6491391 --- /dev/null +++ b/tests/ext/quantum-gate-matrix-smoke.mq.md @@ -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 diff --git a/tests/gold.rs b/tests/gold.rs index 4b78d99..dfa4c6d 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -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("