Add formula-matrix custom gates and fix Variables modal in view.

Parse $$ pmatrix/[[…]] into executable matrices for quantum.gate matrix=, and make the vars panel open a rich modal without breaking the page script.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-12 14:40:55 +08:00
1 parent 505d478724
commit d269ccb7e7
15 files changed
+1622 -162

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
# `ext/quantum` — 自定义酉门(公式矩阵 → 可施加)
| | |
|---|---|
| 状态 | **Accepted · 已落地** |
| 日期 | 2026-08-12 |
| 父设计 | [ext-quantum.md](ext-quantum.md) |
---
## 1. 目标
作者用 `$$…$$`(或嵌套 list)写出酉矩阵 → `quantum.gate matrix=…` 得到可复用门句柄 → `` `qc`.apply gate=… qubits=… `` 施加到电路。
---
## 2. 公式矩阵
`$$` 围栏若含 `[[…]]` 或 `\begin{pmatrix}` / `\begin{bmatrix}`,在**解析期**求值为嵌套数值 list(非整棵 `Formula` 标量树)。
支持:
- ASCII:`[[1,0],[0,-1]]`、`(1/sqrt(2))*[[1,1],[1,-1]]`
- LaTeX 子集:`\frac{…}{…}`、`\sqrt{…}`、`pmatrix` / `bmatrix`(`&` / `\\`)
复数:list 路径仍可用 `{re,im}` 或 `[re,im]`;公式路径本切片以实矩阵为主。
---
## 3. API
```markdown
*`U` = > quantum.gate matrix=`H_matrix` name=U *
# 或构造参数 matrix=;name 可选(默认 U)
*`qc` = > `qc`.apply gate=`U` qubits=0 *
# qubits= 标量或 list;矩阵维数须为 2^k
```
中文:`量子.门 矩阵=` / `` `qc`.施加 门= 比特= ``。
具名门仍可用 `name=H`;`matrix` / `matches_matrix` / `draw` 对自定义门同样有效。
---
## 4. 验收
- 公式(或 list)定义的 H 与内置 `H` 概率一致
- EN/ZH 金样
+6 -8
View File
@@ -131,7 +131,7 @@ marqdo ext add quantum
### 4.3 公式面(对齐 math 精神,不抢 math 实现)
允许用 `` `G` = `` + `$$…$$` 书写门矩阵或态(**展示 + 教学核对**):
允许用 `` `G` = `` + `$$…$$` 书写门矩阵(**可执行**,见 [ext-quantum-custom-gate.md](ext-quantum-custom-gate.md)):
````markdown
`H_matrix` =
@@ -139,16 +139,14 @@ $$
\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}
$$
*`H` = > quantum.gate name=H *
*`U` = > quantum.gate matrix=`H_matrix` *
*`qc` = > `qc`.apply gate=`U` qubits=0 *
*`ok` = > `H`.matches_matrix matrix=`H_matrix` *
````
- v1:**具名门**以插件内置酉矩阵为准;`matches_matrix` 为可选数值核对(容差)。
- 叙述区无名 `$$` 仍只是注释(同 [stdlib-math.md](stdlib-math.md) §2.4)。
- **不**要求核心 `Value::Formula` 理解量子;矩阵核对可走「公式 ASCII/LaTeX → 插件解析子集」或作者显式 `matrix=` 表。
**v1 优先路径:** 电路用**表 + 方法**;`$$` 作文档展示;矩阵核对可放 **Q3**。
- v1:**具名门**以插件内置酉矩阵为准;`matrix=` 可从嵌套 list / `$$` 矩阵围栏构造自定义门。
- `$$` 含 `[[…]]` 或 `\begin{pmatrix}` 时解析期求值为数值 list;标量公式仍为 `Formula`。
- `matches_matrix` 仍可用于核对。
---
## 5. 作者面 API(锁定草图)
+3 -2
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Q0–Q5 最小 + Q5.5 振幅阻尼已落地**(更大 n / 完整开放系统另文) |
| 状态 | **Q0–Q6 已落地**(含公式自定义门;更大 n / 完整开放系统另文) |
| 日期 | 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) |
@@ -29,8 +29,9 @@
| **Q4** | 概率条 / 布洛赫;`matches_matrix`;examples + 用户文档 | **done** |
| **Q5** | 教学噪声 + barrier/measure/append/state — [ext-quantum-q5.md](../design/ext-quantum-q5.md) | **done(最小)** |
| **Q5.5** | `amplitude_damping` 轨迹 — [ext-quantum-q5.5.md](../design/ext-quantum-q5.5.md) | **done** |
| **Q6** | 公式/`matrix=` 自定义门 + `apply` — [ext-quantum-custom-gate.md](../design/ext-quantum-custom-gate.md) | **done** |
验收金样:`tests/ext/quantum-bell-smoke.mq.md`、`quantum-draw-smoke.mq.md`、`quantum-gate-matrix-smoke.mq.md`、`quantum-gate-heatmap-smoke.mq.md`、`quantum-author-api-smoke.mq.md`、`quantum-noise-smoke.mq.md`、`quantum-amp-damp-smoke.mq.md`、中文对称样例(`quantum-author-api-zh-smoke` / `quantum-noise-zh-smoke` / `quantum-amp-damp-zh-smoke`)。
验收金样:`tests/ext/quantum-bell-smoke.mq.md`、`quantum-draw-smoke.mq.md`、`quantum-gate-matrix-smoke.mq.md`、`quantum-gate-heatmap-smoke.mq.md`、`quantum-author-api-smoke.mq.md`、`quantum-noise-smoke.mq.md`、`quantum-amp-damp-smoke.mq.md`、`quantum-custom-gate-smoke.mq.md`、中文对称样例。
---
+15 -3
View File
@@ -118,6 +118,14 @@ Append another circuit's ops or a `{gate,qubits}` op map.
**> quantum_append circuit=`self` op=`op`**
## apply
+ `gate`
+ `qubits`=0
Apply a gate handle (named or custom `matrix=`) on `qubits` (int or list).
**> quantum_apply circuit=`self` gate=`gate` qubits=`qubits`**
## noise
+ `kind`
+ `p`
@@ -162,13 +170,17 @@ Circuit rail / probability bars / Bloch sphere SVG (`kind=circuit|probs|bloch`).
**> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit`**
# gate
+ `name`
+ `name`=None
+ `theta`=None
+ `matrix`=None
Named gate handle (built-in unitary). Use `matches_matrix` to check an author-supplied matrix.
Named built-in gate (`name=H`) or custom unitary from `matrix=` (nested list / `$$` matrix fence). Optional `name=` label for custom gates (default `U`).
> ensure_plugin
**> quantum_gate_new name=`name` theta=`theta`**
1. `matrix`
**> quantum_gate_from_matrix matrix=`matrix` name=`name`**
2. *
**> quantum_gate_new name=`name` theta=`theta`**
## matrix
+15 -3
View File
@@ -118,6 +118,14 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。
**> quantum_append circuit=`self` op=`操作`**
## 施加
+ `门`
+ `比特`=0
将门句柄(具名或 `矩阵=` 自定义)施加到 `比特`(整数或列表)。
**> quantum_apply circuit=`self` gate=`门` qubits=`比特`**
## 噪声
+ `种类`
+ `概率`
@@ -162,13 +170,17 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。
**> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特`**
# 门
+ `名`
+ `名`=None
+ `参数`=None
+ `矩阵`=None
具名门句柄。用「匹配矩阵」核对作者给出的矩阵。
具名内置门(`名=H`)或由 `矩阵=`(嵌套 list / `$$` 矩阵围栏)定义的自定义酉门。自定义门可选 `名=`(默认 `U`)。
> 确保插件
**> quantum_gate_new name=`名` theta=`参数`**
1. `矩阵`
**> quantum_gate_from_matrix matrix=`矩阵` name=`名`**
2. *
**> quantum_gate_new name=`名` theta=`参数`**
## 矩阵
+48 -28
View File
@@ -470,11 +470,21 @@ q_ffi!(quantum_draw_circuit, |args: &Value| {
});
q_ffi!(quantum_gate_new, |args: &Value| {
let matrix = args.get("matrix").or_else(|| args.get("矩阵"));
if let Some(m) = matrix {
if !m.is_null() {
let name = args
.get("name")
.or_else(|| args.get("名"))
.and_then(|v| v.as_str());
return sim::gate_from_matrix(m, name);
}
}
let name = args
.get("name")
.or_else(|| args.get("名"))
.and_then(|v| v.as_str())
.ok_or_else(|| "gate needs `name`".to_string())?;
.ok_or_else(|| "gate needs `name` or `matrix`".to_string())?;
let theta = match args.get("theta").or_else(|| args.get("参数")) {
None | Some(Value::Null) => None,
Some(v) => Some(
@@ -486,21 +496,24 @@ q_ffi!(quantum_gate_new, |args: &Value| {
sim::gate_new(name, theta)
});
q_ffi!(quantum_gate_from_matrix, |args: &Value| {
let matrix = args
.get("matrix")
.or_else(|| args.get("矩阵"))
.ok_or_else(|| "missing `matrix`".to_string())?;
let name = args
.get("name")
.or_else(|| args.get("名"))
.and_then(|v| v.as_str());
sim::gate_from_matrix(matrix, name)
});
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)?;
let m = sim::gate_matrix_of(gate)?;
Ok(sim::matrix_to_json(&m))
});
@@ -509,15 +522,6 @@ q_ffi!(quantum_gate_matches_matrix, |args: &Value| {
.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("矩阵"))
@@ -527,7 +531,7 @@ q_ffi!(quantum_gate_matches_matrix, |args: &Value| {
.or_else(|| args.get("容差"))
.and_then(|v| v.as_f64())
.unwrap_or(1e-9);
let expect = sim::named_gate_matrix(name, theta)?;
let expect = sim::gate_matrix_of(gate)?;
let got = sim::parse_matrix(matrix)?;
Ok(json!(sim::matrices_close(&expect, &got, tol)))
});
@@ -542,10 +546,6 @@ q_ffi!(quantum_gate_draw, |args: &Value| {
.or_else(|| gate.get("名"))
.and_then(|v| v.as_str())
.unwrap_or("?");
let theta = gate
.get("theta")
.or_else(|| gate.get("参数"))
.and_then(|v| v.as_f64());
let kind = args
.get("kind")
.or_else(|| args.get("种类"))
@@ -559,7 +559,7 @@ q_ffi!(quantum_gate_draw, |args: &Value| {
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
let (kind_out, svg) = if matches!(kind.as_str(), "matrix" | "heatmap" | "矩阵") {
let m = sim::named_gate_matrix(name, theta)?;
let m = sim::gate_matrix_of(gate)?;
(
"matrix",
draw::matrix_heatmap_svg(&m, &format!("{name} matrix")),
@@ -577,6 +577,16 @@ q_ffi!(quantum_gate_draw, |args: &Value| {
}))
});
q_ffi!(quantum_apply, |args: &Value| {
let c = circuit_of(args)?;
let gate = args
.get("gate")
.or_else(|| args.get("门"))
.ok_or_else(|| "missing `gate`".to_string())?;
let qubits = args.get("qubits").or_else(|| args.get("比特"));
sim::apply_gate(c, gate, qubits)
});
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
let register = match host.register_fn {
Some(f) => f,
@@ -658,7 +668,12 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
"circuit,path,kind,qubit",
quantum_draw_circuit as PluginFn,
),
("quantum_gate_new", "name,theta", quantum_gate_new as PluginFn),
("quantum_gate_new", "name,theta,matrix", quantum_gate_new as PluginFn),
(
"quantum_gate_from_matrix",
"matrix,name",
quantum_gate_from_matrix as PluginFn,
),
(
"quantum_gate_matrix",
"gate",
@@ -671,9 +686,14 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
),
(
"quantum_gate_draw",
"gate,path",
"gate,path,kind",
quantum_gate_draw as PluginFn,
),
(
"quantum_apply",
"circuit,gate,qubits",
quantum_apply as PluginFn,
),
];
for (name, params, f) in regs {
if register(host, name, params, f) != 0 {
+346 -81
View File
@@ -290,6 +290,96 @@ pub struct Op {
pub gate: String,
pub qubits: Vec<usize>,
pub theta: Option<f64>,
/// Custom unitary (row-major). When set, overrides named-gate dispatch.
pub matrix: Option<Vec<Vec<C>>>,
}
pub fn op_to_json(op: &Op) -> Value {
let mut m = json!({
"gate": op.gate,
"qubits": op.qubits,
});
if let Some(t) = op.theta {
m.as_object_mut()
.unwrap()
.insert("theta".into(), json!(t));
}
if let Some(ref mat) = op.matrix {
m.as_object_mut()
.unwrap()
.insert("matrix".into(), matrix_to_json(mat));
}
m
}
fn parse_op_row(row: &Value) -> Result<Op, String> {
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::<Result<Vec<_>, _>>()?,
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)) => {
let t = s.trim();
if t.is_empty() {
vec![]
} else {
parse_qubit_list(s)?
}
}
Some(Value::Null) => vec![],
None => {
if is_meta_gate(&gate) {
vec![]
} else if let Some(q) = row
.get("qubit")
.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"));
}
}
_ => return Err(format!("op `{gate}` bad qubits")),
};
let theta = row
.get("theta")
.or_else(|| row.get("参数"))
.or_else(|| row.get("params"))
.and_then(|v| parse_theta_value(v).ok().flatten());
let matrix = match row.get("matrix").or_else(|| row.get("矩阵")) {
None | Some(Value::Null) => None,
Some(v) => Some(parse_matrix(v)?),
};
Ok(Op {
gate,
qubits,
theta,
matrix,
})
}
pub fn parse_ops(circuit: &Value) -> Result<Vec<Op>, String> {
@@ -300,64 +390,7 @@ pub fn parse_ops(circuit: &Value) -> Result<Vec<Op>, String> {
.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::<Result<Vec<_>, _>>()?,
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)) => {
let t = s.trim();
if t.is_empty() {
vec![]
} else {
parse_qubit_list(s)?
}
}
Some(Value::Null) => vec![],
None => {
if is_meta_gate(&gate) {
vec![]
} else if let Some(q) = row
.get("qubit")
.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"));
}
}
_ => return Err(format!("op `{gate}` bad qubits")),
};
let theta = row
.get("theta")
.or_else(|| row.get("参数"))
.or_else(|| row.get("params"))
.and_then(|v| parse_theta_value(v).ok().flatten());
out.push(Op { gate, qubits, theta });
out.push(parse_op_row(&row)?);
}
Ok(out)
}
@@ -379,6 +412,9 @@ pub fn apply_op(amps: &mut [C], qubits: usize, op: &Op) -> Result<(), String> {
return Err(format!("qubit {q} out of range for n={qubits}"));
}
}
if let Some(ref mat) = op.matrix {
return apply_unitary(amps, &op.qubits, mat);
}
match op.gate.as_str() {
"BARRIER" | "MEASURE" | "M" => Ok(()),
"I" | "ID" | "IDENTITY" => {
@@ -456,11 +492,69 @@ pub fn apply_op(amps: &mut [C], qubits: usize, op: &Op) -> Result<(), String> {
Ok(())
}
other => Err(format!(
"unsupported gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP/BARRIER/MEASURE)"
"unsupported gate `{other}` (I/X/Y/Z/H/S/T/Rx/Ry/Rz/CX/CZ/SWAP/BARRIER/MEASURE or custom matrix)"
)),
}
}
/// Apply a `2^k × 2^k` unitary on `targets` (targets[0] = LSB of matrix index).
pub fn apply_unitary(amps: &mut [C], targets: &[usize], u: &[Vec<C>]) -> Result<(), String> {
let k = targets.len();
if k == 0 {
return Err("unitary needs at least one qubit".into());
}
let mut seen = Vec::new();
for &q in targets {
if seen.contains(&q) {
return Err("unitary qubits must be unique".into());
}
seen.push(q);
}
let dim = 1usize << k;
if u.len() != dim || u.iter().any(|r| r.len() != dim) {
return Err(format!(
"unitary matrix must be {dim}x{dim} for {} qubit(s)",
k
));
}
let n = amps.len();
for i in 0..n {
let mut sub = 0usize;
for (b, &q) in targets.iter().enumerate() {
if bit(i, q) {
sub |= 1 << b;
}
}
if sub != 0 {
continue;
}
let mut idxs = vec![0usize; dim];
let mut vin = vec![C::zero(); dim];
for s in 0..dim {
let mut idx = i;
for (b, &q) in targets.iter().enumerate() {
if (s >> b) & 1 == 1 {
idx = flip(idx, q);
}
}
idxs[s] = idx;
vin[s] = amps[idx];
}
let mut vout = vec![C::zero(); dim];
for r in 0..dim {
let mut sum = C::zero();
for c in 0..dim {
sum = sum.add(u[r][c].mul(vin[c]));
}
vout[r] = sum;
}
for s in 0..dim {
amps[idxs[s]] = vout[s];
}
}
Ok(())
}
pub fn is_meta_gate(gate: &str) -> bool {
matches!(
gate.to_ascii_uppercase().as_str(),
@@ -756,21 +850,7 @@ pub fn circuit_new(qubits: usize, steps: Option<&Value>) -> Result<Value, String
}
}
}
let ops_json: Vec<Value> = ops
.into_iter()
.map(|op| {
let mut m = json!({
"gate": op.gate,
"qubits": op.qubits,
});
if let Some(t) = op.theta {
m.as_object_mut()
.unwrap()
.insert("theta".into(), json!(t));
}
m
})
.collect();
let ops_json: Vec<Value> = ops.into_iter().map(|op| op_to_json(&op)).collect();
Ok(json!({
"qubits": qubits,
"ops": ops_json,
@@ -838,6 +918,7 @@ pub fn ops_from_steps(steps: &Value) -> Result<Vec<Op>, String> {
gate,
qubits: qs,
theta,
matrix: None,
});
}
Ok(out)
@@ -882,6 +963,7 @@ fn op_from_step_row(row: &Value) -> Result<Op, String> {
gate,
qubits,
theta,
matrix: None,
})
}
@@ -1030,13 +1112,7 @@ pub fn append(circuit: &Value, op: &Value) -> Result<Value, String> {
return Err(format!("append qubit {q} out of range for n={n}"));
}
}
let mut row = json!({ "gate": p.gate, "qubits": p.qubits });
if let Some(t) = p.theta {
row.as_object_mut()
.unwrap()
.insert("theta".into(), json!(t));
}
ops.push(row);
ops.push(op_to_json(&p));
}
} else if op.get("name").or_else(|| op.get("名")).is_some() {
return Err("append gate handle needs an op with qubits; pass a circuit or {{gate,qubits}}".into());
@@ -1179,6 +1255,12 @@ fn parse_complex_cell(v: &Value) -> Result<C, String> {
n.as_f64().ok_or_else(|| "bad matrix cell".to_string())?,
0.0,
)),
Value::String(s) => {
let t = s.trim();
t.parse::<f64>()
.map(|f| C::new(f, 0.0))
.map_err(|_| format!("matrix cell string not a number: `{s}`"))
}
Value::Object(map) => {
let re = map
.get("re")
@@ -1296,6 +1378,176 @@ pub fn gate_new(name: &str, theta: Option<f64>) -> Result<Value, String> {
Ok(out)
}
fn is_power_of_two(n: usize) -> bool {
n > 0 && (n & (n - 1)) == 0
}
pub fn check_unitary(m: &[Vec<C>], tol: f64) -> Result<(), String> {
let n = m.len();
if n == 0 || m.iter().any(|r| r.len() != n) {
return Err("matrix must be square".into());
}
// U† U ≈ I
for i in 0..n {
for j in 0..n {
let mut re = 0.0;
let mut im = 0.0;
for k in 0..n {
// (U†)_{ik} = conj(U_ki); sum_k conj(U_ki)*U_kj
let a = m[k][i];
let b = m[k][j];
re += a.re * b.re + a.im * b.im;
im += a.re * b.im - a.im * b.re;
}
let expect = if i == j { 1.0 } else { 0.0 };
if (re - expect).abs() > tol || im.abs() > tol {
return Err(format!(
"matrix not unitary within tol={tol} (U†U[{i},{j}]≈{re}+{im}i)"
));
}
}
}
Ok(())
}
/// Build a custom gate handle from a nested matrix (or table).
pub fn gate_from_matrix(matrix: &Value, name: Option<&str>) -> Result<Value, String> {
let m = parse_matrix(matrix)?;
let n = m.len();
if !is_power_of_two(n) {
return Err(format!(
"gate matrix size {n} must be a power of two (2^k × 2^k)"
));
}
check_unitary(&m, 1e-6)?;
let label = name
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.unwrap_or("U")
.to_string();
Ok(json!({
"name": label,
"custom": true,
"matrix": matrix_to_json(&m),
}))
}
pub fn gate_matrix_of(gate: &Value) -> Result<Vec<Vec<C>>, String> {
if let Some(m) = gate.get("matrix").or_else(|| gate.get("矩阵")) {
if !m.is_null() {
return parse_matrix(m);
}
}
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());
named_gate_matrix(name, theta)
}
fn parse_qubits_arg(v: Option<&Value>) -> Result<Vec<usize>, String> {
match v {
None | Some(Value::Null) => Ok(vec![0]),
Some(Value::Number(n)) => {
let u = n
.as_u64()
.or_else(|| n.as_i64().map(|i| i as u64))
.ok_or_else(|| "bad qubits".to_string())? as usize;
Ok(vec![u])
}
Some(Value::Array(a)) => a
.iter()
.map(|x| {
x.as_u64()
.or_else(|| x.as_i64().map(|i| i as u64))
.ok_or_else(|| "bad qubit index".to_string())
.map(|u| u as usize)
})
.collect(),
Some(Value::String(s)) => parse_qubit_list(s),
_ => Err("qubits must be int or list".into()),
}
}
/// Apply a gate handle (named or custom matrix) onto a circuit.
pub fn apply_gate(circuit: &Value, gate: &Value, qubits: Option<&Value>) -> Result<Value, String> {
let qs = parse_qubits_arg(qubits)?;
let name = gate
.get("name")
.or_else(|| gate.get("名"))
.and_then(|v| v.as_str())
.unwrap_or("U");
let custom = gate
.get("custom")
.and_then(|v| v.as_bool())
.unwrap_or(false)
|| gate.get("matrix").or_else(|| gate.get("矩阵")).is_some_and(|m| !m.is_null());
if custom {
let mat = gate_matrix_of(gate)?;
let dim = mat.len();
let k = (dim as f64).log2() as usize;
if 1usize << k != dim {
return Err("custom gate matrix size must be 2^k".into());
}
if qs.len() != k {
return Err(format!(
"custom gate is {k}-qubit (matrix {dim}x{dim}); got {} qubit index(es)",
qs.len()
));
}
let n = circuit
.get("qubits")
.and_then(|v| v.as_u64())
.ok_or_else(|| "circuit missing qubits".to_string())? as usize;
for &q in &qs {
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();
ops.push(op_to_json(&Op {
gate: name.to_ascii_uppercase(),
qubits: qs,
theta: None,
matrix: Some(mat),
}));
obj.insert("ops".into(), Value::Array(ops));
return Ok(Value::Object(obj));
}
let theta = gate
.get("theta")
.or_else(|| gate.get("参数"))
.and_then(|v| v.as_f64());
let g = name.trim().to_ascii_uppercase();
let mat = named_gate_matrix(&g, theta)?;
let k = {
let mut k = 0usize;
let mut d = mat.len();
while d > 1 {
if d % 2 != 0 {
return Err(format!("gate `{g}` matrix size not power of two"));
}
d /= 2;
k += 1;
}
k
};
if qs.len() != k {
return Err(format!("gate `{g}` needs {k} qubit(s), got {}", qs.len()));
}
push_op(circuit, &g, qs, theta)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1320,4 +1572,17 @@ mod tests {
];
assert!(matrices_close(&m, &expect, 1e-12));
}
#[test]
fn custom_h_unitary_on_zero() {
let s = std::f64::consts::FRAC_1_SQRT_2;
let u = vec![
vec![C::new(s, 0.0), C::new(s, 0.0)],
vec![C::new(s, 0.0), C::new(-s, 0.0)],
];
let mut amps = zero_state(1);
apply_unitary(&mut amps, &[0], &u).unwrap();
assert!((amps[0].norm_sq() - 0.5).abs() < 1e-12);
assert!((amps[1].norm_sq() - 0.5).abs() < 1e-12);
}
}
+348
View File
@@ -22,6 +22,11 @@ pub enum Expr {
name: String,
args: Vec<Expr>,
},
/// Matrix from a `$$` fence (LaTeX / `[[…]]`). `source` is for display; `rows` for eval/JSON.
Matrix {
source: String,
rows: Vec<Vec<f64>>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -80,6 +85,7 @@ impl Expr {
let joined: Vec<String> = args.iter().map(|a| a.as_display()).collect();
format!("{name}({})", joined.join(", "))
}
Expr::Matrix { source, .. } => source.clone(),
}
}
}
@@ -383,6 +389,10 @@ pub fn simplify(e: &Expr) -> Expr {
args,
}
}
Expr::Matrix { source, rows } => Expr::Matrix {
source: source.clone(),
rows: rows.clone(),
},
}
}
@@ -671,6 +681,7 @@ fn diff_raw(e: &Expr, var: &str) -> Expr {
_ => Expr::Num(0.0),
}
}
Expr::Matrix { .. } => Expr::Num(0.0),
}
}
@@ -698,6 +709,10 @@ fn subs_raw(e: &Expr, var: &str, value: &Expr) -> Expr {
name: name.clone(),
args: args.iter().map(|a| subs_raw(a, var, value)).collect(),
},
Expr::Matrix { source, rows } => Expr::Matrix {
source: source.clone(),
rows: rows.clone(),
},
}
}
@@ -732,6 +747,7 @@ pub fn eval_f64(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, String> {
}
eval_call_f64(name, &xs).ok_or_else(|| format!("unknown or arity-mismatch function `{name}`"))
}
Expr::Matrix { .. } => Err("cannot evaluate matrix as a scalar".into()),
}
}
@@ -936,6 +952,318 @@ fn push_unique(xs: &mut Vec<f64>, x: f64) {
xs.push(x);
}
/// True if `$$` body looks like a matrix (ASCII `[[` or LaTeX pmatrix/bmatrix).
pub fn looks_like_matrix(input: &str) -> bool {
let t = input.trim();
t.contains("[[")
|| t.contains("\\begin{pmatrix}")
|| t.contains("\\begin{bmatrix}")
|| t.contains("\\begin{matrix}")
}
fn replace_latex_cmd(s: &str, cmd: &str, open: char, close: char) -> Result<String, String> {
let needle = format!("\\{cmd}");
let mut out = String::new();
let mut i = 0;
let bytes = s.as_bytes();
while i < s.len() {
if s[i..].starts_with(&needle) {
i += needle.len();
while i < s.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i >= s.len() || s[i..].chars().next() != Some(open) {
return Err(format!("\\{cmd} needs `{{{open}…{close}}}`"));
}
i += open.len_utf8();
let start = i;
let mut depth = 1;
while i < s.len() {
let c = s[i..].chars().next().unwrap();
if c == open {
depth += 1;
} else if c == close {
depth -= 1;
if depth == 0 {
break;
}
}
i += c.len_utf8();
}
if depth != 0 {
return Err(format!("unclosed \\{cmd}{{…}}"));
}
let inner = &s[start..i];
i += close.len_utf8();
let inner_norm = normalize_latex_math(inner)?;
match cmd {
"frac" => {
// frac has two braced args — this helper only got first; handled separately
out.push_str(&inner_norm);
}
"sqrt" => {
out.push_str("sqrt(");
out.push_str(&inner_norm);
out.push(')');
}
_ => out.push_str(&inner_norm),
}
} else {
let c = s[i..].chars().next().unwrap();
out.push(c);
i += c.len_utf8();
}
}
Ok(out)
}
fn normalize_frac(s: &str) -> Result<String, String> {
let mut out = String::new();
let mut i = 0;
while i < s.len() {
if s[i..].starts_with("\\frac") {
i += "\\frac".len();
while i < s.len() && s.as_bytes()[i].is_ascii_whitespace() {
i += 1;
}
let (num, ni) = read_brace_group(s, i)?;
i = ni;
while i < s.len() && s.as_bytes()[i].is_ascii_whitespace() {
i += 1;
}
let (den, di) = read_brace_group(s, i)?;
i = di;
let num = normalize_latex_math(&num)?;
let den = normalize_latex_math(&den)?;
out.push_str(&format!("(({num})/({den}))"));
} else {
let c = s[i..].chars().next().unwrap();
out.push(c);
i += c.len_utf8();
}
}
Ok(out)
}
fn read_brace_group(s: &str, mut i: usize) -> Result<(String, usize), String> {
if i >= s.len() || !s[i..].starts_with('{') {
return Err("expected `{` group".into());
}
i += 1;
let start = i;
let mut depth = 1;
while i < s.len() {
let c = s[i..].chars().next().unwrap();
if c == '{' {
depth += 1;
} else if c == '}' {
depth -= 1;
if depth == 0 {
let inner = s[start..i].to_string();
return Ok((inner, i + 1));
}
}
i += c.len_utf8();
}
Err("unclosed `{`".into())
}
fn normalize_begin_matrix(s: &str) -> Result<String, String> {
let envs = ["pmatrix", "bmatrix", "matrix"];
let mut out = String::new();
let mut i = 0;
while i < s.len() {
let mut matched = false;
for env in envs {
let open = format!("\\begin{{{env}}}");
let close = format!("\\end{{{env}}}");
if s[i..].starts_with(&open) {
i += open.len();
let start = i;
let Some(rel) = s[i..].find(&close) else {
return Err(format!("missing \\end{{{env}}}"));
};
let body = s[start..start + rel].trim();
i = start + rel + close.len();
let body = normalize_latex_math(body)?;
let rows: Vec<&str> = body
.split("\\\\")
.map(|r| r.trim())
.filter(|r| !r.is_empty())
.collect();
let mut mat = String::from("[[");
for (ri, row) in rows.iter().enumerate() {
if ri > 0 {
mat.push_str("],[");
}
let cells: Vec<&str> = row.split('&').map(|c| c.trim()).collect();
for (ci, cell) in cells.iter().enumerate() {
if ci > 0 {
mat.push(',');
}
mat.push_str(cell);
}
}
mat.push_str("]]");
// Implicit multiply if previous token is `)` / digit / `}`
if out
.chars()
.rev()
.find(|c| !c.is_whitespace())
.is_some_and(|c| c.is_ascii_alphanumeric() || c == ')' || c == '}')
{
out.push('*');
}
out.push_str(&mat);
matched = true;
break;
}
}
if !matched {
let c = s[i..].chars().next().unwrap();
out.push(c);
i += c.len_utf8();
}
}
Ok(out)
}
fn normalize_latex_math(s: &str) -> Result<String, String> {
let s = s.replace('\n', " ");
let s = normalize_frac(&s)?;
let s = replace_latex_cmd(&s, "sqrt", '{', '}')?;
let s = normalize_begin_matrix(&s)?;
// leftover common no-ops
let s = s.replace("\\left", "").replace("\\right", "");
Ok(s)
}
fn eval_cell(expr: &str) -> Result<f64, String> {
let e = parse(expr.trim())?;
eval_f64(&simplify(&e), &HashMap::new())
}
fn parse_bracket_matrix(s: &str) -> Result<Vec<Vec<f64>>, String> {
let t = s.trim();
if !t.starts_with("[[") || !t.ends_with("]]") {
return Err("matrix must look like [[…],[…]]".into());
}
let inner = &t[2..t.len() - 2];
// Split rows on "],[" at top level
let mut rows_s: Vec<String> = Vec::new();
let mut cur = String::new();
let mut depth = 0i32;
let chars: Vec<char> = inner.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i] == ']'
&& depth == 0
&& i + 2 < chars.len()
&& chars[i + 1] == ','
&& chars[i + 2] == '['
{
rows_s.push(cur.clone());
cur.clear();
i += 3;
continue;
}
let c = chars[i];
if c == '[' {
depth += 1;
} else if c == ']' {
depth -= 1;
}
cur.push(c);
i += 1;
}
rows_s.push(cur);
let mut rows = Vec::new();
for row in rows_s {
let row = row.trim().trim_matches(|c| c == '[' || c == ']');
let mut cells = Vec::new();
let mut cell = String::new();
let mut depth = 0i32;
for c in row.chars() {
match c {
'(' | '[' => {
depth += 1;
cell.push(c);
}
')' | ']' => {
depth -= 1;
cell.push(c);
}
',' if depth == 0 => {
cells.push(eval_cell(&cell)?);
cell.clear();
}
_ => cell.push(c),
}
}
if !cell.trim().is_empty() {
cells.push(eval_cell(&cell)?);
}
if cells.is_empty() {
return Err("empty matrix row".into());
}
rows.push(cells);
}
if rows.is_empty() {
return Err("empty matrix".into());
}
let w = rows[0].len();
if rows.iter().any(|r| r.len() != w) {
return Err("matrix rows must have equal length".into());
}
Ok(rows)
}
fn scale_matrix(m: &[Vec<f64>], s: f64) -> Vec<Vec<f64>> {
m.iter()
.map(|row| row.iter().map(|x| x * s).collect())
.collect()
}
/// Parse ASCII / LaTeX matrix source into numeric rows (constant-fold cells).
pub fn parse_eval_matrix(input: &str) -> Result<Vec<Vec<f64>>, String> {
let norm = normalize_latex_math(input)?.trim().to_string();
// scalar * [[…]] or [[…]] * scalar or bare [[…]]
if let Some(idx) = norm.find("[[") {
let before = norm[..idx].trim();
let rest = &norm[idx..];
let end = rest
.rfind("]]")
.ok_or_else(|| "unclosed [[ matrix".to_string())?;
let mat_s = &rest[..=end + 1];
let after = rest[end + 2..].trim();
let mat = parse_bracket_matrix(mat_s)?;
let mut scale = 1.0;
if before.ends_with('*') {
let expr = before.trim_end_matches('*').trim();
if !expr.is_empty() {
scale *= eval_cell(expr)?;
}
} else if !before.is_empty() {
return Err(format!("unexpected prefix before matrix: `{before}`"));
}
if after.starts_with('*') {
let expr = after.trim_start_matches('*').trim();
if !expr.is_empty() {
scale *= eval_cell(expr)?;
}
} else if !after.is_empty() {
return Err(format!("unexpected suffix after matrix: `{after}`"));
}
Ok(if (scale - 1.0).abs() < 1e-15 {
mat
} else {
scale_matrix(&mat, scale)
})
} else {
Err("no [[…]] matrix found after LaTeX normalize".into())
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -958,4 +1286,24 @@ mod tests {
env.insert("x".into(), 0.0);
assert!((eval_f64(&e, &env).unwrap()).abs() < 1e-12);
}
#[test]
fn latex_hadamard_matrix() {
let m = parse_eval_matrix(
r"\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}",
)
.unwrap();
let s = std::f64::consts::FRAC_1_SQRT_2;
assert_eq!(m.len(), 2);
assert!((m[0][0] - s).abs() < 1e-12);
assert!((m[0][1] - s).abs() < 1e-12);
assert!((m[1][0] - s).abs() < 1e-12);
assert!((m[1][1] + s).abs() < 1e-12);
}
#[test]
fn ascii_pauli_z() {
let m = parse_eval_matrix("[[1,0],[0,-1]]").unwrap();
assert_eq!(m, vec![vec![1.0, 0.0], vec![0.0, -1.0]]);
}
}
+27 -1
View File
@@ -118,7 +118,33 @@ pub(crate) fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
}
serde_json::Value::Object(map)
}
Value::Formula(e) => serde_json::Value::String(e.as_display()),
Value::Formula(e) => match e {
crate::formula::Expr::Matrix { rows, .. } => {
let mut arr = Vec::with_capacity(rows.len());
for row in rows {
let mut cells = Vec::with_capacity(row.len());
for &n in row {
cells.push(
serde_json::Number::from_f64(n)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null),
);
}
arr.push(serde_json::Value::Array(cells));
}
serde_json::Value::Array(arr)
}
other => {
let s = crate::formula::simplify(other);
if let crate::formula::Expr::Num(n) = s {
serde_json::Number::from_f64(n)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null)
} else {
serde_json::Value::String(e.as_display())
}
}
},
Value::Code(c) => serde_json::Value::String(c.source.clone()),
})
}
+22 -8
View File
@@ -439,9 +439,11 @@ impl<'a> Cursor<'a> {
if body.is_empty() {
bail!("{open_line}:1: empty formula");
}
let expr = crate::formula::parse(body)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
return Ok((Expr::Formula(expr), open_line));
return Ok((
formula_fence_to_expr(body)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?,
open_line,
));
}
if trimmed != "$$" {
bail!(
@@ -468,9 +470,9 @@ impl<'a> Cursor<'a> {
if text.is_empty() {
bail!("{open_line}:1: empty formula");
}
let expr = crate::formula::parse(&text)
let expr = formula_fence_to_expr(&text)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
Ok((Expr::Formula(expr), end_line))
Ok((expr, end_line))
}
/// GFM table after empty RHS:
@@ -712,7 +714,7 @@ fn is_bare_assign_ident(s: &str) -> bool {
true
}
/// Same-line `$$body$$` → Formula; otherwise None (caller parses normally).
/// Same-line `$$body$$` → Formula or numeric matrix List; otherwise None.
fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
let rhs = rhs.trim();
if !rhs.starts_with("$$") {
@@ -728,12 +730,24 @@ fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
if body.is_empty() {
bail!("empty formula");
}
let expr = crate::formula::parse(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
return Ok(Some(Expr::Formula(expr)));
let expr = formula_fence_to_expr(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
return Ok(Some(expr));
}
bail!("incomplete inline formula (expected `$$…$$` on one line)");
}
fn formula_fence_to_expr(body: &str) -> Result<Expr, String> {
if crate::formula::looks_like_matrix(body) {
let rows = crate::formula::parse_eval_matrix(body)?;
return Ok(Expr::Formula(crate::formula::Expr::Matrix {
source: body.trim().to_string(),
rows,
}));
}
let expr = crate::formula::parse(body)?;
Ok(Expr::Formula(expr))
}
fn parse_backtick_ident(s: &str) -> Option<String> {
let s = s.trim();
if !s.starts_with('`') {
+286 -20
View File
@@ -427,35 +427,89 @@ section.block > h2 {
box-shadow: none;
}
.vars-panel {
max-height: min(50vh, 28rem);
max-height: min(52vh, 30rem);
overflow: auto;
font: 0.72rem/1.35 var(--mono);
font: 0.72rem/1.35 var(--sans);
padding-right: 0.1rem;
}
.vars-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.vars-item {
margin: 0 0 0.55rem;
padding-bottom: 0.45rem;
border-bottom: 1px solid var(--line);
.vars-card {
display: block;
margin: 0;
padding: 0.45rem 0.5rem 0.5rem;
border: 1px solid var(--line);
border-radius: 10px;
background: #fff;
cursor: pointer;
transition: border-color 0.12s ease, box-shadow 0.12s ease;
}
.vars-item:last-child {
margin-bottom: 0;
padding-bottom: 0;
border-bottom: none;
.vars-card:hover {
border-color: #a1a1a6;
box-shadow: 0 4px 14px rgba(0,0,0,0.06);
}
.vars-card:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
.vars-head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.25rem 0.55rem;
margin-bottom: 0.35rem;
}
.vars-name {
font-weight: 600;
font: 600 0.8rem/1.25 var(--mono);
color: var(--ink);
margin-bottom: 0.2rem;
word-break: break-all;
}
.vars-kind {
font: 500 0.65rem/1.2 var(--sans);
color: var(--muted);
}
.vars-preview {
max-height: 7.5rem;
overflow: hidden;
position: relative;
border-radius: 8px;
background: #fafafa;
border: 1px solid var(--line);
padding: 0.35rem;
pointer-events: none;
}
.vars-preview::after {
content: "";
position: absolute;
left: 0; right: 0; bottom: 0;
height: 1.6rem;
background: linear-gradient(transparent, #fafafa);
pointer-events: none;
}
.vars-preview .matrix-wrap {
border: none;
padding: 0.25rem;
background: transparent;
}
.vars-preview .matrix-cell {
min-width: 2.4rem;
padding: 0.28rem 0.35rem;
font-size: 0.68rem;
}
.vars-muted { color: var(--muted); }
.vars-peek { font-size: 0.68rem; }
.math-sm .katex-display { font-size: 0.92em; margin: 0.1rem 0; }
.vars-table {
width: 100%;
border-collapse: collapse;
font: inherit;
font: 0.72rem/1.35 var(--mono);
}
.vars-table th,
.vars-table td {
@@ -474,6 +528,120 @@ section.block > h2 {
.vars-scalar { white-space: pre-wrap; }
.vars-empty, .vars-skipped { color: var(--muted); margin: 0.2rem 0; }
.vars-nested > summary { cursor: pointer; color: var(--muted); }
.var-dialog {
border: none;
padding: 0;
max-width: min(920px, 94vw);
max-height: min(88vh, 900px);
width: min(920px, 94vw);
border-radius: 18px;
background: transparent;
box-shadow: none;
}
.var-dialog::backdrop {
background: rgba(29, 29, 31, 0.42);
backdrop-filter: blur(6px);
}
.var-dialog-sheet {
background: linear-gradient(180deg, #fffef9 0%, #ffffff 42%);
border: 1px solid var(--line);
border-radius: 18px;
box-shadow: 0 24px 80px rgba(0,0,0,0.22);
overflow: hidden;
display: flex;
flex-direction: column;
max-height: min(88vh, 900px);
}
.var-dialog-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.15rem;
border-bottom: 1px solid var(--line);
background: rgba(255,255,255,0.85);
}
.var-dialog-head h2 {
margin: 0;
font: 650 1.05rem/1.25 var(--mono);
color: var(--ink);
word-break: break-all;
}
.var-dialog-close {
appearance: none;
width: 2rem;
height: 2rem;
border-radius: 999px;
border: 1px solid var(--line);
background: #f5f5f7;
color: var(--ink);
font-size: 1.15rem;
line-height: 1;
cursor: pointer;
}
.var-dialog-close:hover { background: var(--hover); }
.var-dialog-body {
padding: 1.15rem 1.25rem 1.4rem;
overflow: auto;
font: 0.85rem/1.45 var(--sans);
}
.var-rich-meta {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin: 0 0 0.85rem;
}
.var-chip {
display: inline-block;
padding: 0.2rem 0.55rem;
border-radius: 999px;
background: #1d1d1f;
color: #fff;
font: 600 0.68rem/1.2 var(--sans);
}
.var-chip.muted {
background: #e8e8ed;
color: var(--muted);
}
.var-rich-more {
margin-top: 1rem;
color: var(--muted);
font-size: 0.78rem;
}
.matrix-wrap {
overflow: auto;
border-radius: 14px;
border: 1px solid var(--line);
background:
radial-gradient(120% 80% at 0% 0%, rgba(0,113,227,0.06), transparent 55%),
#fff;
padding: 0.75rem;
}
.matrix-cap {
caption-side: top;
text-align: left;
font: 500 0.7rem/1.2 var(--sans);
color: var(--muted);
margin-bottom: 0.45rem;
}
.matrix-grid {
border-collapse: separate;
border-spacing: 0.35rem;
margin: 0 auto;
font: 0.78rem/1.2 var(--mono);
}
.matrix-cell {
min-width: 3.6rem;
padding: 0.55rem 0.65rem;
text-align: center;
border-radius: 10px;
border: 1px solid var(--line);
background: #f7f8fa;
color: var(--ink);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.65);
}
.matrix-cell span { font-variant-numeric: tabular-nums; }
.math-lg .katex-display { font-size: 1.15em; }
.fn-search {
width: 100%;
box-sizing: border-box;
@@ -529,14 +697,16 @@ section.block > h2 {
font-weight: 500;
}
.formula-card .math-block {
display: inline-block;
margin: 0.25rem 0 0.1rem 0.25rem;
vertical-align: middle;
overflow-x: auto;
display: block;
margin: 0.35rem 0 0.1rem;
overflow: visible;
max-width: 100%;
}
.formula-card .katex-display {
margin: 0.2rem 0;
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 0.15rem;
}
.code-card {
padding: 0;
@@ -1008,7 +1178,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
<link rel="shortcut icon" href="https://s3.cflmy.cn/logo/Logo.ico" type="image/x-icon"/>
<link rel="apple-touch-icon" href="https://s3.cflmy.cn/logo/Logo.png"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" crossorigin="anonymous"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github-dark.min.css" crossorigin="anonymous"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css" crossorigin="anonymous"/>
<style>{css}</style>
</head>
<body>
@@ -1040,10 +1210,19 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
</main>
</div>
</div>
<dialog class="var-dialog" id="var-dialog" aria-labelledby="var-dialog-title">
<div class="var-dialog-sheet">
<div class="var-dialog-head">
<h2 id="var-dialog-title">Variable</h2>
<button type="button" class="var-dialog-close" id="var-dialog-close" aria-label="Close">×</button>
</div>
<div class="var-dialog-body" id="var-dialog-body"></div>
</div>
</dialog>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" crossorigin="anonymous"
onload="renderMathInElement(document.body,{{delimiters:[{{left:'$$',right:'$$',display:true}},{{left:'\\(',right:'\\)',display:false}}],ignoredTags:['script','noscript','style','textarea','pre','code','kbd']}});"></script>
<script defer src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/highlight.min.js" crossorigin="anonymous"
<script defer src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js" crossorigin="anonymous"
onload="document.querySelectorAll('pre.code-body code').forEach(function(el){{hljs.highlightElement(el);}});"></script>
<script>
(function () {{
@@ -1499,7 +1678,8 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
var vp = document.getElementById("vars-panel");
if (vp) {{
vp.innerHTML = ev.bindings_html
|| "<p class=\\"vars-empty\\">No bindings</p>";
|| '<p class="vars-empty">No bindings</p>';
initVarsPanel();
}}
}}
}}
@@ -1616,16 +1796,102 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}}
}}
function initVarsPanel() {{
var panel = document.getElementById("vars-panel");
var dialog = document.getElementById("var-dialog");
var title = document.getElementById("var-dialog-title");
var body = document.getElementById("var-dialog-body");
var closeBtn = document.getElementById("var-dialog-close");
if (!panel || !dialog || !title || !body) return;
function renderMath(root) {{
if (window.renderMathInElement) {{
try {{
window.renderMathInElement(root, {{
delimiters: [
{{ left: "$$", right: "$$", display: true }},
{{ left: "\\(", right: "\\)", display: false }}
],
ignoredTags: ["script", "noscript", "style", "textarea", "pre", "code", "kbd", "button"]
}});
}} catch (e) {{}}
}}
}}
function openVar(id) {{
var store = document.getElementById("var-full-" + id);
if (!store) return;
var name = store.getAttribute("data-var-name") || ("#" + id);
title.textContent = name;
body.innerHTML = store.innerHTML;
renderMath(body);
try {{
if (typeof dialog.showModal === "function") dialog.showModal();
else dialog.setAttribute("open", "");
}} catch (e) {{
dialog.setAttribute("open", "");
}}
}}
function closeVar() {{
try {{
if (typeof dialog.close === "function") dialog.close();
else dialog.removeAttribute("open");
}} catch (e) {{
dialog.removeAttribute("open");
}}
}}
// Event delegation: survives vars-panel innerHTML refresh after runs.
if (panel.dataset.varsBound !== "1") {{
panel.dataset.varsBound = "1";
panel.addEventListener("click", function (ev) {{
var card = ev.target.closest(".vars-card");
if (!card || !panel.contains(card)) return;
ev.preventDefault();
openVar(card.getAttribute("data-var-id"));
}});
panel.addEventListener("keydown", function (ev) {{
if (ev.key !== "Enter" && ev.key !== " ") return;
var card = ev.target.closest(".vars-card");
if (!card || !panel.contains(card)) return;
ev.preventDefault();
openVar(card.getAttribute("data-var-id"));
}});
}}
if (closeBtn && closeBtn.dataset.bound !== "1") {{
closeBtn.dataset.bound = "1";
closeBtn.addEventListener("click", function (ev) {{
ev.preventDefault();
closeVar();
}});
}}
if (dialog.dataset.bound !== "1") {{
dialog.dataset.bound = "1";
dialog.addEventListener("click", function (ev) {{
if (ev.target === dialog) closeVar();
}});
document.addEventListener("keydown", function (ev) {{
if (ev.key === "Escape" && dialog.open) closeVar();
}});
}}
renderMath(panel);
}}
if (document.readyState === "loading") {{
document.addEventListener("DOMContentLoaded", function () {{
initForeignCards();
initOutlineSearch();
initStreamPanel();
initVarsPanel();
}});
}} else {{
initForeignCards();
initOutlineSearch();
initStreamPanel();
initVarsPanel();
}}
function initOutlineSearch() {{
+377 -8
View File
@@ -301,7 +301,7 @@ pub fn render_right_rail(module: &Module, bindings_html: &str, writeback_html: &
)
}
/// Render entry bindings as HTML tables (List / Map / records).
/// Render entry bindings: visible preview in the rail; click card → inspect dialog.
pub fn render_bindings_html(bindings: &HashMap<String, crate::value::Value>) -> String {
if bindings.is_empty() {
return String::new();
@@ -309,26 +309,376 @@ pub fn render_bindings_html(bindings: &HashMap<String, crate::value::Value>) ->
let mut names: Vec<&String> = bindings.keys().collect();
names.sort();
let mut out = String::from(r#"<ul class="vars-list">"#);
for name in names {
for (i, name) in names.into_iter().enumerate() {
let Some(val) = bindings.get(name) else {
continue;
};
let kind = value_kind_label(val);
let preview = render_value_preview_html(val);
let full = render_value_rich(val, 0);
out.push_str(&format!(
r#"<li class="vars-item"><div class="vars-name">{}</div><div class="vars-value">{}</div></li>"#,
escape(name),
render_value_html(val, 0)
r#"<li class="vars-item vars-card" data-var-id="{id}" role="button" tabindex="0" title="Click to inspect">
<div class="vars-head">
<span class="vars-name">{name}</span>
<span class="vars-kind">{kind}</span>
</div>
<div class="vars-preview">{preview}</div>
<div class="vars-full" id="var-full-{id}" data-var-name="{name}" hidden>{full}</div>
</li>"#,
name = escape(name),
kind = escape(&kind),
preview = preview,
id = i,
full = full,
));
}
out.push_str("</ul>");
out
}
const BIND_MAX_DEPTH: usize = 2;
/// Compact inline preview (may truncate visually via CSS).
fn render_value_preview_html(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(r#"<div class="math-block math-sm">$${}$$</div>"#, tex)
}
Value::List(xs) => {
if let Some((_, _, complex)) = detect_matrix(xs) {
return render_matrix_grid(xs, complex);
}
render_value_html(v, 0)
}
Value::Map(pairs) => {
if let Some(Value::List(rows)) = pairs
.iter()
.find(|(k, _)| k == "matrix" || k == "矩阵")
.map(|(_, v)| v)
{
if let Some((_, _, complex)) = detect_matrix(rows) {
return render_matrix_grid(rows, complex);
}
}
// Prefer a short key/value peek for objects.
let mut s = String::from(r#"<table class="vars-table vars-peek"><tbody>"#);
for (k, val) in pairs.iter().take(6) {
if k == "matrix" || k == "矩阵" || k == "ops" {
s.push_str(&format!(
"<tr><td class=\"vars-key\">{}</td><td class=\"vars-muted\">…</td></tr>",
escape(k)
));
continue;
}
s.push_str(&format!(
"<tr><td class=\"vars-key\">{}</td><td>{}</td></tr>",
escape(k),
escape(&brief_preview_cell(val))
));
}
if pairs.len() > 6 {
s.push_str(
r#"<tr><td colspan="2" class="vars-muted">…</td></tr>"#,
);
}
s.push_str("</tbody></table>");
s
}
other => format!(
r#"<span class="vars-scalar">{}</span>"#,
escape(&other.as_display())
),
}
}
fn brief_preview_cell(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::List(xs) => format!("List({})", xs.len()),
Value::Map(xs) => format!("Map({})", xs.len()),
Value::Formula(_) => "formula".into(),
other => {
let s = other.as_display();
if s.chars().count() > 36 {
format!("{}…", s.chars().take(36).collect::<String>())
} else {
s
}
}
}
}
fn value_kind_label(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::None => "none".into(),
Value::Bool(_) => "bool".into(),
Value::Int(_) => "int".into(),
Value::Num(_) => "num".into(),
Value::Text(_) => "text".into(),
Value::Formula(crate::formula::Expr::Matrix { rows, .. }) => {
format!("formula · {}×{}", rows.len(), rows.first().map(|r| r.len()).unwrap_or(0))
}
Value::Formula(_) => "formula".into(),
Value::Code(c) => format!("code · {}", c.lang),
Value::List(xs) => {
if let Some((r, c, _)) = detect_matrix(xs) {
format!("matrix · {r}×{c}")
} else {
format!("list · {}", xs.len())
}
}
Value::Map(pairs) => {
if let Some(t) = pairs.iter().find(|(k, _)| k == "_type").and_then(|(_, v)| match v {
Value::Text(s) => Some(s.as_str()),
_ => None,
}) {
if let Some(Value::List(rows)) = pairs
.iter()
.find(|(k, _)| k == "matrix" || k == "矩阵")
.map(|(_, v)| v)
{
if let Some((r, c, _)) = detect_matrix(rows) {
return format!("{t} · {r}×{c}");
}
}
t.to_string()
} else {
format!("map · {}", pairs.len())
}
}
}
}
/// Complex or real matrix: rows × cols, and whether cells are complex maps.
fn detect_matrix(xs: &[crate::value::Value]) -> Option<(usize, usize, bool)> {
use crate::value::Value;
if xs.is_empty() {
return None;
}
let mut cols = None;
let mut complex = false;
for row in xs {
let Value::List(cells) = row else {
return None;
};
if cells.is_empty() {
return None;
}
match cols {
None => cols = Some(cells.len()),
Some(c) if c != cells.len() => return None,
_ => {}
}
for c in cells {
match c {
Value::Num(_) | Value::Int(_) => {}
Value::Map(m)
if m.iter().any(|(k, _)| k == "re")
&& m.iter().any(|(k, _)| k == "im") =>
{
complex = true;
}
_ => return None,
}
}
}
Some((xs.len(), cols.unwrap_or(0), complex))
}
fn format_complex_cell(v: &crate::value::Value) -> String {
use crate::value::Value;
match v {
Value::Num(n) => format_matrix_num(*n),
Value::Int(i) => i.to_string(),
Value::Map(m) => {
let re = m
.iter()
.find(|(k, _)| k == "re")
.and_then(|(_, v)| match v {
Value::Num(n) => Some(*n),
Value::Int(i) => Some(*i as f64),
_ => None,
})
.unwrap_or(0.0);
let im = m
.iter()
.find(|(k, _)| k == "im")
.and_then(|(_, v)| match v {
Value::Num(n) => Some(*n),
Value::Int(i) => Some(*i as f64),
_ => None,
})
.unwrap_or(0.0);
if im.abs() < 1e-12 {
format_matrix_num(re)
} else if re.abs() < 1e-12 {
format!("{}i", format_matrix_num(im))
} else {
format!("{}{:+}i", format_matrix_num(re), im)
}
}
other => other.as_display(),
}
}
fn format_matrix_num(n: f64) -> String {
if n.fract().abs() < 1e-12 && n.abs() < 1e15 {
format!("{}", n as i64)
} else {
let s = format!("{n:.6}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
}
fn render_matrix_grid(xs: &[crate::value::Value], complex: bool) -> String {
let mut s = String::from(r#"<div class="matrix-wrap"><table class="matrix-grid">"#);
if complex {
s.push_str(r#"<caption class="matrix-cap">complex amplitudes</caption>"#);
}
s.push_str("<tbody>");
for row in xs {
let crate::value::Value::List(cells) = row else {
continue;
};
s.push_str("<tr>");
for c in cells {
let label = escape(&format_complex_cell(c));
let mag = match c {
crate::value::Value::Num(n) => n.abs(),
crate::value::Value::Int(i) => (*i as f64).abs(),
crate::value::Value::Map(m) => {
let re = m
.iter()
.find(|(k, _)| k == "re")
.and_then(|(_, v)| match v {
crate::value::Value::Num(n) => Some(*n),
_ => None,
})
.unwrap_or(0.0);
let im = m
.iter()
.find(|(k, _)| k == "im")
.and_then(|(_, v)| match v {
crate::value::Value::Num(n) => Some(*n),
_ => None,
})
.unwrap_or(0.0);
(re * re + im * im).sqrt()
}
_ => 0.0,
};
let heat = mag.clamp(0.0, 1.0);
let bg = format!(
"rgba(74, 111, 165, {:.3})",
0.06 + heat * 0.42
);
s.push_str(&format!(
r#"<td class="matrix-cell" style="background:{bg}"><span>{label}</span></td>"#
));
}
s.push_str("</tr>");
}
s.push_str("</tbody></table></div>");
s
}
const BIND_MAX_DEPTH: usize = 3;
/// Full rich HTML for the inspect dialog (matrices get a dedicated grid).
fn render_value_rich(v: &crate::value::Value, depth: usize) -> String {
use crate::value::Value;
match v {
Value::List(xs) => {
if let Some((_, _, complex)) = detect_matrix(xs) {
return render_matrix_grid(xs, complex);
}
if let Some(keys) = record_keys(xs) {
return render_records_table(xs, &keys, depth);
}
render_value_html(v, depth)
}
Value::Map(pairs) => {
// Prefer pretty matrix when object carries `matrix` / `矩阵`.
if let Some(Value::List(rows)) = pairs
.iter()
.find(|(k, _)| k == "matrix" || k == "矩阵")
.map(|(_, v)| v)
{
if let Some((_, _, complex)) = detect_matrix(rows) {
let mut s = String::from(r#"<div class="var-rich">"#);
if let Some(Value::Text(t)) =
pairs.iter().find(|(k, _)| k == "_type").map(|(_, v)| v)
{
s.push_str(&format!(
r#"<p class="var-rich-meta"><span class="var-chip">{}</span>"#,
escape(t)
));
if let Some(Value::Text(n)) =
pairs.iter().find(|(k, _)| k == "name" || k == "名").map(|(_, v)| v)
{
s.push_str(&format!(
r#" <span class="var-chip muted">{}</span>"#,
escape(n)
));
}
s.push_str("</p>");
}
s.push_str(&render_matrix_grid(rows, complex));
// Other keys (skip matrix / _type / name noise)
let rest: Vec<_> = pairs
.iter()
.filter(|(k, _)| {
k != "matrix"
&& k != "矩阵"
&& k != "_type"
&& k != "name"
&& k != "名"
&& k != "custom"
})
.collect();
if !rest.is_empty() {
s.push_str(r#"<details class="var-rich-more"><summary>Other fields</summary>"#);
s.push_str(r#"<table class="vars-table"><tbody>"#);
for (k, val) in rest {
s.push_str(&format!(
"<tr><td class=\"vars-key\">{}</td><td>{}</td></tr>",
escape(k),
cell_html(val, depth)
));
}
s.push_str("</tbody></table></details>");
}
s.push_str("</div>");
return s;
}
}
render_value_html(v, depth)
}
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(
r#"<div class="var-rich"><div class="math-block math-lg">$${}$$</div></div>"#,
tex
)
}
other => render_value_html(other, depth),
}
}
fn render_value_html(v: &crate::value::Value, depth: usize) -> String {
use crate::value::Value;
match v {
Value::List(xs) => {
if let Some((_, _, complex)) = detect_matrix(xs) {
return render_matrix_grid(xs, complex);
}
if let Some(keys) = record_keys(xs) {
return render_records_table(xs, &keys, depth);
}
@@ -363,6 +713,13 @@ fn render_value_html(v: &crate::value::Value, depth: usize) -> String {
s.push_str("</tbody></table>");
s
}
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(r#"<div class="math-block">$${}$$</div>"#, tex)
}
other => format!(r#"<span class="vars-scalar">{}</span>"#, escape(&other.as_display())),
}
}
@@ -378,6 +735,13 @@ fn cell_html(v: &crate::value::Value, depth: usize) -> String {
)
}
Value::List(_) | Value::Map(_) => render_value_html(v, depth + 1),
Value::Formula(e) => {
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(r#"<div class="math-block">$${}$$</div>"#, tex)
}
other => escape(&other.as_display()),
}
}
@@ -740,7 +1104,12 @@ fn render_stmt(
value: Expr::Formula(e),
..
} => {
let tex = escape(&formula_ascii_to_tex(&e.as_display()));
// Matrix fences keep original LaTeX/`[[…]]` source — feed KaTeX as-is.
// Scalar ASCII formulas go through formula_ascii_to_tex.
let tex = match e {
crate::formula::Expr::Matrix { source, .. } => escape(source),
_ => escape(&formula_ascii_to_tex(&e.as_display())),
};
format!(
"<div class=\"card formula-card\"><span class=\"badge\">formula</span> \
<code class=\"expr\">`{}` =</code> \
@@ -1220,7 +1589,7 @@ mod tests {
assert!(html.contains("Functions"), "{html}");
assert!(html.contains("Variables"), "{html}");
assert!(html.contains("vars-panel"), "{html}");
assert!(html.contains("vars-table"), "{html}");
assert!(html.contains("vars-card"), "{html}");
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
}
+29
View File
@@ -0,0 +1,29 @@
---
title: quantum custom gate from formula matrix
description: $$ H matrix $$ → gate matrix= → apply → probs match built-in H.
> ext/quantum/quantum.mq.md
> lib/math.mq.md
---
# main
`H_matrix` =
$$
\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}
$$
*`U` = > quantum.gate matrix=`H_matrix` name=U *
*`qc` = > quantum.circuit qubits=1 *
*`qc` = > `qc`.apply gate=`U` qubits=0 *
*`p` = > `qc`.probabilities *
*`p0` = `p`[^0] *
*`lo` = > math.div a=4 b=10 *
*`hi` = > math.div a=6 b=10 *
1. `p0` > `lo`
1. `p0` < `hi`
> print text=custom-ok
2. *
> print text=custom-fail
2. *
> print text=custom-fail
@@ -0,0 +1,29 @@
---
title: quantum custom gate zh from formula
description: $$ 矩阵 $$ → 门 矩阵= → 施加.
> ext/quantum/量子.mq.md
> lib/math.mq.md
---
# main
`H矩阵` =
$$
\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}
$$
*`U` = > 量子.门 矩阵=`H矩阵` 名=U *
*`qc` = > 量子.电路 比特数=1 *
*`qc` = > `qc`.施加 门=`U` 比特=0 *
*`p` = > `qc`.概率 *
*`p0` = `p`[^0] *
*`lo` = > math.div a=4 b=10 *
*`hi` = > math.div a=6 b=10 *
1. `p0` > `lo`
1. `p0` < `hi`
> print text=custom-ok
2. *
> print text=custom-fail
2. *
> print text=custom-fail
+22
View File
@@ -1630,6 +1630,28 @@ fn ext_quantum_amp_damp_zh_smoke() {
assert_out("tests/ext/quantum-amp-damp-zh-smoke.mq.md", "amp-ok");
}
#[test]
fn ext_quantum_custom_gate_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-custom-gate-smoke.mq.md", "custom-ok");
}
#[test]
fn ext_quantum_custom_gate_zh_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-custom-gate-zh-smoke.mq.md", "custom-ok");
}
#[test]
fn ext_agent_framework_smoke() {
let status = Command::new("cargo")