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

+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));
}
}