feat(quantum): Q7 density linear algebra and advanced SVG viz

Add density-matrix ops (partial trace, Hermitian eig, Schmidt, Pauli
expect, purity/fidelity, kron) and hinton/city/qsphere/paulivec/multibloch
draw kinds via plugins/quantum ABI, with EN/ZH L1 and gold smokes.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-28 14:23:24 +08:00
1 parent 4956460773
commit 88fe076216
13 files changed
+1871 -8

No files matched your search

+354
View File
@@ -496,3 +496,357 @@ pub fn matrix_heatmap_svg(m: &[Vec<C>], title: &str) -> String {
body = body,
)
}
fn phase_hue(arg: f64) -> String {
// map [-π,π] → hue degrees
let h = ((arg + std::f64::consts::PI) / (2.0 * std::f64::consts::PI) * 360.0) % 360.0;
format!("hsl({h:.0},70%,45%)")
}
/// Hinton diagram for density matrix (Q7b).
pub fn hinton_svg(m: &[Vec<C>], title: &str) -> String {
let n = m.len().max(1);
let cell = if n <= 2 { 56.0 } else if n <= 4 { 44.0 } else { 32.0 };
let left = 40.0;
let top = 28.0;
let width = left + cell * n as f64 + 16.0;
let height = top + cell * n as f64 + 24.0;
let mut max_a: f64 = 1e-12;
for row in m {
for c in row {
max_a = max_a.max(mag(*c));
}
}
let mut body = String::new();
body.push_str(&format!(
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title}</text>"#,
title = esc(title),
STROKE = STROKE,
));
body.push_str(&format!(
r##"<rect x="{left}" y="{top}" width="{w}" height="{h}" fill="#f0eee8" stroke="{STROKE}" stroke-width="1"/>"##,
left = left,
top = top,
w = cell * n as f64,
h = cell * n as f64,
STROKE = STROKE,
));
for i in 0..n {
for j in 0..n {
let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero());
let a = mag(c) / max_a;
let side = (cell * 0.85 * a.sqrt()).max(1.0);
let cx = left + (j as f64 + 0.5) * cell;
let cy = top + (i as f64 + 0.5) * cell;
let fill = if c.re >= 0.0 { "#f5f5f5" } else { "#1a1a1a" };
let stroke = if c.re >= 0.0 { STROKE } else { "#f5f5f5" };
body.push_str(&format!(
r#"<rect x="{x}" y="{y}" width="{side}" height="{side}" fill="{fill}" stroke="{stroke}" stroke-width="0.8" data-hinton="1"/>"#,
x = cx - side * 0.5,
y = cy - side * 0.5,
side = side,
fill = fill,
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="hinton">{body}</svg>"#,
w = width,
h = height,
body = body,
)
}
/// Cirq-inspired density: magnitude disk + phase needle; diagonal probability bars.
pub fn density_cells_svg(m: &[Vec<C>], title: &str) -> String {
let n = m.len().max(1);
let cell = if n <= 2 { 64.0 } else if n <= 4 { 48.0 } else { 36.0 };
let left = 36.0;
let top = 28.0;
let width = left + cell * n as f64 + 16.0;
let height = top + cell * n as f64 + 20.0;
let mut max_a: f64 = 1e-12;
for row in m {
for c in row {
max_a = max_a.max(mag(*c));
}
}
let mut body = String::new();
body.push_str(&format!(
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title}</text>"#,
title = esc(title),
STROKE = STROKE,
));
for i in 0..n {
for j in 0..n {
let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero());
let x0 = left + j as f64 * cell;
let y0 = top + i as f64 * cell;
body.push_str(&format!(
r##"<rect x="{x0}" y="{y0}" width="{cell}" height="{cell}" fill="#eeeeee" stroke="#ccc" stroke-width="0.5"/>"##,
x0 = x0,
y0 = y0,
cell = cell,
));
let cx = x0 + cell * 0.5;
let cy = y0 + cell * 0.5;
if i == n - 1 - j || i == j {
// soft diagonal highlight for probability (i==j)
}
if i == j {
let p = c.re.clamp(0.0, 1.0);
let bw = cell * 0.7 * p;
body.push_str(&format!(
r##"<rect x="{x}" y="{y}" width="{bw}" height="6" fill="#3a6ea5" data-density-diag="1"/>"##,
x = cx - cell * 0.35,
y = y0 + cell - 10.0,
bw = bw,
));
}
let r = cell * 0.35 * (mag(c) / max_a).sqrt();
let arg = c.im.atan2(c.re);
body.push_str(&format!(
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="{fill}" fill-opacity="0.35" stroke="{fill}" stroke-width="1.2" data-density="1"/>"#,
cx = cx,
cy = cy,
r = r.max(0.5),
fill = phase_hue(arg),
));
let nx = cx + r * arg.cos();
let ny = cy - r * arg.sin();
body.push_str(&format!(
r#"<line x1="{cx}" y1="{cy}" x2="{nx}" y2="{ny}" stroke="{STROKE}" stroke-width="1.2"/>"#,
cx = cx,
cy = cy,
nx = nx,
ny = ny,
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="density">{body}</svg>"#,
w = width,
h = height,
body = body,
)
}
/// 2.5D cityscape: Re (left) and Im (right) bar grids.
pub fn city_svg(m: &[Vec<C>], title: &str) -> String {
let n = m.len().max(1);
let cell = 28.0;
let left = 40.0;
let top = 40.0;
let gap = 24.0;
let grid_w = cell * n as f64;
let width = left + grid_w * 2.0 + gap + 24.0;
let max_h = 80.0;
let mut max_re: f64 = 1e-12;
let mut max_im: f64 = 1e-12;
for row in m {
for c in row {
max_re = max_re.max(c.re.abs());
max_im = max_im.max(c.im.abs());
}
}
let height = top + max_h + cell * n as f64 * 0.35 + 40.0;
let mut body = String::new();
body.push_str(&format!(
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title} (city)</text>"#,
title = esc(title),
STROKE = STROKE,
));
body.push_str(r##"<text x="40" y="34" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="#666">Re</text>"##);
body.push_str(&format!(
r##"<text x="{x}" y="34" font-family="ui-monospace,Menlo,monospace" font-size="10" fill="#666">Im</text>"##,
x = left + grid_w + gap,
));
let draw_city = |body: &mut String, origin_x: f64, use_re: bool| {
for i in 0..n {
for j in 0..n {
let c = m.get(i).and_then(|r| r.get(j)).copied().unwrap_or(C::zero());
let val = if use_re { c.re } else { c.im };
let denom = if use_re { max_re } else { max_im };
let h = (val.abs() / denom) * max_h;
let iso_x = origin_x + (j as f64 - i as f64) * cell * 0.5;
let iso_y = top + (i as f64 + j as f64) * cell * 0.28 + (max_h - h);
let fill = if use_re { "#3a6ea5" } else { "#c45c26" };
body.push_str(&format!(
r#"<rect x="{iso_x}" y="{iso_y}" width="{w}" height="{h}" fill="{fill}" fill-opacity="0.85" stroke="{STROKE}" stroke-width="0.4" data-city="1"/>"#,
iso_x = iso_x,
iso_y = iso_y,
w = cell * 0.45,
h = h.max(0.5),
fill = fill,
STROKE = STROKE,
));
}
}
};
draw_city(&mut body, left + grid_w * 0.35, true);
draw_city(&mut body, left + grid_w + gap + grid_w * 0.35, false);
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="city">{body}</svg>"#,
w = width,
h = height,
body = body,
)
}
/// Pauli expectation bar chart.
pub fn paulivec_svg(labels: &[String], values: &[f64], title: &str) -> String {
let n = labels.len().max(1);
let bar_w = 28.0;
let gap = 8.0;
let left = 48.0;
let top = 28.0;
let chart_h = 120.0;
let width = left + n as f64 * (bar_w + gap) + 16.0;
let height = top + chart_h + 40.0;
let mid_y = top + chart_h * 0.5;
let mut body = String::new();
body.push_str(&format!(
r#"<text x="8" y="18" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="{STROKE}">{title}</text>"#,
title = esc(title),
STROKE = STROKE,
));
body.push_str(&format!(
r##"<line x1="{left}" y1="{mid_y}" x2="{x2}" y2="{mid_y}" stroke="#888" stroke-width="1"/>"##,
left = left,
mid_y = mid_y,
x2 = width - 8.0,
));
for (i, (lab, val)) in labels.iter().zip(values.iter()).enumerate() {
let x = left + i as f64 * (bar_w + gap);
let h = val.abs().clamp(0.0, 1.0) * (chart_h * 0.45);
let y = if *val >= 0.0 { mid_y - h } else { mid_y };
body.push_str(&format!(
r##"<rect x="{x}" y="{y}" width="{bar_w}" height="{h}" fill="#2f6f4e" data-paulivec="1"/>"##,
x = x,
y = y,
bar_w = bar_w,
h = h.max(0.5),
));
body.push_str(&format!(
r#"<text x="{tx}" y="{ty}" text-anchor="middle" font-family="ui-monospace,Menlo,monospace" font-size="9" fill="{STROKE}">{lab}</text>"#,
tx = x + bar_w * 0.5,
ty = top + chart_h + 14.0,
lab = esc(lab),
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="paulivec">{body}</svg>"#,
w = width,
h = height,
body = body,
)
}
/// QSphere-style: amplitudes on a circle (phase→angle, amp→radius of marker).
pub fn qsphere_svg(amps: &[C], qubits: usize) -> String {
let dim = amps.len();
let cx = 160.0;
let cy = 160.0;
let r = 110.0;
let width = 320.0;
let height = 320.0;
let mut body = String::new();
body.push_str(&format!(
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{STROKE}" stroke-width="1.5"/>"#,
cx = cx,
cy = cy,
r = r,
STROKE = STROKE,
));
body.push_str(r##"<text x="12" y="20" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="#1a1a1a">qsphere</text>"##);
for (i, a) in amps.iter().enumerate() {
let amp = mag(*a);
if amp < 1e-9 {
continue;
}
// latitude from Hamming weight, longitude from index
let wt = (i as u32).count_ones() as f64;
let lat = if qubits == 0 {
0.0
} else {
std::f64::consts::PI * (wt / qubits as f64 - 0.5)
};
let lon = 2.0 * std::f64::consts::PI * (i as f64) / (dim as f64);
let rr = r * lat.cos();
let x = cx + rr * lon.cos();
let y = cy - r * lat.sin();
let rad = 4.0 + 14.0 * amp;
let arg = a.im.atan2(a.re);
body.push_str(&format!(
r#"<circle cx="{x}" cy="{y}" r="{rad}" fill="{fill}" stroke="{STROKE}" stroke-width="1" data-qsphere="1"/>"#,
x = x,
y = y,
rad = rad,
fill = phase_hue(arg),
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="qsphere">{body}</svg>"#,
w = width,
h = height,
body = body,
)
}
/// Side-by-side Bloch spheres for each qubit.
pub fn multibloch_svg(amps: &[C], qubits: usize) -> Result<String, String> {
let sphere_w = 140.0;
let width = 16.0 + qubits as f64 * sphere_w;
let height = 160.0;
let mut body = String::new();
body.push_str(r##"<text x="8" y="16" font-family="ui-monospace,Menlo,monospace" font-size="12" fill="#1a1a1a">multibloch</text>"##);
for q in 0..qubits {
let (x, y, z) = crate::sim::bloch_vector(amps, qubits, q)?;
let svg = bloch_svg(x, y, z);
// extract inner content roughly by offsetting — simpler: draw mini sphere
let ox = 8.0 + q as f64 * sphere_w;
let cx = ox + 60.0;
let cy = 90.0;
let r = 40.0;
body.push_str(&format!(
r##"<text x="{ox}" y="32" font-family="ui-monospace,Menlo,monospace" font-size="11" fill="#1a1a1a">q{q}</text>"##,
ox = ox + 8.0,
q = q,
));
body.push_str(&format!(
r##"<ellipse cx="{cx}" cy="{cy}" rx="{r}" ry="{ry}" fill="#f7f4ef" stroke="{STROKE}" stroke-width="1.2"/>"##,
cx = cx,
cy = cy,
r = r,
ry = r * 0.55,
STROKE = STROKE,
));
body.push_str(&format!(
r#"<circle cx="{cx}" cy="{cy}" r="{r}" fill="none" stroke="{STROKE}" stroke-width="1.2"/>"#,
cx = cx,
cy = cy,
r = r,
STROKE = STROKE,
));
let px = cx + x * r;
let py = cy - z * r * 0.85;
body.push_str(&format!(
r##"<line x1="{cx}" y1="{cy}" x2="{px}" y2="{py}" stroke="#c45c26" stroke-width="2" data-multibloch="1"/>"##,
cx = cx,
cy = cy,
px = px,
py = py,
));
let _ = (y, svg);
}
Ok(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="multibloch">{body}</svg>"#,
w = width,
h = height,
body = body,
))
}
+329 -1
View File
@@ -1,6 +1,7 @@
//! Marqdo quantum plugin (C ABI v2): state-vector circuit simulation.
mod draw;
mod linalg;
mod sim;
use std::ffi::{CStr, CString};
@@ -443,9 +444,46 @@ q_ffi!(quantum_draw_circuit, |args: &Value| {
let (x, y, z) = sim::bloch_vector(&amps, qubits, qubit)?;
("bloch", draw::bloch_svg(x, y, z))
}
"hinton" | "欣顿" => {
let (n, amps) = sim::simulate_circuit(c)?;
let (_, rho) = linalg::density_from_amps(&amps, n)?;
let nested = linalg::flat_to_nested(&rho, 1 << n);
("hinton", draw::hinton_svg(&nested, "ρ hinton"))
}
"city" | "城市" => {
let (n, amps) = sim::simulate_circuit(c)?;
let (_, rho) = linalg::density_from_amps(&amps, n)?;
let nested = linalg::flat_to_nested(&rho, 1 << n);
("city", draw::city_svg(&nested, "ρ"))
}
"density" | "密度图" => {
let (n, amps) = sim::simulate_circuit(c)?;
let (_, rho) = linalg::density_from_amps(&amps, n)?;
let nested = linalg::flat_to_nested(&rho, 1 << n);
("density", draw::density_cells_svg(&nested, "ρ"))
}
"paulivec" | "泡利向量" => {
let (n, amps) = sim::simulate_circuit(c)?;
let (_, rho) = linalg::density_from_amps(&amps, n)?;
let dim = 1 << n;
let labels = linalg::all_pauli_labels(n)?;
let mut vals = Vec::with_capacity(labels.len());
for lab in &labels {
vals.push(linalg::expect_pauli(&rho, dim, n, lab)?);
}
("paulivec", draw::paulivec_svg(&labels, &vals, "Pauli"))
}
"qsphere" | "球" => {
let (n, amps) = sim::simulate_circuit(c)?;
("qsphere", draw::qsphere_svg(&amps, n))
}
"multibloch" | "多布洛赫" => {
let (n, amps) = sim::simulate_circuit(c)?;
("multibloch", draw::multibloch_svg(&amps, n)?)
}
other => {
return Err(format!(
"unknown draw kind `{other}` (circuit|probs|bloch)"
"unknown draw kind `{other}` (circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch)"
));
}
};
@@ -587,6 +625,249 @@ q_ffi!(quantum_apply, |args: &Value| {
sim::apply_gate(c, gate, qubits)
});
q_ffi!(quantum_density_from_state, |args: &Value| {
let src = args
.get("state")
.or_else(|| args.get("态"))
.or_else(|| args.get("circuit"))
.or_else(|| args.get("电路"))
.ok_or_else(|| "density needs `state` or `circuit`".to_string())?;
let (n, amps) = linalg::amps_from_state_or_circuit(src)?;
let (_, rho) = linalg::density_from_amps(&amps, n)?;
Ok(linalg::density_handle(n, &rho))
});
q_ffi!(quantum_density_from_matrix, |args: &Value| {
let matrix = args
.get("matrix")
.or_else(|| args.get("矩阵"))
.ok_or_else(|| "missing `matrix`".to_string())?;
let bag = json!({ "matrix": matrix });
let (n, rho) = linalg::parse_density(&bag)?;
Ok(linalg::density_handle(n, &rho))
});
q_ffi!(quantum_density_matrix, |args: &Value| {
let d = args
.get("density")
.or_else(|| args.get("密度"))
.ok_or_else(|| "missing `density`".to_string())?;
let (n, rho) = linalg::parse_density(d)?;
let dim = 1 << n;
Ok(sim::matrix_to_json(&linalg::flat_to_nested(&rho, dim)))
});
q_ffi!(quantum_density_purity, |args: &Value| {
let d = args
.get("density")
.or_else(|| args.get("密度"))
.ok_or_else(|| "missing `density`".to_string())?;
let (n, rho) = linalg::parse_density(d)?;
let dim = 1 << n;
Ok(json!(linalg::purity(&rho, dim)))
});
q_ffi!(quantum_density_partial_trace, |args: &Value| {
let d = args
.get("density")
.or_else(|| args.get("密度"))
.ok_or_else(|| "missing `density`".to_string())?;
let keep_v = args
.get("keep")
.or_else(|| args.get("保留"))
.ok_or_else(|| "missing `keep`".to_string())?;
let keep = parse_usize_list(keep_v)?;
let (n, rho) = linalg::parse_density(d)?;
let (k, out) = linalg::partial_trace(&rho, n, &keep)?;
Ok(linalg::density_handle(k, &out))
});
q_ffi!(quantum_density_eig, |args: &Value| {
let d = args
.get("density")
.or_else(|| args.get("密度"))
.ok_or_else(|| "missing `density`".to_string())?;
let (n, rho) = linalg::parse_density(d)?;
let dim = 1 << n;
let (evals, evecs) = linalg::hermite_eig(&rho, dim)?;
Ok(linalg::spectrum_handle(&evals, &evecs))
});
q_ffi!(quantum_density_expect, |args: &Value| {
let d = args
.get("density")
.or_else(|| args.get("密度"))
.or_else(|| args.get("state"))
.or_else(|| args.get("态"))
.or_else(|| args.get("circuit"))
.or_else(|| args.get("电路"))
.ok_or_else(|| "expect needs density/state/circuit".to_string())?;
let (n, rho) = if d.get("amplitudes").is_some()
|| d.get("_type").and_then(|t| t.as_str()) == Some("quantum_state")
|| d.get("ops").is_some()
{
let (qn, amps) = linalg::amps_from_state_or_circuit(d)?;
let (_, r) = linalg::density_from_amps(&amps, qn)?;
(qn, r)
} else {
linalg::parse_density(d)?
};
let dim = 1 << n;
let obs = args
.get("obs")
.or_else(|| args.get("可观测量"))
.ok_or_else(|| "missing `obs`".to_string())?;
let val = if let Some(s) = obs.as_str() {
linalg::expect_pauli(&rho, dim, n, s)?
} else {
let (_od, om) = linalg::value_as_matrix(obs)?;
linalg::expect_matrix(&rho, dim, &om, dim)?
};
Ok(json!(val))
});
q_ffi!(quantum_density_draw, |args: &Value| {
let d = args
.get("density")
.or_else(|| args.get("密度"))
.ok_or_else(|| "missing `density`".to_string())?;
let kind = args
.get("kind")
.or_else(|| args.get("种类"))
.and_then(|v| v.as_str())
.unwrap_or("hinton")
.to_ascii_lowercase();
let path = args
.get("path")
.or_else(|| args.get("路径"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
let (n, rho) = linalg::parse_density(d)?;
let dim = 1 << n;
let nested = linalg::flat_to_nested(&rho, dim);
let (kind_out, svg) = match kind.as_str() {
"hinton" | "欣顿" => ("hinton", draw::hinton_svg(&nested, "ρ hinton")),
"city" | "城市" => ("city", draw::city_svg(&nested, "ρ")),
"density" | "密度图" => ("density", draw::density_cells_svg(&nested, "ρ")),
"paulivec" | "泡利向量" => {
let labels = linalg::all_pauli_labels(n)?;
let mut vals = Vec::with_capacity(labels.len());
for lab in &labels {
vals.push(linalg::expect_pauli(&rho, dim, n, lab)?);
}
("paulivec", draw::paulivec_svg(&labels, &vals, "Pauli"))
}
other => {
return Err(format!(
"unknown density draw kind `{other}` (hinton|city|density|paulivec)"
));
}
};
record_plot(&svg, path)?;
Ok(json!({
"_type": "quantum_svg",
"kind": kind_out,
"qubits": n,
"svg": svg,
}))
});
q_ffi!(quantum_kron, |args: &Value| {
let a = args
.get("a")
.or_else(|| args.get("左"))
.ok_or_else(|| "kron needs `a`".to_string())?;
let b = args
.get("b")
.or_else(|| args.get("右"))
.ok_or_else(|| "kron needs `b`".to_string())?;
if (a.get("amplitudes").is_some()
|| a.get("_type").and_then(|t| t.as_str()) == Some("quantum_state"))
&& (b.get("amplitudes").is_some()
|| b.get("_type").and_then(|t| t.as_str()) == Some("quantum_state"))
{
let (na, aa) = linalg::amps_from_state_or_circuit(a)?;
let (nb, bb) = linalg::amps_from_state_or_circuit(b)?;
let out = linalg::kronecker_amps(&aa, &bb);
return Ok(json!({
"_type": "quantum_state",
"qubits": na + nb,
"dim": out.len(),
"amplitudes": sim::amps_to_json(&out),
}));
}
let (_na, ma) = linalg::value_as_matrix(a)?;
let (_nb, mb) = linalg::value_as_matrix(b)?;
let da = (ma.len() as f64).sqrt() as usize;
let db = (mb.len() as f64).sqrt() as usize;
if da * da != ma.len() || db * db != mb.len() {
return Err("kron: matrices must be square".into());
}
let out = linalg::kronecker(&ma, da, &mb, db);
let dim = da * db;
let qubits_f = (dim as f64).log2();
if (qubits_f - qubits_f.round()).abs() < 1e-9 {
let qubits = qubits_f.round() as usize;
Ok(linalg::density_handle(qubits, &out))
} else {
Ok(json!({
"_type": "quantum_density",
"dim": dim,
"matrix": sim::matrix_to_json(&linalg::flat_to_nested(&out, dim)),
}))
}
});
q_ffi!(quantum_schmidt, |args: &Value| {
let src = args
.get("state")
.or_else(|| args.get("态"))
.or_else(|| args.get("circuit"))
.or_else(|| args.get("电路"))
.ok_or_else(|| "schmidt needs `state` or `circuit`".to_string())?;
let cut = arg_u(args, "cut")
.or_else(|_| arg_u(args, "分割"))
.unwrap_or(1);
let (n, amps) = linalg::amps_from_state_or_circuit(src)?;
linalg::schmidt_decompose(&amps, n, cut)
});
q_ffi!(quantum_fidelity, |args: &Value| {
let a = args
.get("a")
.or_else(|| args.get("左"))
.ok_or_else(|| "fidelity needs `a`".to_string())?;
let b = args
.get("b")
.or_else(|| args.get("右"))
.ok_or_else(|| "fidelity needs `b`".to_string())?;
let (_, aa) = linalg::amps_from_state_or_circuit(a)?;
let (_, bb) = linalg::amps_from_state_or_circuit(b)?;
Ok(json!(linalg::fidelity_pure(&aa, &bb)?))
});
fn parse_usize_list(v: &Value) -> Result<Vec<usize>, String> {
match v {
Value::Array(a) => a
.iter()
.map(|x| {
x.as_u64()
.or_else(|| x.as_i64().map(|i| i as u64))
.or_else(|| x.as_str().and_then(|s| s.trim().parse().ok()))
.map(|u| u as usize)
.ok_or_else(|| "bad keep list entry".to_string())
})
.collect(),
Value::Number(n) => Ok(vec![n.as_u64().unwrap_or(0) as usize]),
Value::String(s) => s
.split(|c| c == ',' || c == ' ')
.filter(|t| !t.is_empty())
.map(|t| t.parse().map_err(|_| format!("bad keep `{t}`")))
.collect(),
_ => Err("keep must be list, number, or comma string".into()),
}
}
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
let register = match host.register_fn {
Some(f) => f,
@@ -695,6 +976,53 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
"circuit,gate,qubits",
quantum_apply as PluginFn,
),
(
"quantum_density_from_state",
"state",
quantum_density_from_state as PluginFn,
),
(
"quantum_density_from_matrix",
"matrix",
quantum_density_from_matrix as PluginFn,
),
(
"quantum_density_matrix",
"density",
quantum_density_matrix as PluginFn,
),
(
"quantum_density_purity",
"density",
quantum_density_purity as PluginFn,
),
(
"quantum_density_partial_trace",
"density,keep",
quantum_density_partial_trace as PluginFn,
),
(
"quantum_density_eig",
"density",
quantum_density_eig as PluginFn,
),
(
"quantum_density_expect",
"density,obs",
quantum_density_expect as PluginFn,
),
(
"quantum_density_draw",
"density,path,kind",
quantum_density_draw as PluginFn,
),
("quantum_kron", "a,b", quantum_kron as PluginFn),
(
"quantum_schmidt",
"state,cut",
quantum_schmidt as PluginFn,
),
("quantum_fidelity", "a,b", quantum_fidelity as PluginFn),
];
for (name, params, f) in regs {
if register(host, name, params, f) != 0 {
+638
View File
@@ -0,0 +1,638 @@
//! Q7a: density matrix, Kronecker, partial trace, Hermitian eig, Schmidt, Pauli expect.
use serde_json::{json, Map, Value};
use crate::sim::{
amps_to_json, matrix_to_json, parse_matrix, simulate_circuit, C,
};
pub const DENSITY_MAX_QUBITS: usize = 6;
fn check_density_qubits(n: usize) -> Result<(), String> {
if n > DENSITY_MAX_QUBITS {
return Err(format!(
"density-matrix ops limited to {DENSITY_MAX_QUBITS} qubits (got {n}); use state-vector APIs for larger n"
));
}
Ok(())
}
fn dim_of(n: usize) -> usize {
1usize << n
}
/// Flat row-major dim×dim complex matrix.
pub type Mat = Vec<C>;
pub fn mat_get(m: &Mat, dim: usize, i: usize, j: usize) -> C {
m[i * dim + j]
}
pub fn mat_set(m: &mut Mat, dim: usize, i: usize, j: usize, v: C) {
m[i * dim + j] = v;
}
pub fn mat_zeros(dim: usize) -> Mat {
vec![C::zero(); dim * dim]
}
pub fn nested_to_flat(m: &[Vec<C>]) -> Result<(usize, Mat), String> {
if m.is_empty() {
return Err("matrix is empty".into());
}
let dim = m.len();
for (i, row) in m.iter().enumerate() {
if row.len() != dim {
return Err(format!("matrix row {i} length {} != {dim}", row.len()));
}
}
let mut flat = Mat::with_capacity(dim * dim);
for row in m {
flat.extend_from_slice(row);
}
Ok((dim, flat))
}
pub fn flat_to_nested(m: &Mat, dim: usize) -> Vec<Vec<C>> {
let mut out = Vec::with_capacity(dim);
for i in 0..dim {
out.push(m[i * dim..(i + 1) * dim].to_vec());
}
out
}
pub fn density_from_amps(amps: &[C], qubits: usize) -> Result<(usize, Mat), String> {
check_density_qubits(qubits)?;
let dim = dim_of(qubits);
if amps.len() != dim {
return Err(format!(
"state dim {} != 2^{qubits}={dim}",
amps.len()
));
}
let mut rho = mat_zeros(dim);
for i in 0..dim {
for j in 0..dim {
// ρ_ij = ψ_i * conj(ψ_j)
mat_set(&mut rho, dim, i, j, amps[i].mul(amps[j].conj()));
}
}
Ok((dim, rho))
}
pub fn amps_from_state_or_circuit(v: &Value) -> Result<(usize, Vec<C>), String> {
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_circuit")
|| (v.get("qubits").is_some() && v.get("ops").is_some())
{
let (n, amps) = simulate_circuit(v)?;
return Ok((n, amps));
}
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_state")
|| v.get("amplitudes").is_some()
{
let qubits = v
.get("qubits")
.or_else(|| v.get("比特数"))
.and_then(|x| x.as_u64().or_else(|| x.as_i64().map(|i| i as u64)))
.ok_or_else(|| "state missing qubits".to_string())? as usize;
let amps_v = v
.get("amplitudes")
.or_else(|| v.get("振幅"))
.ok_or_else(|| "state missing amplitudes".to_string())?;
let nested = match amps_v {
Value::Array(a) => a
.iter()
.map(|c| match c {
Value::Object(o) => Ok(C::new(
o.get("re").and_then(|x| x.as_f64()).unwrap_or(0.0),
o.get("im").and_then(|x| x.as_f64()).unwrap_or(0.0),
)),
_ => Err("amplitude cell must be {re,im}".into()),
})
.collect::<Result<Vec<_>, String>>()?,
_ => return Err("amplitudes must be a list".into()),
};
return Ok((qubits, nested));
}
Err("expected quantum_state or quantum_circuit".into())
}
pub fn density_handle(qubits: usize, rho: &Mat) -> Value {
let dim = dim_of(qubits);
json!({
"_type": "density",
"qubits": qubits,
"dim": dim,
"matrix": matrix_to_json(&flat_to_nested(rho, dim)),
})
}
pub fn parse_density(v: &Value) -> Result<(usize, Mat), String> {
if let Some(mat_v) = v.get("matrix").or_else(|| v.get("矩阵")) {
let nested = parse_matrix(mat_v)?;
let (dim, flat) = nested_to_flat(&nested)?;
let qubits = (dim as f64).log2() as usize;
if dim_of(qubits) != dim {
return Err(format!("density dim {dim} is not a power of two"));
}
check_density_qubits(qubits)?;
check_hermitian(&flat, dim)?;
return Ok((qubits, flat));
}
let (n, amps) = amps_from_state_or_circuit(v)?;
density_from_amps(&amps, n)
}
pub fn check_hermitian(m: &Mat, dim: usize) -> Result<(), String> {
let mut err = 0.0;
for i in 0..dim {
for j in i..dim {
let a = mat_get(m, dim, i, j);
let b = mat_get(m, dim, j, i).conj();
let d = a.sub(b);
err += d.norm_sq();
}
}
if err.sqrt() > 1e-8 {
return Err(format!(
"matrix is not Hermitian (‖ρ−ρ†‖_F ≈ {:.2e})",
err.sqrt()
));
}
Ok(())
}
pub fn purity(m: &Mat, dim: usize) -> f64 {
// Tr(ρ²) = Σ_ij |ρ_ij|² for Hermitian ρ? Actually Tr(ρ²)=Σ_ij ρ_ij ρ_ji = Σ_ij |ρ_ij|² when Hermitian.
let mut s = 0.0;
for i in 0..dim {
for j in 0..dim {
s += mat_get(m, dim, i, j).norm_sq();
}
}
s
}
pub fn kronecker(a: &Mat, da: usize, b: &Mat, db: usize) -> Mat {
let dim = da * db;
let mut out = mat_zeros(dim);
for i in 0..da {
for j in 0..da {
let aij = mat_get(a, da, i, j);
for k in 0..db {
for l in 0..db {
let bij = mat_get(b, db, k, l);
mat_set(
&mut out,
dim,
i * db + k,
j * db + l,
aij.mul(bij),
);
}
}
}
}
out
}
pub fn kronecker_amps(a: &[C], b: &[C]) -> Vec<C> {
let mut out = Vec::with_capacity(a.len() * b.len());
for &ai in a {
for &bj in b {
out.push(ai.mul(bj));
}
}
out
}
/// Keep listed qubits (LSB numbering). Trace out the rest.
pub fn partial_trace(rho: &Mat, qubits: usize, keep: &[usize]) -> Result<(usize, Mat), String> {
check_density_qubits(qubits)?;
let mut keep_sorted = keep.to_vec();
keep_sorted.sort_unstable();
keep_sorted.dedup();
for &q in &keep_sorted {
if q >= qubits {
return Err(format!("keep qubit {q} out of range for n={qubits}"));
}
}
let k = keep_sorted.len();
check_density_qubits(k)?;
let dim = dim_of(qubits);
let kdim = dim_of(k);
let mut out = mat_zeros(kdim);
// Map full basis index -> kept subspace index
let map_keep = |full: usize| -> usize {
let mut idx = 0usize;
for (bit_pos, &q) in keep_sorted.iter().enumerate() {
if (full >> q) & 1 == 1 {
idx |= 1 << bit_pos;
}
}
idx
};
let traced: Vec<usize> = (0..qubits).filter(|q| !keep_sorted.contains(q)).collect();
for i in 0..dim {
for j in 0..dim {
// Only contribute when traced bits of i and j match
let mut same = true;
for &q in &traced {
if ((i >> q) & 1) != ((j >> q) & 1) {
same = false;
break;
}
}
if !same {
continue;
}
let ik = map_keep(i);
let jk = map_keep(j);
let v = mat_get(rho, dim, i, j);
let cur = mat_get(&out, kdim, ik, jk);
mat_set(&mut out, kdim, ik, jk, cur.add(v));
}
}
Ok((k, out))
}
/// Jacobi eigenvalue algorithm for Hermitian matrices. Returns eigenvalues (desc) and eigenvectors as columns.
pub fn hermite_eig(m: &Mat, dim: usize) -> Result<(Vec<f64>, Vec<Vec<C>>), String> {
check_hermitian(m, dim)?;
let mut a = m.clone();
// Force diagonal imaginary parts to 0 (Hermitian)
for i in 0..dim {
let d = mat_get(&a, dim, i, i);
mat_set(&mut a, dim, i, i, C::new(d.re, 0.0));
}
let mut v = mat_zeros(dim);
for i in 0..dim {
mat_set(&mut v, dim, i, i, C::one());
}
let max_iter = 200 * dim * dim;
for _ in 0..max_iter {
let mut p = 0usize;
let mut q = 1usize;
let mut max_abs = 0.0;
for i in 0..dim {
for j in (i + 1)..dim {
let mag = mat_get(&a, dim, i, j).norm_sq().sqrt();
if mag > max_abs {
max_abs = mag;
p = i;
q = j;
}
}
}
if max_abs < 1e-14 {
break;
}
let app = mat_get(&a, dim, p, p).re;
let aqq = mat_get(&a, dim, q, q).re;
let apq = mat_get(&a, dim, p, q);
let abs_apq = apq.norm_sq().sqrt();
let phase = apq.scale(1.0 / abs_apq); // e^{iα}
// tan(2φ) = 2|apq| / (app - aqq)
let diff = app - aqq;
let (c, s_mag) = if abs_apq < 1e-30 {
(1.0, 0.0)
} else {
let tau = diff / (2.0 * abs_apq);
let t = if tau >= 0.0 {
1.0 / (tau + (1.0 + tau * tau).sqrt())
} else {
-1.0 / (-tau + (1.0 + tau * tau).sqrt())
};
let cc = 1.0 / (1.0 + t * t).sqrt();
(cc, t * cc)
};
let s = phase.scale(s_mag); // complex sine
// Apply Jacobi rotation to A (similarity J† A J)
let mut row_p = vec![C::zero(); dim];
let mut row_q = vec![C::zero(); dim];
for i in 0..dim {
let aip = mat_get(&a, dim, i, p);
let aiq = mat_get(&a, dim, i, q);
row_p[i] = aip.scale(c).add(aiq.mul(s));
row_q[i] = aiq.scale(c).sub(aip.mul(s.conj()));
}
// Diagonals: phase = apq/|apq| ⇒ Re(conj(phase)*apq) = |apq|
let new_app = c * c * app + s_mag * s_mag * aqq + 2.0 * c * s_mag * abs_apq;
let new_aqq = c * c * aqq + s_mag * s_mag * app - 2.0 * c * s_mag * abs_apq;
for i in 0..dim {
if i == p || i == q {
continue;
}
mat_set(&mut a, dim, i, p, row_p[i]);
mat_set(&mut a, dim, p, i, row_p[i].conj());
mat_set(&mut a, dim, i, q, row_q[i]);
mat_set(&mut a, dim, q, i, row_q[i].conj());
}
mat_set(&mut a, dim, p, p, C::new(new_app, 0.0));
mat_set(&mut a, dim, q, q, C::new(new_aqq, 0.0));
mat_set(&mut a, dim, p, q, C::zero());
mat_set(&mut a, dim, q, p, C::zero());
// V ← V J
for i in 0..dim {
let vip = mat_get(&v, dim, i, p);
let viq = mat_get(&v, dim, i, q);
mat_set(&mut v, dim, i, p, vip.scale(c).add(viq.mul(s)));
mat_set(
&mut v,
dim,
i,
q,
viq.scale(c).sub(vip.mul(s.conj())),
);
}
}
let mut evals: Vec<(f64, usize)> = (0..dim)
.map(|i| (mat_get(&a, dim, i, i).re, i))
.collect();
evals.sort_by(|x, y| y.0.partial_cmp(&x.0).unwrap_or(std::cmp::Ordering::Equal));
let mut eigenvalues = Vec::with_capacity(dim);
let mut eigenvectors = Vec::with_capacity(dim);
for &(ev, idx) in &evals {
eigenvalues.push(ev);
let mut col = Vec::with_capacity(dim);
for row in 0..dim {
col.push(mat_get(&v, dim, row, idx));
}
let nrm = col.iter().map(|c| c.norm_sq()).sum::<f64>().sqrt();
if nrm > 1e-15 {
for c in &mut col {
*c = c.scale(1.0 / nrm);
}
}
eigenvectors.push(col);
}
Ok((eigenvalues, eigenvectors))
}
/// Thin SVD via eig of A†A for complex matrix rows×cols (rows = 2^cut, cols = 2^(n-cut)).
pub fn schmidt_decompose(amps: &[C], qubits: usize, cut: usize) -> Result<Value, String> {
if cut == 0 || cut >= qubits {
return Err(format!("schmidt cut must be in 1..{} (got {cut})", qubits - 1));
}
check_density_qubits(qubits)?;
let da = dim_of(cut);
let db = dim_of(qubits - cut);
if amps.len() != da * db {
return Err("state dimension mismatch for schmidt".into());
}
// Build Gram G = M M† (da×da) where M[ia, ib] = ψ[(ib << cut) | ia] (A = low bits)
let mut gram = mat_zeros(da);
for ia in 0..da {
for ja in 0..da {
let mut s = C::zero();
for ib in 0..db {
let i = (ib << cut) | ia;
let j = (ib << cut) | ja;
s = s.add(amps[i].mul(amps[j].conj()));
}
mat_set(&mut gram, da, ia, ja, s);
}
}
let (evals, evecs) = hermite_eig(&gram, da)?;
let coeffs: Vec<f64> = evals
.iter()
.map(|e| e.max(0.0).sqrt())
.collect();
// entropy
let mut entropy = 0.0;
for &c in &coeffs {
let p = c * c;
if p > 1e-15 {
entropy -= p * p.ln();
}
}
// Keep significant coeffs
let ua: Vec<Value> = evecs
.iter()
.map(|col| Value::Array(col.iter().map(|c| c.to_json()).collect()))
.collect();
// For each singular vector u_k, v_k = M† u_k / σ_k
let mut ub = Vec::new();
for (k, sigma) in coeffs.iter().enumerate() {
if *sigma < 1e-12 {
ub.push(Value::Array(
(0..db).map(|_| C::zero().to_json()).collect(),
));
continue;
}
let u = &evecs[k];
let mut vk = vec![C::zero(); db];
for ib in 0..db {
let mut s = C::zero();
for ia in 0..da {
let idx = (ib << cut) | ia;
// (M† u)_ib = Σ_ia conj(M_ia,ib) u_ia = Σ conj(ψ) u
s = s.add(amps[idx].conj().mul(u[ia]));
}
vk[ib] = s.scale(1.0 / sigma);
}
ub.push(Value::Array(vk.iter().map(|c| c.to_json()).collect()));
}
// Drop near-zero trailing for readability but keep all for determinism
let _ = coeffs
.iter()
.position(|&c| c < 1e-10)
.unwrap_or(coeffs.len());
Ok(json!({
"_type": "quantum_schmidt",
"cut": cut,
"qubits": qubits,
"coeffs": coeffs,
"ua": ua,
"ub": ub,
"entropy": entropy,
}))
}
fn pauli_matrix(p: char) -> Result<[[C; 2]; 2], String> {
match p.to_ascii_uppercase() {
'I' => Ok([
[C::one(), C::zero()],
[C::zero(), C::one()],
]),
'X' => Ok([
[C::zero(), C::one()],
[C::one(), C::zero()],
]),
'Y' => Ok([
[C::zero(), C::new(0.0, -1.0)],
[C::new(0.0, 1.0), C::zero()],
]),
'Z' => Ok([
[C::one(), C::zero()],
[C::zero(), C::new(-1.0, 0.0)],
]),
other => Err(format!("unknown Pauli `{other}` (I/X/Y/Z)")),
}
}
/// Pauli string: left = qubit n-1 (MSB), right = qubit 0 (LSB). Returns dim×dim.
pub fn pauli_string_matrix(s: &str, qubits: usize) -> Result<(usize, Mat), String> {
let t = s.trim();
if t.len() != qubits {
return Err(format!(
"Pauli string length {} != qubits {qubits} (left=high bit)",
t.len()
));
}
let chars: Vec<char> = t.chars().collect();
// chars[0] = qubit n-1
let mut mat = {
let p = pauli_matrix(chars[qubits - 1])?; // qubit 0 first in kron chain
let mut m = mat_zeros(2);
for i in 0..2 {
for j in 0..2 {
mat_set(&mut m, 2, i, j, p[i][j]);
}
}
(2usize, m)
};
for q in 1..qubits {
let ch = chars[qubits - 1 - q];
let p = pauli_matrix(ch)?;
let mut b = mat_zeros(2);
for i in 0..2 {
for j in 0..2 {
mat_set(&mut b, 2, i, j, p[i][j]);
}
}
// New = b ⊗ old so that higher qubit is left in kron...
// Full basis: index bit q corresponds to qubit q.
// Kronecker A⊗B means A on high subspace if we use (i<<logB)|j with j low.
// We build from qubit0 (LSB) up: mat = P_{q} ⊗ mat
let (da, a) = (2usize, b);
let (db, ref bm) = mat;
let out = kronecker(&a, da, bm, db);
mat = (da * db, out);
}
Ok(mat)
}
pub fn expect_pauli(rho: &Mat, dim: usize, qubits: usize, obs: &str) -> Result<f64, String> {
let (od, op) = pauli_string_matrix(obs, qubits)?;
if od != dim {
return Err("observable dimension mismatch".into());
}
// ⟨P⟩ = Tr(ρ P) = Σ_ij ρ_ij P_ji
let mut s = C::zero();
for i in 0..dim {
for j in 0..dim {
s = s.add(mat_get(rho, dim, i, j).mul(mat_get(&op, dim, j, i)));
}
}
if s.im.abs() > 1e-8 {
return Err(format!("expectation has imaginary part {}", s.im));
}
Ok(s.re)
}
pub fn expect_matrix(rho: &Mat, dim: usize, obs: &Mat, odim: usize) -> Result<f64, String> {
if odim != dim {
return Err("observable dimension mismatch".into());
}
let mut s = C::zero();
for i in 0..dim {
for j in 0..dim {
s = s.add(mat_get(rho, dim, i, j).mul(mat_get(obs, dim, j, i)));
}
}
Ok(s.re)
}
pub fn fidelity_pure(a: &[C], b: &[C]) -> Result<f64, String> {
if a.len() != b.len() {
return Err("fidelity: state dimensions differ".into());
}
let mut s = C::zero();
for i in 0..a.len() {
s = s.add(a[i].conj().mul(b[i]));
}
Ok(s.norm_sq())
}
pub fn all_pauli_labels(qubits: usize) -> Result<Vec<String>, String> {
if qubits > 3 {
return Err("paulivec default basis only for n≤3; pass explicit ops".into());
}
let letters = ['I', 'X', 'Y', 'Z'];
let n = qubits;
let total = 4usize.pow(n as u32);
let mut out = Vec::with_capacity(total);
for code in 0..total {
let mut s = String::with_capacity(n);
let mut c = code;
// left = high qubit
let mut chars = vec!['I'; n];
for q in 0..n {
chars[n - 1 - q] = letters[c % 4];
c /= 4;
}
for ch in chars {
s.push(ch);
}
out.push(s);
}
Ok(out)
}
pub fn spectrum_handle(evals: &[f64], evecs: &[Vec<C>]) -> Value {
let eigenvectors: Vec<Value> = evecs
.iter()
.map(|col| Value::Array(col.iter().map(|c| c.to_json()).collect()))
.collect();
json!({
"_type": "quantum_spectrum",
"eigenvalues": evals,
"eigenvectors": eigenvectors,
})
}
pub fn value_as_matrix(v: &Value) -> Result<(usize, Mat), String> {
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_density")
|| v.get("_type").and_then(|t| t.as_str()) == Some("density")
|| v.get("_type").and_then(|t| t.as_str()) == Some("密度")
|| v.get("matrix").is_some()
{
return parse_density(v);
}
if v.get("_type").and_then(|t| t.as_str()) == Some("quantum_gate") {
let nested = crate::sim::gate_matrix_of(v)?;
let (dim, flat) = nested_to_flat(&nested)?;
return Ok(((dim as f64).log2() as usize, flat));
}
// nested list
let nested = parse_matrix(v)?;
let (dim, flat) = nested_to_flat(&nested)?;
Ok(((dim as f64).log2() as usize, flat))
}
/// Helper for JSON amps list export (re-export style).
pub fn amps_json(amps: &[C]) -> Value {
amps_to_json(amps)
}
pub fn density_map_insert_matrix(obj: &mut Map<String, Value>, rho: &Mat, dim: usize) {
obj.insert(
"matrix".into(),
matrix_to_json(&flat_to_nested(rho, dim)),
);
}
+12
View File
@@ -42,6 +42,18 @@ impl C {
im: self.im * s,
}
}
pub fn conj(self) -> C {
C {
re: self.re,
im: -self.im,
}
}
pub fn sub(self, o: C) -> C {
C {
re: self.re - o.re,
im: self.im - o.im,
}
}
pub fn to_json(self) -> Value {
json!({ "re": self.re, "im": self.im })
}