feat(linalg): L3 block collapse and lazy Kronecker

Add Block/Kron MatExpr, collapse for Block*Block, R7 flatten,
explicit assembly/kronecker, and linalg-block-kron smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-07 14:22:08 +08:00
1 parent 03aca7cdac
commit b6f116108c
10 files changed
+663 -11

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
## Unreleased
### Added
- **`ext/linalg` L0–L2**:公式 MatExpr(R1–R5)+ 稠密 `explicit`/`det`/`trace`/`solve`/`from_formula`;`marqdo ext add linalg`;金样 `linalg-formula-smoke` · `linalg-zh-smoke` · `linalg-basic-smoke`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。
- **`ext/linalg` L0–L3**:公式 MatExpr(含分块/`kron`)+ 稠密 `explicit`/`det`/`trace`/`solve`;`collapse` 分块乘;金样 `linalg-formula-smoke` · `linalg-zh-smoke` · `linalg-basic-smoke` · `linalg-block-kron`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。
### Fixed
+1 -1
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **Draft · L0–L2 已落地** |
| 状态 | **Draft · L0–L3 已落地** |
| 日期 | 2026-09-07 |
| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) |
| 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) |
+4 -4
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **L0–L2 已落地 · L3+ 待做** |
| 状态 | **L0–L3 已落地 · L4+ 待做** |
| 日期 | 2026-09-07 |
| **锁定设计** | [design/ext-linalg.md](../design/ext-linalg.md) |
| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) |
@@ -26,7 +26,7 @@
| **L0** | CATALOG + `plugins/linalg` ping + L1 `ensure_plugin`;`ext add` 条目 | **done** |
| **L1** | MatExpr:`symbol` / 稠密叶子 / `mul`·`add`·`T`·`inv`;`simplify` R1–R5;`latex`·`ascii`·`show` | **done** |
| **L2** | `explicit` / 小阵 gemm·解系·`det`·`trace`;维数护栏;金样 `linalg-basic-smoke` | **done** |
| **L3** | `block` + `collapse`;`kron` 惰性 + R7;金样 `linalg-block-kron` | **pending** |
| **L3** | `block` + `collapse`;`kron` 惰性 + R7;金样 `linalg-block-kron` | **done** |
| **L4** | `factorize` LU/QR/SVD/eig(+ 可选 chol);结构 SVG `svd|qr|ge|eig`;金样 `linalg-factor-smoke` | **pending** |
| **L5** | `heatmap`/`hinton`;examples(最小二乘 / SVD 示意);public + skill 摘要 | **pending** |
| **L6** | 复数 dtype;`lstsq`;`norm`/`cond`;主题令牌对齐 | **pending** |
@@ -59,8 +59,8 @@
### L3
- [ ] 分块乘 `collapse` 后块级正确
- [ ] Kronecker 默认不膨胀元素个数
- [x] 分块乘 `collapse` 后块级正确
- [x] Kronecker 默认不膨胀元素个数(惰性 `A⊗B`)
### L4
+25
View File
@@ -161,6 +161,31 @@ Dense matrix product → `linalg_dense`.
> ensure_plugin
**> linalg_matmul a=`a` b=`b`**
## kron
+ `a`
+ `b`
Lazy Kronecker product (does not expand).
> ensure_plugin
**> linalg_kron a=`a` b=`b`**
## block
+ `blocks`
Block matrix from a nested list of expressions.
> ensure_plugin
**> linalg_block blocks=`blocks`**
## collapse
+ `expr`
Block-level collapse (`Block*Block` → block of products).
> ensure_plugin
**> linalg_collapse expr=`expr`**
## symbol
+ `name`
+ `rows`
+25
View File
@@ -153,6 +153,31 @@ import sys:lib/sys.mq.md
> 确保插件
**> linalg_matmul a=`左` b=`右`**
## 克罗内克
+ `左`
+ `右`
惰性 Kronecker 积(默认不展开)。
> 确保插件
**> linalg_kron a=`左` b=`右`**
## 分块
+ `块`
由嵌套表达式列表构造分块矩阵。
> 确保插件
**> linalg_block blocks=`块`**
## 分块化简
+ `式`
分块级塌缩(`Block*Block` → 块乘加)。
> 确保插件
**> linalg_collapse expr=`式`**
## 符号
+ `名`
+ `行`
+90
View File
@@ -199,9 +199,99 @@ pub fn explicit(expr: &Expr) -> Result<Mat, String> {
Expr::Sub { left, right } => mat_sub(&explicit(left)?, &explicit(right)?),
Expr::Transpose { arg } => Ok(transpose(&explicit(arg)?)),
Expr::Inv { arg } => invert(&explicit(arg)?),
Expr::Kron { factors } => {
if factors.is_empty() {
return Err("empty Kronecker product".into());
}
let mut acc = explicit(&factors[0])?;
for f in &factors[1..] {
acc = kronecker(&acc, &explicit(f)?)?;
}
Ok(acc)
}
Expr::Block { blocks } => explicit_block(blocks),
}
}
fn explicit_block(blocks: &[Vec<Expr>]) -> Result<Mat, String> {
if blocks.is_empty() || blocks[0].is_empty() {
return Err("empty block matrix".into());
}
let br = blocks.len();
let bc = blocks[0].len();
let mut tiles: Vec<Vec<Mat>> = Vec::with_capacity(br);
for i in 0..br {
let mut row = Vec::with_capacity(bc);
for j in 0..bc {
row.push(explicit(&blocks[i][j])?);
}
tiles.push(row);
}
// Validate and assemble
let mut row_heights = Vec::with_capacity(br);
for i in 0..br {
let (h, _) = shape(&tiles[i][0])?;
for j in 1..bc {
let (h2, _) = shape(&tiles[i][j])?;
if h != h2 {
return Err("block row height mismatch when explicit".into());
}
}
row_heights.push(h);
}
let mut col_widths = Vec::with_capacity(bc);
for j in 0..bc {
let (_, w) = shape(&tiles[0][j])?;
for i in 1..br {
let (_, w2) = shape(&tiles[i][j])?;
if w != w2 {
return Err("block col width mismatch when explicit".into());
}
}
col_widths.push(w);
}
let total_r: usize = row_heights.iter().sum();
let total_c: usize = col_widths.iter().sum();
check_elems(total_r, total_c)?;
let mut out = zeros(total_r, total_c);
let mut r0 = 0;
for i in 0..br {
let mut c0 = 0;
for j in 0..bc {
let tile = &tiles[i][j];
let (h, w) = shape(tile)?;
for ii in 0..h {
for jj in 0..w {
out[r0 + ii][c0 + jj] = tile[ii][jj];
}
}
c0 += w;
}
r0 += row_heights[i];
}
Ok(out)
}
pub fn kronecker(a: &Mat, b: &Mat) -> Result<Mat, String> {
let (ar, ac) = shape(a)?;
let (br, bc) = shape(b)?;
let rows = ar.saturating_mul(br);
let cols = ac.saturating_mul(bc);
check_elems(rows, cols)?;
let mut out = zeros(rows, cols);
for i in 0..ar {
for j in 0..ac {
let aij = a[i][j];
for ii in 0..br {
for jj in 0..bc {
out[i * br + ii][j * bc + jj] = aij * b[ii][jj];
}
}
}
}
Ok(out)
}
pub fn matmul(a: &Mat, b: &Mat) -> Result<Mat, String> {
let (ar, ac) = shape(a)?;
let (br, bc) = shape(b)?;
+37 -1
View File
@@ -206,7 +206,7 @@ la_ffi!(linalg_ping, |_args: &Value| {
"ok": true,
"name": "linalg",
"abi": ABI_VERSION,
"features": ["matexpr", "simplify", "dense", "solve"],
"features": ["matexpr", "simplify", "dense", "solve", "block", "kron"],
}))
});
@@ -391,6 +391,39 @@ la_ffi!(linalg_matmul, |args: &Value| {
dense::to_dense_value(&dense::matmul(&a, &b)?)
});
la_ffi!(linalg_kron, |args: &Value| {
let a = arg_expr_opt(args, &["a", "左"])?;
let b = arg_expr_opt(args, &["b", "右"])?;
wrap(matexpr::kron(a, b)?)
});
la_ffi!(linalg_block, |args: &Value| {
let blocks_v = args
.get("blocks")
.or_else(|| args.get("块"))
.ok_or_else(|| "missing `blocks`".to_string())?;
let grid = blocks_v
.as_array()
.ok_or_else(|| "`blocks` must be a list of rows".to_string())?;
let mut blocks = Vec::new();
for row in grid {
let cells = row
.as_array()
.ok_or_else(|| "each block row must be a list".to_string())?;
let mut r = Vec::new();
for c in cells {
r.push(coerce_expr(c)?);
}
blocks.push(r);
}
wrap(matexpr::block(blocks)?)
});
la_ffi!(linalg_collapse, |args: &Value| {
let e = arg_expr_opt(args, &["expr", "a", "式"])?;
wrap(matexpr::collapse(e)?)
});
fn dense_arg(args: &Value, keys: &[&str]) -> Result<dense::Mat, String> {
for k in keys {
if let Some(v) = args.get(*k) {
@@ -450,6 +483,9 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("linalg_trace", "expr", linalg_trace as PluginFn),
("linalg_solve", "a,b", linalg_solve as PluginFn),
("linalg_matmul", "a,b", linalg_matmul as PluginFn),
("linalg_kron", "a,b", linalg_kron as PluginFn),
("linalg_block", "blocks", linalg_block as PluginFn),
("linalg_collapse", "expr", linalg_collapse as PluginFn),
];
for (name, params, f) in regs {
let c_name = CString::new(name).unwrap();
+417 -4
View File
@@ -84,6 +84,14 @@ pub enum Expr {
Inv {
arg: Box<Expr>,
},
/// Block matrix grid (rows of block rows).
Block {
blocks: Vec<Vec<Expr>>,
},
/// Kronecker product (lazy; do not expand by default).
Kron {
factors: Vec<Expr>,
},
}
impl Expr {
@@ -167,6 +175,19 @@ impl Expr {
}
Ok((r, c))
}
Expr::Block { blocks } => block_shape(blocks),
Expr::Kron { factors } => {
if factors.is_empty() {
return Err("empty Kronecker product".into());
}
let (mut rows, mut cols) = factors[0].shape()?;
for f in &factors[1..] {
let (r, c) = f.shape()?;
rows = dim_mul(&rows, &r)?;
cols = dim_mul(&cols, &c)?;
}
Ok((rows, cols))
}
}
}
@@ -216,6 +237,31 @@ impl Expr {
format!("({inner})^-1")
}
}
Expr::Block { blocks } => {
let rows: Vec<String> = blocks
.iter()
.map(|row| {
let cells: Vec<String> = row.iter().map(|b| b.ascii()).collect();
format!("[{}]", cells.join(", "))
})
.collect();
format!("Block[{}]", rows.join("; "))
}
Expr::Kron { factors } => factors
.iter()
.map(|f| {
let s = f.ascii();
if matches!(
f,
Expr::Add { .. } | Expr::Sub { .. } | Expr::Mul { .. } | Expr::Block { .. }
) {
format!("({s})")
} else {
s
}
})
.collect::<Vec<_>>()
.join("⊗"),
}
}
@@ -267,6 +313,36 @@ impl Expr {
format!("\\left({inner}\\right)^{{-1}}")
}
}
Expr::Block { blocks } => {
let body: Vec<String> = blocks
.iter()
.map(|row| {
row.iter()
.map(|b| b.latex())
.collect::<Vec<_>>()
.join(" & ")
})
.collect();
format!(
"\\begin{{bmatrix}}{}\\end{{bmatrix}}",
body.join(" \\\\ ")
)
}
Expr::Kron { factors } => factors
.iter()
.map(|f| {
let s = f.latex();
if matches!(
f,
Expr::Add { .. } | Expr::Sub { .. } | Expr::Mul { .. } | Expr::Block { .. }
) {
format!("\\left({s}\\right)")
} else {
s
}
})
.collect::<Vec<_>>()
.join(" \\otimes "),
}
}
@@ -321,6 +397,23 @@ impl Expr {
obj.insert("kind".into(), json!("inv"));
obj.insert("arg".into(), arg.to_value()?);
}
Expr::Block { blocks } => {
obj.insert("kind".into(), json!("block"));
let mut grid = Vec::new();
for row in blocks {
let mut r = Vec::new();
for b in row {
r.push(b.to_value()?);
}
grid.push(Value::Array(r));
}
obj.insert("blocks".into(), Value::Array(grid));
}
Expr::Kron { factors } => {
obj.insert("kind".into(), json!("kron"));
let kids: Result<Vec<_>, _> = factors.iter().map(|f| f.to_value()).collect();
obj.insert("factors".into(), Value::Array(kids?));
}
}
Ok(Value::Object(obj))
}
@@ -389,6 +482,35 @@ impl Expr {
"inv" => Ok(Expr::Inv {
arg: Box::new(Expr::from_value(obj.get("arg").ok_or("inv missing arg")?)?),
}),
"block" => {
let grid = obj
.get("blocks")
.and_then(|x| x.as_array())
.ok_or("block missing blocks")?;
let mut blocks = Vec::new();
for row in grid {
let cells = row
.as_array()
.ok_or("block row must be a list")?;
let row: Result<Vec<_>, _> =
cells.iter().map(Expr::from_value).collect();
blocks.push(row?);
}
let expr = Expr::Block { blocks };
let _ = expr.shape()?;
Ok(expr)
}
"kron" => {
let factors = obj
.get("factors")
.and_then(|x| x.as_array())
.ok_or("kron missing factors")?;
let factors: Result<Vec<_>, _> =
factors.iter().map(Expr::from_value).collect();
Ok(Expr::Kron {
factors: flatten_kron(factors?),
})
},
other => Err(format!("unknown linalg_expr kind `{other}`")),
}
}
@@ -404,6 +526,76 @@ fn dims_eq(a: &Dim, b: &Dim) -> bool {
}
}
fn dim_add(a: &Dim, b: &Dim) -> Result<Dim, String> {
match (a, b) {
(Dim::Int(x), Dim::Int(y)) => Ok(Dim::Int(x + y)),
(Dim::Sym(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}+{y})"))),
(Dim::Int(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}+{y})"))),
(Dim::Sym(x), Dim::Int(y)) => Ok(Dim::Sym(format!("({x}+{y})"))),
}
}
fn dim_mul(a: &Dim, b: &Dim) -> Result<Dim, String> {
match (a, b) {
(Dim::Int(x), Dim::Int(y)) => Ok(Dim::Int(x.saturating_mul(*y))),
(Dim::Sym(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}*{y})"))),
(Dim::Int(x), Dim::Sym(y)) => Ok(Dim::Sym(format!("({x}*{y})"))),
(Dim::Sym(x), Dim::Int(y)) => Ok(Dim::Sym(format!("({x}*{y})"))),
}
}
fn block_shape(blocks: &[Vec<Expr>]) -> Result<(Dim, Dim), String> {
if blocks.is_empty() || blocks[0].is_empty() {
return Err("empty block matrix".into());
}
let br = blocks.len();
let bc = blocks[0].len();
if blocks.iter().any(|row| row.len() != bc) {
return Err("block matrix rows must have equal width".into());
}
// Row heights: from column 0
let mut row_heights = Vec::with_capacity(br);
for i in 0..br {
let (h, _) = blocks[i][0].shape()?;
for j in 1..bc {
let (h2, _) = blocks[i][j].shape()?;
if !dims_eq(&h, &h2) {
return Err(format!(
"block row {i}: incompatible heights {} vs {}",
h.ascii(),
h2.ascii()
));
}
}
row_heights.push(h);
}
// Col widths: from row 0
let mut col_widths = Vec::with_capacity(bc);
for j in 0..bc {
let (_, w) = blocks[0][j].shape()?;
for i in 1..br {
let (_, w2) = blocks[i][j].shape()?;
if !dims_eq(&w, &w2) {
return Err(format!(
"block col {j}: incompatible widths {} vs {}",
w.ascii(),
w2.ascii()
));
}
}
col_widths.push(w);
}
let mut rows = row_heights[0].clone();
for h in &row_heights[1..] {
rows = dim_add(&rows, h)?;
}
let mut cols = col_widths[0].clone();
for w in &col_widths[1..] {
cols = dim_add(&cols, w)?;
}
Ok((rows, cols))
}
fn parse_dense(v: &Value) -> Result<Vec<Vec<f64>>, String> {
let rows = v
.as_array()
@@ -541,12 +733,14 @@ fn simplify_once(expr: Expr) -> Result<Expr, String> {
Expr::Add { terms } => {
let terms: Result<Vec<_>, _> = terms.into_iter().map(simplify_once).collect();
let mut terms = terms?;
let zero_shape = terms.iter().find_map(|t| match t {
Expr::Zero { rows, cols } => Some((rows.clone(), cols.clone())),
_ => None,
});
terms.retain(|t| !is_zero(t));
if terms.is_empty() {
return Ok(Expr::Zero {
rows: Dim::Int(0),
cols: Dim::Int(0),
});
let (rows, cols) = zero_shape.unwrap_or((Dim::Int(0), Dim::Int(0)));
return Ok(Expr::Zero { rows, cols });
}
if terms.len() == 1 {
return Ok(terms.pop().unwrap());
@@ -603,6 +797,34 @@ fn simplify_once(expr: Expr) -> Result<Expr, String> {
rows: cols,
cols: rows,
}),
// Block^T → block of transposed tiles, swapped indices
Expr::Block { blocks } => {
if blocks.is_empty() {
return Ok(Expr::Block { blocks });
}
let br = blocks.len();
let bc = blocks[0].len();
let mut out = vec![vec![]; bc];
for j in 0..bc {
out[j] = Vec::with_capacity(br);
for i in 0..br {
out[j].push(Expr::Transpose {
arg: Box::new(blocks[i][j].clone()),
});
}
}
simplify_once(Expr::Block { blocks: out })
}
// (A⊗B)^T → A^T ⊗ B^T
Expr::Kron { factors } => {
let factors = factors
.into_iter()
.map(|f| Expr::Transpose {
arg: Box::new(f),
})
.collect();
simplify_once(Expr::Kron { factors })
}
other => Ok(Expr::Transpose {
arg: Box::new(other),
}),
@@ -620,12 +842,138 @@ fn simplify_once(expr: Expr) -> Result<Expr, String> {
}),
}
}
Expr::Block { blocks } => {
let mut out = Vec::new();
for row in blocks {
let mut r = Vec::new();
for b in row {
r.push(simplify_once(b)?);
}
out.push(r);
}
Ok(Expr::Block { blocks: out })
}
Expr::Kron { factors } => {
// R7: flatten nested Kronecker
let factors: Result<Vec<_>, _> = flatten_kron(factors)
.into_iter()
.map(simplify_once)
.collect();
let mut factors = factors?;
if factors.len() == 1 {
return Ok(factors.pop().unwrap());
}
Ok(Expr::Kron { factors })
}
Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } => {
Ok(expr)
}
}
}
fn flatten_kron(factors: Vec<Expr>) -> Vec<Expr> {
let mut out = Vec::new();
for f in factors {
match f {
Expr::Kron { factors: inner } => out.extend(flatten_kron(inner)),
other => out.push(other),
}
}
out
}
/// Block-level collapse (R6 subset): `Block * Block` → block of products.
pub fn collapse(expr: Expr) -> Result<Expr, String> {
let expr = simplify(expr)?;
collapse_once(expr)
}
fn collapse_once(expr: Expr) -> Result<Expr, String> {
match expr {
Expr::Mul { factors } => {
let factors: Result<Vec<_>, _> =
flatten_mul(factors).into_iter().map(collapse_once).collect();
let factors = factors?;
let mut acc = factors[0].clone();
for f in factors.into_iter().skip(1) {
acc = collapse_mul_pair(acc, f)?;
}
Ok(acc)
}
Expr::Block { blocks } => {
let mut out = Vec::new();
for row in blocks {
let mut r = Vec::new();
for b in row {
r.push(collapse_once(b)?);
}
out.push(r);
}
Ok(Expr::Block { blocks: out })
}
Expr::Add { terms } => {
let terms: Result<Vec<_>, _> = terms.into_iter().map(collapse_once).collect();
Ok(Expr::Add { terms: terms? })
}
Expr::Sub { left, right } => Ok(Expr::Sub {
left: Box::new(collapse_once(*left)?),
right: Box::new(collapse_once(*right)?),
}),
Expr::Transpose { arg } => Ok(Expr::Transpose {
arg: Box::new(collapse_once(*arg)?),
}),
Expr::Inv { arg } => Ok(Expr::Inv {
arg: Box::new(collapse_once(*arg)?),
}),
Expr::Kron { factors } => {
let factors: Result<Vec<_>, _> = factors.into_iter().map(collapse_once).collect();
Ok(Expr::Kron {
factors: flatten_kron(factors?),
})
}
other => Ok(other),
}
}
fn collapse_mul_pair(a: Expr, b: Expr) -> Result<Expr, String> {
match (a, b) {
(Expr::Block { blocks: left }, Expr::Block { blocks: right }) => {
let lr = left.len();
let lc = left[0].len();
let rr = right.len();
let rc = right[0].len();
if lc != rr {
return Err(format!(
"block mul: left cols {lc} != right rows {rr}"
));
}
let mut out = Vec::with_capacity(lr);
for i in 0..lr {
let mut row = Vec::with_capacity(rc);
for j in 0..rc {
let mut term = mul(left[i][0].clone(), right[0][j].clone())?;
for k in 1..lc {
let p = mul(left[i][k].clone(), right[k][j].clone())?;
term = add(term, p)?;
}
row.push(simplify(term)?);
}
out.push(row);
}
let expr = Expr::Block { blocks: out };
let _ = expr.shape()?;
Ok(expr)
}
(a, b) => {
let expr = Expr::Mul {
factors: flatten_mul(vec![a, b]),
};
let _ = expr.shape()?;
Ok(expr)
}
}
}
pub fn mul(a: Expr, b: Expr) -> Result<Expr, String> {
let expr = Expr::Mul {
factors: flatten_mul(vec![a, b]),
@@ -694,6 +1042,20 @@ pub fn from_list(data: Vec<Vec<f64>>) -> Result<Expr, String> {
Ok(Expr::Dense { data })
}
pub fn block(blocks: Vec<Vec<Expr>>) -> Result<Expr, String> {
let expr = Expr::Block { blocks };
let _ = expr.shape()?;
Ok(expr)
}
pub fn kron(a: Expr, b: Expr) -> Result<Expr, String> {
let expr = Expr::Kron {
factors: flatten_kron(vec![a, b]),
};
let _ = expr.shape()?;
Ok(expr)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -722,4 +1084,55 @@ mod tests {
let b = symbol("B", Dim::Int(3), Dim::Int(3));
assert!(mul(a, b).is_err());
}
#[test]
fn kron_lazy_ascii() {
let a = symbol("A", Dim::Int(2), Dim::Int(2));
let b = symbol("B", Dim::Int(2), Dim::Int(2));
let k = kron(a, b).unwrap();
assert_eq!(k.ascii(), "A⊗B");
let (r, c) = k.shape().unwrap();
assert_eq!(r, Dim::Int(4));
assert_eq!(c, Dim::Int(4));
}
#[test]
fn block_collapse_mul() {
let a = symbol("A", Dim::Int(2), Dim::Int(2));
let b = symbol("B", Dim::Int(2), Dim::Int(2));
let z = zeros(Dim::Int(2), Dim::Int(2));
let left = block(vec![
vec![a.clone(), b.clone()],
vec![z.clone(), a.clone()],
])
.unwrap();
let right = block(vec![
vec![a.clone(), z.clone()],
vec![z.clone(), b.clone()],
])
.unwrap();
let p = mul(left, right).unwrap();
let c = collapse(p).unwrap();
// [[A,B],[0,A]] * [[A,0],[0,B]] → [[A*A, B*B],[0, A*B]]
assert!(matches!(c, Expr::Block { .. }));
assert_eq!(c.ascii(), "Block[[A*A, B*B]; [0(2×2), A*B]]");
}
#[test]
fn block_collapse_same_blocks() {
let a = symbol("A", Dim::Int(2), Dim::Int(2));
let b = symbol("B", Dim::Int(2), Dim::Int(2));
let z = zeros(Dim::Int(2), Dim::Int(2));
let m = block(vec![
vec![a.clone(), b.clone()],
vec![z.clone(), a.clone()],
])
.unwrap();
let p = mul(m.clone(), m).unwrap();
let c = collapse(p).unwrap();
assert_eq!(
c.ascii(),
"Block[[A*A, A*B + B*A]; [0(2×2), A*A]]"
);
}
}
+49
View File
@@ -0,0 +1,49 @@
---
title: linalg block/kron smoke (L3)
description: Lazy kron ascii; block*block collapse.
import la:ext/linalg/linalg.mq.md
---
# main
*`A` = > la.symbol name="A" rows=2 cols=2*
*`B` = > la.symbol name="B" rows=2 cols=2*
*`Z` = > la.zeros rows=2 cols=2*
*`K` = > la.kron a=`A` b=`B`*
*`kt` = > la.ascii expr=`K`*
> print text=`kt`
`r0` =
| v |
|---|
| `A` |
| `B` |
`r1` =
| v |
|---|
| `Z` |
| `A` |
`blocks` =
| v |
|---|
| `r0` |
| `r1` |
*`L` = > la.block blocks=`blocks`*
*`P` = > la.mul a=`L` b=`L`*
*`C` = > la.collapse expr=`P`*
*`ct` = > la.ascii expr=`C`*
> print text=`ct`
*`ping` = > la.ping*
*`ok` = ping[^ok]*
1. `ok`
> print text=ping-ok
2. *
> print text=ping-fail
+14
View File
@@ -2464,6 +2464,20 @@ txn-rollback-ok",
);
}
#[test]
fn ext_linalg_block_kron() {
let status = Command::new("cargo")
.args(["build", "-p", "marqdo_plugin_linalg"])
.current_dir(env!("CARGO_MANIFEST_DIR"))
.status()
.expect("build linalg plugin");
assert!(status.success(), "failed to build marqdo_plugin_linalg");
assert_out(
"tests/ext/linalg-block-kron.mq.md",
"A⊗B\nBlock[[A*A, A*B + B*A]; [0(2×2), A*A]]\nping-ok",
);
}
#[test]
fn ext_linalg_basic_smoke() {
let status = Command::new("cargo")