From 4a7a33e29a87d26000db75941c5b3193cd316e04 Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 12 Aug 2026 10:24:33 +0800 Subject: [PATCH] =?UTF-8?q?Add=20ext/quantum=20Q0=E2=80=93Q1:=20ABI=20simu?= =?UTF-8?q?lator=20with=20H/CX=20and=20Bell=20smoke.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Register the quantum catalog package, English/Chinese circuit APIs, and a state-vector plugin that verifies Bell-state probabilities. Co-authored-by: Cursor --- Cargo.toml | 2 +- doc/design/ext-cli.md | 2 +- doc/design/ext-quantum.md | 2 +- doc/roadmap/ext-quantum.md | 6 +- ext/quantum/quantum.mq.md | 60 ++++++ ext/quantum/量子.mq.md | 58 ++++++ plugins/quantum/Cargo.toml | 15 ++ plugins/quantum/src/lib.rs | 267 ++++++++++++++++++++++++ plugins/quantum/src/sim.rs | 324 +++++++++++++++++++++++++++++ src/ext_cli.rs | 14 +- tests/ext/quantum-bell-smoke.mq.md | 42 ++++ tests/gold.rs | 16 ++ 12 files changed, 799 insertions(+), 9 deletions(-) create mode 100644 ext/quantum/quantum.mq.md create mode 100644 ext/quantum/量子.mq.md create mode 100644 plugins/quantum/Cargo.toml create mode 100644 plugins/quantum/src/lib.rs create mode 100644 plugins/quantum/src/sim.rs create mode 100644 tests/ext/quantum-bell-smoke.mq.md diff --git a/Cargo.toml b/Cargo.toml index 00a1233..d10a5c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ include_dir = "0.7" libc = "0.2" [workspace] -members = ["plugins/demo", "plugins/agent", "plugins/web"] +members = ["plugins/demo", "plugins/agent", "plugins/web", "plugins/quantum"] resolver = "2" [dev-dependencies] diff --git a/doc/design/ext-cli.md b/doc/design/ext-cli.md index 4a4b0a8..d9b0f85 100644 --- a/doc/design/ext-cli.md +++ b/doc/design/ext-cli.md @@ -50,7 +50,7 @@ Future optional ext domains get their own subdirs (e.g. `ext/web/`, `ext/quantum | `llm` | `ai/llm.mq.md`, `ai/大模型.mq.md` | | `agent` | `ai/agent.mq.md`, `ai/智能体.mq.md`, **`native/libagent.so`** (or `.dylib`) | | `web` | `web/web.mq.md`, `web/网页.mq.md`, **`native/libweb.so`** — 见 [ext-web.md](ext-web.md) · [roadmap](../roadmap/ext-web.md) | -| `quantum`(规划) | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **`native/libquantum.so`** — 见 [ext-quantum.md](ext-quantum.md) · [roadmap](../roadmap/ext-quantum.md) | +| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **`native/libquantum.so`** — 见 [ext-quantum.md](ext-quantum.md) · [roadmap](../roadmap/ext-quantum.md) | `add agent` copies the built native plugin into `MARQDO_EXT/native/`. Build it first: diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md index 5c5a13c..697ca0e 100644 --- a/doc/design/ext-quantum.md +++ b/doc/design/ext-quantum.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Accepted · 待实现**(作者面与分期已锁定;实现未开工) | +| 状态 | **Accepted · 实现中**(Q0–Q1:电路 + H/CX + 概率;Q2+ 见路线图) | | 日期 | 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` / `量子`) | diff --git a/doc/roadmap/ext-quantum.md b/doc/roadmap/ext-quantum.md index 42f69c2..845b7fe 100644 --- a/doc/roadmap/ext-quantum.md +++ b/doc/roadmap/ext-quantum.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Q0 未开工**(设计已 Accepted) | +| 状态 | **Q0–Q1 落地中**(设计 Accepted) | | 日期 | 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) | @@ -22,8 +22,8 @@ | 阶段 | 内容 | 状态 | |------|------|------| -| **Q0** | CATALOG + `plugins/quantum` ping + L1 `ensure_plugin` | pending | -| **Q1** | 态向量;I/X/H/CX;`simulate` / `probabilities`;贝尔态 gold | pending | +| **Q0** | CATALOG + `plugins/quantum` ping + L1 `ensure_plugin` | **done** | +| **Q1** | 态向量;I/X/H/CX;`simulate` / `probabilities`;贝尔态 gold | **done** | | **Q2** | Y/Z/S/T/R\* /CZ/SWAP;`run seed=`;中英 API | pending | | **Q3** | `steps=` 电路表;`draw` 轨线 SVG;view `record_plot` 或值识别 | pending | | **Q4** | 概率条 / 布洛赫;`matches_matrix`;examples + 用户文档 | pending | diff --git a/ext/quantum/quantum.mq.md b/ext/quantum/quantum.mq.md new file mode 100644 index 0000000..4da61c9 --- /dev/null +++ b/ext/quantum/quantum.mq.md @@ -0,0 +1,60 @@ +--- +title: ext/quantum/quantum +description: Official quantum circuit simulator (English). Gates + circuits; ABI plugin. +> lib/plugin.mq.md +> lib/sys.mq.md +> lib/json.mq.md +--- + +## ensure_plugin + +Load the ABI v2 `quantum` plugin once. + +*`p` = > plugin.native_path name=quantum * +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum) + > sys.exit code=1 +**** + +# circuit + + `qubits`=1 + +State-vector circuit (default |0…0⟩). Methods append gates and return an updated handle. + +> ensure_plugin +**> quantum_circuit_new qubits=`qubits`** + +## h + + `qubit`=0 + +**> quantum_h circuit=`self` qubit=`qubit`** + +## x + + `qubit`=0 + +**> quantum_x circuit=`self` qubit=`qubit`** + +## i + + `qubit`=0 + +**> quantum_i circuit=`self` qubit=`qubit`** + +## cx + + `control`=0 + + `target`=1 + +**> quantum_cx circuit=`self` control=`control` target=`target`** + +## simulate + +Return state vector amplitudes `{re,im}`. + +**> quantum_simulate circuit=`self`** + +## probabilities + +Return map of basis label → probability (qubit 0 = rightmost bit). + +**> quantum_probabilities circuit=`self`** diff --git a/ext/quantum/量子.mq.md b/ext/quantum/量子.mq.md new file mode 100644 index 0000000..2fbd2f8 --- /dev/null +++ b/ext/quantum/量子.mq.md @@ -0,0 +1,58 @@ +--- +title: ext/quantum/量子 +description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。 +> lib/plugin.mq.md +> lib/sys.mq.md +> lib/json.mq.md +--- + +## 确保插件 + +加载 ABI v2 `quantum` 插件。 + +*`p` = > plugin.native_path name=quantum * +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/quantum: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum) + > sys.exit code=1 +**** + +# 电路 + + `比特数`=1 + +状态向量电路(默认 |0…0⟩)。方法追加门并返回更新后的句柄。 + +> 确保插件 +**> quantum_circuit_new qubits=`比特数`** + +## 哈达玛 + + `比特`=0 + +**> quantum_h circuit=`self` qubit=`比特`** + +## 泡利X + + `比特`=0 + +**> quantum_x circuit=`self` qubit=`比特`** + +## 单位 + + `比特`=0 + +**> quantum_i circuit=`self` qubit=`比特`** + +## 控非 + + `控制`=0 + + `目标`=1 + +**> quantum_cx circuit=`self` control=`控制` target=`目标`** + +## 模拟 + +**> quantum_simulate circuit=`self`** + +## 概率 + +基矢标签 → 概率(qubit 0 为最右侧比特)。 + +**> quantum_probabilities circuit=`self`** diff --git a/plugins/quantum/Cargo.toml b/plugins/quantum/Cargo.toml new file mode 100644 index 0000000..3495bd0 --- /dev/null +++ b/plugins/quantum/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "marqdo_plugin_quantum" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Marqdo quantum simulator plugin (ABI v2)" +publish = false + +[lib] +name = "quantum" +crate-type = ["cdylib"] + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs new file mode 100644 index 0000000..51d7b5a --- /dev/null +++ b/plugins/quantum/src/lib.rs @@ -0,0 +1,267 @@ +//! Marqdo quantum plugin (C ABI v2): state-vector circuit simulation. + +mod sim; + +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int, c_void}; +use std::ptr; + +use serde_json::{json, Value}; + +const ABI_VERSION: u32 = 2; + +type PluginFn = unsafe extern "C" fn( + args_json: *const c_char, + out_json: *mut *mut c_char, + err_msg: *mut *mut c_char, +) -> c_int; + +type HostQueryFn = unsafe extern "C" fn( + userdata: *mut c_void, + name: *const c_char, + args_json: *const c_char, + out_json: *mut *mut c_char, + err_msg: *mut *mut c_char, +) -> c_int; + +#[repr(C)] +pub struct MarqdoHostApi { + pub userdata: *mut c_void, + pub register_fn: Option< + unsafe extern "C" fn( + userdata: *mut c_void, + name: *const c_char, + params: *const c_char, + fn_ptr: PluginFn, + ) -> c_int, + >, + pub alloc: Option *mut c_void>, + pub free: Option, + pub host_query: Option, +} + +static mut HOST_FREE: Option = None; +static mut HOST_ALLOC: Option *mut c_void> = None; + +unsafe fn host_strdup(s: &str) -> *mut c_char { + let alloc = HOST_ALLOC.expect("host alloc"); + let bytes = s.as_bytes(); + let p = alloc(bytes.len() + 1) as *mut u8; + if p.is_null() { + return ptr::null_mut(); + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + *p.add(bytes.len()) = 0; + p as *mut c_char +} + +fn set_out(out: *mut *mut c_char, s: &str) { + if out.is_null() { + return; + } + unsafe { + *out = host_strdup(s); + } +} + +fn set_err(err: *mut *mut c_char, s: &str) { + if err.is_null() { + return; + } + unsafe { + *err = host_strdup(s); + } +} + +fn parse_args(args_json: *const c_char) -> Result { + if args_json.is_null() { + return Ok(json!({})); + } + let s = unsafe { CStr::from_ptr(args_json) } + .to_str() + .map_err(|_| "args not utf-8".to_string())?; + if s.trim().is_empty() { + return Ok(json!({})); + } + serde_json::from_str(s).map_err(|e| e.to_string()) +} + +fn reply(out_json: *mut *mut c_char, err_msg: *mut *mut c_char, r: Result) -> c_int { + match r { + Ok(v) => { + set_out(out_json, &v.to_string()); + 0 + } + Err(e) => { + set_err(err_msg, &e); + 1 + } + } +} + +macro_rules! q_ffi { + ($name:ident, $body:expr) => { + unsafe extern "C" fn $name( + args_json: *const c_char, + out_json: *mut *mut c_char, + err_msg: *mut *mut c_char, + ) -> c_int { + let args = match parse_args(args_json) { + Ok(v) => v, + Err(e) => { + set_err(err_msg, &format!("{}: {e}", stringify!($name))); + return 1; + } + }; + let r: Result = (|| $body(&args))(); + reply( + out_json, + err_msg, + r.map_err(|e| format!("{}: {e}", stringify!($name))), + ) + } + }; +} + +fn arg_u(v: &Value, key: &str) -> Result { + match v.get(key) { + Some(Value::Number(n)) => n + .as_u64() + .or_else(|| n.as_i64().map(|i| i as u64)) + .map(|u| u as usize) + .ok_or_else(|| format!("bad `{key}`")), + Some(Value::String(s)) => s + .trim() + .parse() + .map_err(|_| format!("bad `{key}`")), + _ => Err(format!("missing `{key}`")), + } +} + +fn circuit_of(args: &Value) -> Result<&Value, String> { + args.get("circuit") + .or_else(|| args.get("电路")) + .ok_or_else(|| "missing `circuit`".to_string()) +} + +q_ffi!(quantum_ping, |_args: &Value| { + Ok(json!({ + "ok": true, + "name": "quantum", + "abi": ABI_VERSION, + "max_qubits": sim::max_qubits(), + })) +}); + +q_ffi!(quantum_circuit_new, |args: &Value| { + let qubits = arg_u(args, "qubits").or_else(|_| arg_u(args, "比特数"))?; + sim::check_qubits(qubits)?; + Ok(json!({ + "qubits": qubits, + "ops": [], + })) +}); + +q_ffi!(quantum_h, |args: &Value| { + let c = circuit_of(args)?; + let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; + sim::push_op(c, "H", vec![q], None) +}); + +q_ffi!(quantum_x, |args: &Value| { + let c = circuit_of(args)?; + let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; + sim::push_op(c, "X", vec![q], None) +}); + +q_ffi!(quantum_i, |args: &Value| { + let c = circuit_of(args)?; + let q = arg_u(args, "qubit").or_else(|_| arg_u(args, "比特"))?; + sim::push_op(c, "I", vec![q], None) +}); + +q_ffi!(quantum_cx, |args: &Value| { + let c = circuit_of(args)?; + let control = arg_u(args, "control").or_else(|_| arg_u(args, "控制"))?; + let target = arg_u(args, "target").or_else(|_| arg_u(args, "目标"))?; + sim::push_op(c, "CX", vec![control, target], None) +}); + +q_ffi!(quantum_simulate, |args: &Value| { + let c = circuit_of(args)?; + let (qubits, amps) = sim::simulate_circuit(c)?; + Ok(json!({ + "qubits": qubits, + "dim": amps.len(), + "amplitudes": sim::amps_to_json(&s), + })) +}); + +q_ffi!(quantum_probabilities, |args: &Value| { + let c = circuit_of(args)?; + let (qubits, amps) = sim::simulate_circuit(c)?; + Ok(Value::Object(sim::probabilities(&s, qubits))) +}); + +fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int { + let register = match host.register_fn { + Some(f) => f, + None => return 1, + }; + let n = CString::new(name).unwrap(); + let p = CString::new(params).unwrap(); + unsafe { register(host.userdata, n.as_ptr(), p.as_ptr(), fn_ptr) } +} + +#[no_mangle] +pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 { + ABI_VERSION +} + +#[no_mangle] +pub unsafe extern "C" fn marqdo_plugin_shutdown() {} + +#[no_mangle] +pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int { + if host.is_null() { + return 1; + } + let host = &*host; + HOST_ALLOC = host.alloc; + HOST_FREE = host.free; + if host.host_query.is_none() { + // v2 preferred; still allow init if only register is present + } + let regs = [ + ("quantum_ping", "", quantum_ping as PluginFn), + ( + "quantum_circuit_new", + "qubits", + quantum_circuit_new as PluginFn, + ), + ("quantum_h", "circuit,qubit", quantum_h as PluginFn), + ("quantum_x", "circuit,qubit", quantum_x as PluginFn), + ("quantum_i", "circuit,qubit", quantum_i as PluginFn), + ( + "quantum_cx", + "circuit,control,target", + quantum_cx as PluginFn, + ), + ( + "quantum_simulate", + "circuit", + quantum_simulate as PluginFn, + ), + ( + "quantum_probabilities", + "circuit", + quantum_probabilities as PluginFn, + ), + ]; + for (name, params, f) in regs { + if register(host, name, params, f) != 0 { + return 1; + } + } + 0 +} diff --git a/plugins/quantum/src/sim.rs b/plugins/quantum/src/sim.rs new file mode 100644 index 0000000..18c84af --- /dev/null +++ b/plugins/quantum/src/sim.rs @@ -0,0 +1,324 @@ +//! Pure-state state-vector simulator (design §6). + +use serde_json::{json, Map, Value}; + +pub const DEFAULT_MAX_QUBITS: usize = 12; +pub const HARD_MAX_QUBITS: usize = 16; + +#[derive(Clone, Copy, Debug, Default)] +pub struct C { + pub re: f64, + pub im: f64, +} + +impl C { + pub fn new(re: f64, im: f64) -> Self { + Self { re, im } + } + pub fn zero() -> Self { + Self { re: 0.0, im: 0.0 } + } + pub fn one() -> Self { + Self { re: 1.0, im: 0.0 } + } + pub fn norm_sq(self) -> f64 { + self.re * self.re + self.im * self.im + } + pub fn mul(self, o: C) -> C { + C { + re: self.re * o.re - self.im * o.im, + im: self.re * o.im + self.im * o.re, + } + } + pub fn add(self, o: C) -> C { + C { + re: self.re + o.re, + im: self.im + o.im, + } + } + pub fn scale(self, s: f64) -> C { + C { + re: self.re * s, + im: self.im * s, + } + } + pub fn to_json(self) -> Value { + json!({ "re": self.re, "im": self.im }) + } +} + +pub fn max_qubits() -> usize { + match std::env::var("MARQDO_QUANTUM_MAX_QUBITS") { + Ok(s) => s + .trim() + .parse::() + .ok() + .map(|n| n.clamp(1, HARD_MAX_QUBITS)) + .unwrap_or(DEFAULT_MAX_QUBITS), + Err(_) => DEFAULT_MAX_QUBITS, + } +} + +pub fn check_qubits(n: usize) -> Result<(), String> { + let max = max_qubits(); + if n == 0 { + return Err("qubits must be >= 1".into()); + } + if n > max { + return Err(format!( + "qubits={n} exceeds max {max} (set MARQDO_QUANTUM_MAX_QUBITS to lower, hard cap {HARD_MAX_QUBITS})" + )); + } + Ok(()) +} + +fn bit(i: usize, q: usize) -> bool { + ((i >> q) & 1) == 1 +} + +fn flip(i: usize, q: usize) -> usize { + i ^ (1 << q) +} + +/// Apply 2×2 gate `[[a,b],[c,d]]` on qubit `q`. +pub fn apply_u2(amps: &mut [C], q: usize, a: C, b: C, c: C, d: C) { + let n = amps.len(); + let step = 1 << q; + let mut i = 0; + while i < n { + for j in 0..step { + let i0 = i + j; + let i1 = i0 + step; + let v0 = amps[i0]; + let v1 = amps[i1]; + amps[i0] = a.mul(v0).add(b.mul(v1)); + amps[i1] = c.mul(v0).add(d.mul(v1)); + } + i += 2 * step; + } +} + +pub fn apply_x(amps: &mut [C], q: usize) { + apply_u2( + amps, + q, + C::zero(), + C::one(), + C::one(), + C::zero(), + ); +} + +pub fn apply_h(amps: &mut [C], q: usize) { + let s = std::f64::consts::FRAC_1_SQRT_2; + let t = C::new(s, 0.0); + apply_u2(amps, q, t, t, t, t.scale(-1.0)); +} + +pub fn apply_i(_amps: &mut [C], _q: usize) {} + +pub fn apply_cx(amps: &mut [C], control: usize, target: usize) { + if control == target { + return; + } + let n = amps.len(); + for i in 0..n { + if bit(i, control) && !bit(i, target) { + let j = flip(i, target); + if i < j { + amps.swap(i, j); + } + } + } +} + +pub fn zero_state(qubits: usize) -> Vec { + let dim = 1usize << qubits; + let mut amps = vec![C::zero(); dim]; + amps[0] = C::one(); + amps +} + +pub fn renormalize(amps: &mut [C]) { + let n2: f64 = amps.iter().map(|c| c.norm_sq()).sum(); + if n2 <= 0.0 { + return; + } + let inv = 1.0 / n2.sqrt(); + for a in amps.iter_mut() { + *a = a.scale(inv); + } +} + +pub fn basis_label(i: usize, qubits: usize) -> String { + // LSB = qubit 0 on the right + format!("{i:0qubits$b}") +} + +pub fn probabilities(amps: &[C], qubits: usize) -> Map { + let mut m = Map::new(); + for (i, a) in amps.iter().enumerate() { + let p = a.norm_sq(); + if p > 1e-15 { + m.insert(basis_label(i, qubits), json!(p)); + } + } + m +} + +pub fn amps_to_json(amps: &[C]) -> Value { + Value::Array(amps.iter().map(|c| c.to_json()).collect()) +} + +#[derive(Clone, Debug)] +pub struct Op { + pub gate: String, + pub qubits: Vec, + #[allow(dead_code)] + pub theta: Option, // reserved for Rx/Ry/Rz (Q2) +} + +pub fn parse_ops(circuit: &Value) -> Result, String> { + let arr = circuit + .get("ops") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + let mut out = Vec::new(); + for row in arr { + let gate = row + .get("gate") + .or_else(|| row.get("门")) + .and_then(|v| v.as_str()) + .ok_or_else(|| "op missing gate".to_string())? + .to_ascii_uppercase(); + let qubits = match row.get("qubits").or_else(|| row.get("比特")) { + 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 index".to_string()) + .map(|u| u as usize) + }) + .collect::, _>>()?, + Some(Value::Number(n)) => { + 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 + .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] + } else if let (Some(c), Some(t)) = ( + row.get("control") + .or_else(|| row.get("控制")) + .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))), + row.get("target") + .or_else(|| row.get("目标")) + .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))), + ) { + vec![c as usize, t as usize] + } else { + return Err(format!("op `{gate}` missing qubits")); + } + } + }; + let theta = row + .get("theta") + .or_else(|| row.get("参数")) + .and_then(|v| v.as_f64()); + out.push(Op { gate, qubits, theta }); + } + Ok(out) +} + +fn parse_qubit_list(s: &str) -> Result, String> { + s.split(|c| c == ',' || c == ' ' || c == ',') + .filter(|t| !t.is_empty()) + .map(|t| { + t.trim() + .parse::() + .map_err(|_| format!("bad qubit `{t}`")) + }) + .collect() +} + +pub fn apply_op(amps: &mut [C], qubits: usize, op: &Op) -> Result<(), String> { + for &q in &op.qubits { + if q >= qubits { + return Err(format!("qubit {q} out of range for n={qubits}")); + } + } + match op.gate.as_str() { + "I" | "ID" | "IDENTITY" => { + let q = *op.qubits.first().ok_or("I needs qubit")?; + apply_i(amps, q); + } + "X" | "NOT" => { + let q = *op.qubits.first().ok_or("X needs qubit")?; + apply_x(amps, q); + } + "H" | "HADAMARD" => { + let q = *op.qubits.first().ok_or("H needs qubit")?; + apply_h(amps, q); + } + "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]); + } + other => return Err(format!("unsupported gate `{other}` in Q1 (use I/X/H/CX)")), + } + Ok(()) +} + +pub fn simulate_circuit(circuit: &Value) -> Result<(usize, Vec), String> { + 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 mut amps = zero_state(qubits); + for op in &ops { + apply_op(&mut amps, qubits, op)?; + } + renormalize(&mut amps); + Ok((qubits, amps)) +} + +pub fn push_op(circuit: &Value, gate: &str, qubits: Vec, 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; + check_qubits(n)?; + for &q in &qubits { + if q >= n { + return Err(format!("qubit {q} out of range for n={n}")); + } + } + 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(); + let mut op = json!({ + "gate": gate.to_ascii_uppercase(), + "qubits": qubits, + }); + if let Some(t) = theta { + op.as_object_mut().unwrap().insert("theta".into(), json!(t)); + } + ops.push(op); + obj.insert("ops".into(), Value::Array(ops)); + Ok(Value::Object(obj)) +} diff --git a/src/ext_cli.rs b/src/ext_cli.rs index 3daea3d..fdfdc96 100644 --- a/src/ext_cli.rs +++ b/src/ext_cli.rs @@ -36,6 +36,12 @@ pub const CATALOG: &[ExtPackage] = &[ mq_files: &["web/web.mq.md", "web/网页.mq.md"], native_crate: Some("marqdo_plugin_web"), }, + ExtPackage { + id: "quantum", + description: "Quantum circuit simulator (ext/quantum) — gates/state vector", + mq_files: &["quantum/quantum.mq.md", "quantum/量子.mq.md"], + native_crate: Some("marqdo_plugin_quantum"), + }, ]; pub fn find_package(id: &str) -> Option<&'static ExtPackage> { @@ -86,6 +92,7 @@ pub fn native_short_name(crate_or_id: &str) -> &str { match crate_or_id { "marqdo_plugin_agent" | "agent" => "agent", "marqdo_plugin_web" | "web" => "web", + "marqdo_plugin_quantum" | "quantum" => "quantum", other => other, } } @@ -104,6 +111,7 @@ pub fn native_lib_filename(short: &str) -> String { pub fn native_env_var(short: &str) -> &'static str { match native_short_name(short) { "web" => "MARQDO_WEB_PLUGIN", + "quantum" => "MARQDO_QUANTUM_PLUGIN", _ => "MARQDO_AGENT_PLUGIN", } } @@ -314,7 +322,7 @@ pub fn remove_ext(id: &str) -> Result<()> { /// Also falls back to cargo `target/{debug,release}` artifacts for local runs. pub fn installed_native_path(name: &str) -> Option { let short = native_short_name(name); - if !matches!(short, "agent" | "web") { + if !matches!(short, "agent" | "web" | "quantum") { return None; } let lib_name = native_lib_filename(short); @@ -353,7 +361,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool { return true; } } - for key in ["MARQDO_AGENT_PLUGIN", "MARQDO_WEB_PLUGIN"] { + for key in ["MARQDO_AGENT_PLUGIN", "MARQDO_WEB_PLUGIN", "MARQDO_QUANTUM_PLUGIN"] { if let Ok(p) = env::var(key) { let p = PathBuf::from(p); let p = p.canonicalize().unwrap_or(p); @@ -362,7 +370,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool { } } } - for short in ["agent", "web"] { + for short in ["agent", "web", "quantum"] { if let Ok(found) = find_native_plugin(short) { let found = found.canonicalize().unwrap_or(found); if found == path { diff --git a/tests/ext/quantum-bell-smoke.mq.md b/tests/ext/quantum-bell-smoke.mq.md new file mode 100644 index 0000000..27173fc --- /dev/null +++ b/tests/ext/quantum-bell-smoke.mq.md @@ -0,0 +1,42 @@ +--- +title: quantum bell smoke +description: H+CX Bell state probabilities ≈ 1/2 each. +> ext/quantum/quantum.mq.md +> lib/math.mq.md +> lib/json.mq.md +--- + +# main + +*`qc` = > quantum.circuit qubits=2 * +*`qc` = > `qc`.h qubit=0 * +*`qc` = > `qc`.cx control=0 target=1 * +*`p` = > `qc`.probabilities * + +*`p00` = > json.get value=`p` key="00" * +*`p11` = > json.get value=`p` key="11" * +*`lo` = > math.div a=2 b=5 * +*`hi` = > math.div a=3 b=5 * + +1. `p00` > `lo` + 1. `p00` < `hi` + > print text=p00-ok + 2. * + > print text=p00-fail +2. * + > print text=p00-fail + +1. `p11` > `lo` + 1. `p11` < `hi` + > print text=p11-ok + 2. * + > print text=p11-fail +2. * + > print text=p11-fail + +*`ping` = > quantum_ping * +*`ok` = > json.get value=`ping` key=ok * +1. `ok` + > print text=ping-ok +2. * + > print text=ping-fail diff --git a/tests/gold.rs b/tests/gold.rs index 5d1b003..7694ade 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1374,6 +1374,22 @@ custom-ok", ); } +#[test] +fn ext_quantum_bell_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-bell-smoke.mq.md", + "p00-ok +p11-ok +ping-ok", + ); +} + #[test] fn ext_agent_framework_smoke() { let status = Command::new("cargo")