feat(linalg): L6 lstsq, norms, complex dtype, draw themes
Add QR/SVD least squares, norm/cond/rank, complex dense Frobenius baseline, and light/dark/bw draw themes aligned with quantum Q8. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
01287d9e7e
commit
c0fbe9b182
15 files changed
+910
-136
No files matched your search
@@ -235,7 +235,7 @@ Install: `marqdo ext add linalg` (ZH id: `线性代数`). Build: `cargo build --
|
||||
|
||||
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; prefer top-level `la.symbol` (not `matrix.symbol` without a receiver); quote `kind=` strings; dense `explicit` / factorize obey size guards.
|
||||
|
||||
APIs (EN): `symbol` / `mul` / `simplify` / `ascii` / `show` · `from_formula` / `explicit` / `det` / `solve` · `block` / `kron` / `collapse` · `factorize` / `draw` (`eig|svd|qr|lu|heatmap|hinton`).
|
||||
APIs (EN): `symbol` / `mul` / `simplify` / `ascii` / `show` · `from_formula` / `explicit` / `det` / `solve` · `block` / `kron` / `collapse` · `factorize` / `draw` (`theme=light|dark|bw`) · `lstsq` / `norm` / `cond` / `rank`.
|
||||
|
||||
Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../../examples/linalg-least-squares/). Design: [ext-linalg.md](../../doc/design/ext-linalg.md).
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **`ext/linalg` L0–L5**:公式 MatExpr(含分块/`kron`)+ 稠密 `explicit`/`det`/`trace`/`solve`;`collapse` 分块乘;`factorize`(LU/QR/SVD/eig/chol)+ 结构/`heatmap`/`hinton` SVG;示例 `linalg-svd` · `linalg-least-squares`;金样 `linalg-formula-smoke` · `linalg-zh-smoke` · `linalg-basic-smoke` · `linalg-block-kron` · `linalg-factor-smoke`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。
|
||||
- **`ext/linalg` L0–L6**:公式 MatExpr(含分块/`kron`)+ 稠密 `explicit`/`det`/`trace`/`solve`;`collapse`;`factorize` + 结构/`heatmap` SVG;`lstsq`/`norm`/`cond`/`rank`;`dtype=complex` 基线;`draw theme=light|dark|bw`;示例 `linalg-svd` · `linalg-least-squares`;金样至 `linalg-metrics-smoke`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
@@ -111,7 +111,7 @@ marqdo catalog public -o .marqdo
|
||||
- **官方扩展库 `ext/`**(**非** stdlib,本版收口):
|
||||
- **`web`**:W0–W7 + P3 + **W8**;**定制 C0–C4**(admin 前缀/gates/`shell_css`/`layout`/样式 strict/脚本 defer·version/条件导航,见 [ext-web-customization](doc/design/ext-web-customization/));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)
|
||||
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
|
||||
- **`linalg`**:L0–L5 公式 MatExpr + 稠密/`factorize`/`draw`;示例 [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/)
|
||||
- **`linalg`**:L0–L6 公式 MatExpr + 稠密/`factorize`/`lstsq`/`draw theme`;示例 [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/)
|
||||
- **`agent`**:A1–A4(OKF 复用、过程事件、上下文预算、RAG/MCP fixture);下一波缺口 [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)
|
||||
- **`llm`**:OpenAI 兼容对话
|
||||
- 安装:`marqdo ext list` / `add …` / `remove`([ext-cli.md](doc/design/ext-cli.md);默认 `~/.marqdo/ext`)。原生插件先 `cargo build -p marqdo_plugin_*` 再 `ext add`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Draft · L0–L5 已落地** |
|
||||
| 状态 | **Draft · L0–L6 已落地** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) |
|
||||
| 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) |
|
||||
@@ -285,7 +285,7 @@ $$
|
||||
| `eig` | \(A=PDP^{-1}\) 或谱列表 + 对角 |
|
||||
| `heatmap` | 单元填色(实数蓝红;复数幅值) |
|
||||
|
||||
主题:复用文档站浅色;可选 `theme=light|dark|bw`(与 quantum Q8 令牌对齐时可后置)。
|
||||
主题:`theme=light|dark|bw`(与 quantum Q8 令牌对齐;默认 `light`)。
|
||||
|
||||
---
|
||||
|
||||
@@ -309,7 +309,7 @@ $$
|
||||
| **L3** | 分块 + `collapse`;Kronecker 惰性 |
|
||||
| **L4** | `factorize` LU/QR/SVD/eig + 结构 SVG |
|
||||
| **L5** | heatmap/hinton;examples + public 文档 + skill 摘要 |
|
||||
| **L6+** | 复数、lstsq、条件数、矩阵微积分(远期) |
|
||||
| **L6+** | 矩阵微积分 / 更大 BLAS(仅当用户明确要求);复数全路径算子 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **L0–L5 已落地 · L6+ 待做** |
|
||||
| 状态 | **L0–L6 已落地 · L7+ 远期** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| **锁定设计** | [design/ext-linalg.md](../design/ext-linalg.md) |
|
||||
| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) |
|
||||
@@ -29,7 +29,7 @@
|
||||
| **L3** | `block` + `collapse`;`kron` 惰性 + R7;金样 `linalg-block-kron` | **done** |
|
||||
| **L4** | `factorize` LU/QR/SVD/eig(+ 可选 chol);结构 SVG `svd|qr|ge|eig`;金样 `linalg-factor-smoke` | **done** |
|
||||
| **L5** | `heatmap`/`hinton`;examples(最小二乘 / SVD 示意);public + skill 摘要 | **done** |
|
||||
| **L6** | 复数 dtype;`lstsq`;`norm`/`cond`;主题令牌对齐 | **pending** |
|
||||
| **L6** | 复数 dtype;`lstsq`;`norm`/`cond`;主题令牌对齐 | **done** |
|
||||
| **L7+** | 矩阵微积分 / 更大 BLAS 依赖(仅当用户明确要求) | **deferred** |
|
||||
|
||||
验收金样(规划路径):`tests/ext/linalg-*-smoke.mq.md`;示例:`examples/linalg-least-squares/`、`examples/linalg-svd/`。
|
||||
@@ -74,6 +74,12 @@
|
||||
- [x] public/features 或 tutorial 短页
|
||||
- [x] skill / CHANGELOG Unreleased 条目
|
||||
|
||||
### L6
|
||||
|
||||
- [x] `lstsq` / `norm` / `cond` / `rank` 金样
|
||||
- [x] `dtype=complex` 基线(Frobenius;分解仍为实数)
|
||||
- [x] `draw theme=light|dark|bw` 与 quantum Q8 令牌对齐(`data-theme`)
|
||||
|
||||
---
|
||||
|
||||
## 4. 依赖与并行
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
title: Least squares via QR
|
||||
description: Overdetermined Ax≈b with ext/linalg QR + heatmap.
|
||||
title: Least squares via lstsq
|
||||
description: Overdetermined Ax≈b with ext/linalg lstsq + heatmap.
|
||||
import la:ext/linalg/linalg.mq.md
|
||||
import math:lib/math.mq.md
|
||||
---
|
||||
|
||||
# Least squares from a runnable document
|
||||
|
||||
Fit a line through three points with an overdetermined `A x ≈ b`. Factor `A = QR`, form `Qᵀ b`, then solve the square upper-triangular `R`. A heatmap makes the design matrix visible in `view`.
|
||||
Fit a line through three points with an overdetermined `A x ≈ b` using `lstsq` (QR path). A heatmap makes the design matrix visible in `view`.
|
||||
|
||||
# main
|
||||
|
||||
@@ -24,22 +24,12 @@ $$
|
||||
*`A` = > la.from_formula formula=`A`*
|
||||
*`b` = > la.from_formula formula=`b`*
|
||||
|
||||
*`_` = > la.draw factor=`A` kind="heatmap" path="ls-heatmap.svg"*
|
||||
*`_` = > la.draw factor=`A` kind="heatmap" theme="light" path="ls-heatmap.svg"*
|
||||
|
||||
*`qr` = > la.factorize matrix=`A` kind="qr"*
|
||||
*`Q` = qr[^Q]*
|
||||
*`R` = qr[^R]*
|
||||
*`Qt` = > la.transpose expr=`Q`*
|
||||
*`Qtb` = > la.matmul a=`Qt` b=`b`*
|
||||
*`sol` = > la.solve a=`R` b=`Qtb`*
|
||||
*`x` = sol[^x]*
|
||||
|
||||
*`Ax` = > la.matmul a=`A` b=`x`*
|
||||
*`r0` = > at value=Ax[^data] index=0*
|
||||
*`ax0` = > at value=`r0` index=0*
|
||||
*`diff` = > math.sub a=`ax0` b=1*
|
||||
*`diff` = > math.abs value=`diff`*
|
||||
*`ls` = > la.lstsq a=`A` b=`b`*
|
||||
*`x` = ls[^x]*
|
||||
*`resid` = ls[^residual_fro]*
|
||||
|
||||
> print text=`x`
|
||||
> print text=`diff`
|
||||
> print text=`resid`
|
||||
> print text=ls-ok
|
||||
+37
-2
@@ -200,11 +200,46 @@ Dense factorization → `linalg_factor` (`kind` = `lu` | `qr` | `svd` | `eig` |
|
||||
+ `factor`
|
||||
+ `kind`=None
|
||||
+ `path`=None
|
||||
+ `theme`="light"
|
||||
|
||||
Structure SVG for a factor or dense matrix (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`).
|
||||
Structure SVG (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`). Theme tokens match quantum Q8: `light` | `dark` | `bw`.
|
||||
|
||||
> ensure_plugin
|
||||
**> linalg_draw factor=`factor` kind=`kind` path=`path`**
|
||||
**> linalg_draw factor=`factor` kind=`kind` path=`path` theme=`theme`**
|
||||
|
||||
## lstsq
|
||||
+ `a`
|
||||
+ `b`
|
||||
|
||||
Least squares `min ||a x - b||` (QR if tall, SVD if wide).
|
||||
|
||||
> ensure_plugin
|
||||
**> linalg_lstsq a=`a` b=`b`**
|
||||
|
||||
## norm
|
||||
+ `expr`
|
||||
+ `ord`="fro"
|
||||
|
||||
Matrix norm: `fro` | `1` | `inf` | `2`. Complex dense supports `fro` only.
|
||||
|
||||
> ensure_plugin
|
||||
**> linalg_norm expr=`expr` ord=`ord`**
|
||||
|
||||
## cond
|
||||
+ `expr`
|
||||
|
||||
Spectral condition number via SVD (`ord=2`).
|
||||
|
||||
> ensure_plugin
|
||||
**> linalg_cond expr=`expr`**
|
||||
|
||||
## rank
|
||||
+ `expr`
|
||||
|
||||
Numerical rank (SVD).
|
||||
|
||||
> ensure_plugin
|
||||
**> linalg_rank expr=`expr`**
|
||||
|
||||
## symbol
|
||||
+ `name`
|
||||
|
||||
+37
-2
@@ -192,11 +192,46 @@ import sys:lib/sys.mq.md
|
||||
+ `分解`
|
||||
+ `类型`=None
|
||||
+ `路径`=None
|
||||
+ `主题`="light"
|
||||
|
||||
分解/稠密结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。
|
||||
结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。主题与 quantum Q8 对齐:`light` | `dark` | `bw`。
|
||||
|
||||
> 确保插件
|
||||
**> linalg_draw factor=`分解` kind=`类型` path=`路径`**
|
||||
**> linalg_draw factor=`分解` kind=`类型` path=`路径` theme=`主题`**
|
||||
|
||||
## 最小二乘
|
||||
+ `左`
|
||||
+ `右`
|
||||
|
||||
最小二乘 `min ||左 · x - 右||`(高瘦用 QR,宽用 SVD)。
|
||||
|
||||
> 确保插件
|
||||
**> linalg_lstsq a=`左` b=`右`**
|
||||
|
||||
## 范数
|
||||
+ `式`
|
||||
+ `范数`="fro"
|
||||
|
||||
矩阵范数:`fro` | `1` | `inf` | `2`。复数稠密暂仅 `fro`。
|
||||
|
||||
> 确保插件
|
||||
**> linalg_norm expr=`式` ord=`范数`**
|
||||
|
||||
## 条件数
|
||||
+ `式`
|
||||
|
||||
谱条件数(SVD,`ord=2`)。
|
||||
|
||||
> 确保插件
|
||||
**> linalg_cond expr=`式`**
|
||||
|
||||
## 秩
|
||||
+ `式`
|
||||
|
||||
数值秩(SVD)。
|
||||
|
||||
> 确保插件
|
||||
**> linalg_rank expr=`式`**
|
||||
|
||||
## 符号
|
||||
+ `名`
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Complex dense baseline (L6): parse/store + Frobenius norm.
|
||||
//! Factorize / solve stay real-only for now.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::dense::MAX_ELEMENTS;
|
||||
|
||||
pub type CMat = Vec<Vec<(f64, f64)>>;
|
||||
|
||||
pub fn shape(m: &CMat) -> Result<(usize, usize), String> {
|
||||
if m.is_empty() {
|
||||
return Err("empty complex matrix".into());
|
||||
}
|
||||
let r = m.len();
|
||||
let c = m[0].len();
|
||||
if c == 0 || m.iter().any(|row| row.len() != c) {
|
||||
return Err("complex matrix rows must have equal non-zero length".into());
|
||||
}
|
||||
Ok((r, c))
|
||||
}
|
||||
|
||||
fn check_elems(rows: usize, cols: usize) -> Result<(), String> {
|
||||
let n = rows.saturating_mul(cols);
|
||||
if n > MAX_ELEMENTS {
|
||||
return Err(format!(
|
||||
"complex matrix {rows}×{cols} has {n} elements > limit {MAX_ELEMENTS}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_cell(c: &Value) -> Result<(f64, f64), String> {
|
||||
if let Some(n) = c
|
||||
.as_f64()
|
||||
.or_else(|| c.as_i64().map(|i| i as f64))
|
||||
.or_else(|| c.as_u64().map(|u| u as f64))
|
||||
{
|
||||
return Ok((n, 0.0));
|
||||
}
|
||||
if let Some(arr) = c.as_array() {
|
||||
if arr.len() == 2 {
|
||||
let re = arr[0]
|
||||
.as_f64()
|
||||
.or_else(|| arr[0].as_i64().map(|i| i as f64))
|
||||
.ok_or_else(|| "complex re must be number".to_string())?;
|
||||
let im = arr[1]
|
||||
.as_f64()
|
||||
.or_else(|| arr[1].as_i64().map(|i| i as f64))
|
||||
.ok_or_else(|| "complex im must be number".to_string())?;
|
||||
return Ok((re, im));
|
||||
}
|
||||
}
|
||||
if let Some(obj) = c.as_object() {
|
||||
let re = obj
|
||||
.get("re")
|
||||
.or_else(|| obj.get("real"))
|
||||
.and_then(|v| v.as_f64().or_else(|| v.as_i64().map(|i| i as f64)))
|
||||
.ok_or_else(|| "complex cell needs re/real".to_string())?;
|
||||
let im = obj
|
||||
.get("im")
|
||||
.or_else(|| obj.get("imag"))
|
||||
.and_then(|v| v.as_f64().or_else(|| v.as_i64().map(|i| i as f64)))
|
||||
.unwrap_or(0.0);
|
||||
return Ok((re, im));
|
||||
}
|
||||
Err("complex cell must be number, [re,im], or {re,im}".into())
|
||||
}
|
||||
|
||||
fn cell_looks_complex(c: &Value) -> bool {
|
||||
if let Some(arr) = c.as_array() {
|
||||
return arr.len() == 2
|
||||
&& arr.iter().all(|x| {
|
||||
x.is_number() || x.as_i64().is_some() || x.as_u64().is_some()
|
||||
});
|
||||
}
|
||||
c.as_object()
|
||||
.map(|o| o.contains_key("re") || o.contains_key("real") || o.contains_key("im"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// True if nested list contains any complex-looking cell.
|
||||
pub fn data_has_complex(v: &Value) -> bool {
|
||||
let Some(rows) = v.as_array() else {
|
||||
return false;
|
||||
};
|
||||
rows.iter().any(|row| {
|
||||
row.as_array()
|
||||
.map(|cells| cells.iter().any(cell_looks_complex))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn from_data(v: &Value) -> Result<CMat, String> {
|
||||
let rows = v
|
||||
.as_array()
|
||||
.ok_or_else(|| "complex data must be list of rows".to_string())?;
|
||||
let mut out = Vec::new();
|
||||
let mut width = None;
|
||||
for row in rows {
|
||||
let cells = row
|
||||
.as_array()
|
||||
.ok_or_else(|| "complex row must be a list".to_string())?;
|
||||
let mut r = Vec::new();
|
||||
for c in cells {
|
||||
r.push(parse_cell(c)?);
|
||||
}
|
||||
if let Some(w) = width {
|
||||
if r.len() != w {
|
||||
return Err("complex matrix rows must have equal length".into());
|
||||
}
|
||||
} else {
|
||||
width = Some(r.len());
|
||||
}
|
||||
out.push(r);
|
||||
}
|
||||
let (rows, cols) = shape(&out)?;
|
||||
check_elems(rows, cols)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn from_value(v: &Value) -> Result<CMat, String> {
|
||||
if let Some(obj) = v.as_object() {
|
||||
if obj.get("dtype").and_then(|d| d.as_str()) == Some("complex") {
|
||||
if let Some(data) = obj.get("data") {
|
||||
return from_data(data);
|
||||
}
|
||||
}
|
||||
if let Some(data) = obj.get("data") {
|
||||
if data_has_complex(data) {
|
||||
return from_data(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
if v.is_array() && data_has_complex(v) {
|
||||
return from_data(v);
|
||||
}
|
||||
Err("expected linalg_dense dtype=complex or nested complex list".into())
|
||||
}
|
||||
|
||||
fn format_c(z: (f64, f64)) -> String {
|
||||
let (re, im) = z;
|
||||
if im.abs() < 1e-15 {
|
||||
if re.fract() == 0.0 && re.abs() < 1e15 {
|
||||
format!("{}", re as i64)
|
||||
} else {
|
||||
format!("{re}")
|
||||
}
|
||||
} else if re.abs() < 1e-15 {
|
||||
format!("{im}i")
|
||||
} else {
|
||||
format!("{re}{im:+}i")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_dense_value(m: &CMat) -> Result<Value, String> {
|
||||
let (rows, cols) = shape(m)?;
|
||||
check_elems(rows, cols)?;
|
||||
let data: Vec<Vec<Value>> = m
|
||||
.iter()
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(|&(re, im)| json!([re, im]))
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let ascii_rows: Vec<String> = m
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let cells: Vec<String> = row.iter().map(|&z| format_c(z)).collect();
|
||||
format!("[{}]", cells.join(","))
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"_type": "linalg_dense",
|
||||
"rows": rows,
|
||||
"cols": cols,
|
||||
"data": data,
|
||||
"dtype": "complex",
|
||||
"ascii": format!("[{}]", ascii_rows.join(",")),
|
||||
"latex": format!(
|
||||
"\\begin{{bmatrix}}{}\\end{{bmatrix}}",
|
||||
m.iter()
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(|&z| format_c(z))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" & ")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" \\\\ ")
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn frobenius_norm(m: &CMat) -> Result<f64, String> {
|
||||
let _ = shape(m)?;
|
||||
let mut s = 0.0;
|
||||
for row in m {
|
||||
for &(re, im) in row {
|
||||
s += re * re + im * im;
|
||||
}
|
||||
}
|
||||
Ok(s.sqrt())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fro_i() {
|
||||
let m = from_data(&json!([[[0.0, 1.0], [1.0, 0.0]], [[1.0, 0.0], [0.0, -1.0]]])).unwrap();
|
||||
assert!((frobenius_norm(&m).unwrap() - 2.0).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
+211
-85
@@ -1,20 +1,108 @@
|
||||
//! Structure SVG for factorizations (teaching layouts).
|
||||
//! Structure SVG for factorizations (teaching layouts) with Q8-aligned themes.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ThemeName {
|
||||
Dark,
|
||||
Light,
|
||||
Bw,
|
||||
}
|
||||
|
||||
impl ThemeName {
|
||||
pub fn parse(raw: &str) -> Result<Self, String> {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"dark" | "暗" => Ok(Self::Dark),
|
||||
"light" | "亮" | "浅" => Ok(Self::Light),
|
||||
"bw" | "mono" | "黑白" => Ok(Self::Bw),
|
||||
other => Err(format!("unknown theme `{other}` (dark|light|bw)")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Dark => "dark",
|
||||
Self::Light => "light",
|
||||
Self::Bw => "bw",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Theme {
|
||||
name: ThemeName,
|
||||
bg: &'static str,
|
||||
ink: &'static str,
|
||||
muted: &'static str,
|
||||
stroke: &'static str,
|
||||
box_a: &'static str,
|
||||
box_b: &'static str,
|
||||
box_c: &'static str,
|
||||
heat_neg: &'static str,
|
||||
heat_pos: &'static str,
|
||||
}
|
||||
|
||||
impl Theme {
|
||||
fn of(name: ThemeName) -> Self {
|
||||
match name {
|
||||
ThemeName::Dark => Self {
|
||||
name,
|
||||
bg: "#0a0e14",
|
||||
ink: "#e8eef6",
|
||||
muted: "#93a4b8",
|
||||
stroke: "#6b7f96",
|
||||
box_a: "#1e3a5f",
|
||||
box_b: "#3d2e14",
|
||||
box_c: "#1e3f2e",
|
||||
heat_neg: "#cc5555",
|
||||
heat_pos: "#4c8fff",
|
||||
},
|
||||
ThemeName::Light => Self {
|
||||
name,
|
||||
bg: "#eef3f9",
|
||||
ink: "#15202b",
|
||||
muted: "#5a6a7a",
|
||||
stroke: "#4a5a6a",
|
||||
box_a: "#e8f1ff",
|
||||
box_b: "#fff3d6",
|
||||
box_c: "#e8ffe8",
|
||||
heat_neg: "#cc3333",
|
||||
heat_pos: "#2266aa",
|
||||
},
|
||||
ThemeName::Bw => Self {
|
||||
name,
|
||||
bg: "#ffffff",
|
||||
ink: "#111111",
|
||||
muted: "#555555",
|
||||
stroke: "#222222",
|
||||
box_a: "#f0f0f0",
|
||||
box_b: "#e0e0e0",
|
||||
box_c: "#d0d0d0",
|
||||
heat_neg: "#000000",
|
||||
heat_pos: "#666666",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a factor object or matrix as structure SVG.
|
||||
pub fn draw_factor(factor: &Value, kind: Option<&str>, path: Option<&str>) -> Result<String, String> {
|
||||
pub fn draw_factor(
|
||||
factor: &Value,
|
||||
kind: Option<&str>,
|
||||
path: Option<&str>,
|
||||
theme: ThemeName,
|
||||
) -> Result<String, String> {
|
||||
let kind = kind
|
||||
.or_else(|| factor.get("kind").and_then(|k| k.as_str()))
|
||||
.unwrap_or("structure");
|
||||
let th = Theme::of(theme);
|
||||
let svg = match kind {
|
||||
"eig" => draw_eig(factor),
|
||||
"svd" => draw_svd(factor),
|
||||
"qr" => draw_qr(factor),
|
||||
"lu" | "ge" => draw_lu(factor),
|
||||
"chol" => draw_chol(factor),
|
||||
"structure" => draw_structure(factor),
|
||||
"heatmap" | "hinton" => draw_heatmap(factor, kind == "hinton"),
|
||||
"eig" => draw_eig(factor, &th),
|
||||
"svd" => draw_svd(factor, &th),
|
||||
"qr" => draw_qr(factor, &th),
|
||||
"lu" | "ge" => draw_lu(factor, &th),
|
||||
"chol" => draw_chol(factor, &th),
|
||||
"structure" => draw_structure(factor, &th),
|
||||
"heatmap" | "hinton" => draw_heatmap(factor, kind == "hinton", &th),
|
||||
other => {
|
||||
return Err(format!(
|
||||
"unknown draw kind `{other}` (want eig|svd|qr|lu|ge|chol|structure|heatmap|hinton)"
|
||||
@@ -31,17 +119,29 @@ fn escape(s: &str) -> String {
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
fn box_svg(x: f64, y: f64, w: f64, h: f64, label: &str, fill: &str) -> String {
|
||||
fn box_svg(x: f64, y: f64, w: f64, h: f64, label: &str, fill: &str, th: &Theme) -> String {
|
||||
format!(
|
||||
"<rect x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\" fill=\"{fill}\" stroke=\"#333\" stroke-width=\"1.5\" rx=\"4\"/>\
|
||||
<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" dominant-baseline=\"middle\" font-size=\"16\" font-family=\"serif\">{}</text>",
|
||||
"<rect x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\" fill=\"{fill}\" stroke=\"{}\" stroke-width=\"1.5\" rx=\"4\"/>\
|
||||
<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" dominant-baseline=\"middle\" font-size=\"16\" font-family=\"serif\" fill=\"{}\">{}</text>",
|
||||
th.stroke,
|
||||
x + w / 2.0,
|
||||
y + h / 2.0,
|
||||
th.ink,
|
||||
escape(label)
|
||||
)
|
||||
}
|
||||
|
||||
fn draw_eig(factor: &Value) -> String {
|
||||
fn root(w: f64, h: f64, kind: &str, th: &Theme, body: &str) -> String {
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\" data-linalg=\"{kind}\" data-theme=\"{}\" style=\"background:{}\">\
|
||||
{body}\
|
||||
</svg>",
|
||||
th.name.as_str(),
|
||||
th.bg
|
||||
)
|
||||
}
|
||||
|
||||
fn draw_eig(factor: &Value, th: &Theme) -> String {
|
||||
let latex = factor
|
||||
.get("latex")
|
||||
.and_then(|x| x.as_str())
|
||||
@@ -57,23 +157,24 @@ fn draw_eig(factor: &Value) -> String {
|
||||
.join(", ")
|
||||
})
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"520\" height=\"140\" data-linalg=\"eig\">\
|
||||
<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\">{}</text>\
|
||||
let body = format!(
|
||||
"<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\" fill=\"{}\">{}</text>\
|
||||
{}\
|
||||
{}\
|
||||
{}\
|
||||
<text x=\"16\" y=\"120\" font-size=\"13\" font-family=\"sans-serif\" fill=\"#444\">λ = [{}]</text>\
|
||||
</svg>",
|
||||
<text x=\"16\" y=\"120\" font-size=\"13\" font-family=\"sans-serif\" fill=\"{}\">λ = [{}]</text>",
|
||||
th.ink,
|
||||
escape(latex),
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "P", "#e8f1ff"),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "D", "#fff3d6"),
|
||||
box_svg(220.0, 48.0, 90.0, 50.0, "P⁻¹", "#e8f1ff"),
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "P", th.box_a, th),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "D", th.box_b, th),
|
||||
box_svg(220.0, 48.0, 90.0, 50.0, "P⁻¹", th.box_a, th),
|
||||
th.muted,
|
||||
escape(&evals)
|
||||
)
|
||||
);
|
||||
root(520.0, 140.0, "eig", th, &body)
|
||||
}
|
||||
|
||||
fn draw_svd(factor: &Value) -> String {
|
||||
fn draw_svd(factor: &Value, th: &Theme) -> String {
|
||||
let s = factor
|
||||
.get("S")
|
||||
.and_then(|x| x.as_array())
|
||||
@@ -85,61 +186,59 @@ fn draw_svd(factor: &Value) -> String {
|
||||
.join(", ")
|
||||
})
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"560\" height=\"140\" data-linalg=\"svd\">\
|
||||
<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\">A = U Σ V⊤</text>\
|
||||
let body = format!(
|
||||
"<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\" fill=\"{}\">A = U Σ V⊤</text>\
|
||||
{}\
|
||||
{}\
|
||||
{}\
|
||||
<text x=\"16\" y=\"120\" font-size=\"13\" font-family=\"sans-serif\" fill=\"#444\">σ = [{}]</text>\
|
||||
</svg>",
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "U", "#e8f1ff"),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "Σ", "#fff3d6"),
|
||||
box_svg(220.0, 48.0, 80.0, 50.0, "V⊤", "#e8f1ff"),
|
||||
<text x=\"16\" y=\"120\" font-size=\"13\" font-family=\"sans-serif\" fill=\"{}\">σ = [{}]</text>",
|
||||
th.ink,
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "U", th.box_a, th),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "Σ", th.box_b, th),
|
||||
box_svg(220.0, 48.0, 80.0, 50.0, "V⊤", th.box_a, th),
|
||||
th.muted,
|
||||
escape(&s)
|
||||
)
|
||||
);
|
||||
root(560.0, 140.0, "svd", th, &body)
|
||||
}
|
||||
|
||||
fn draw_qr(factor: &Value) -> String {
|
||||
let _ = factor;
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"420\" height=\"120\" data-linalg=\"qr\">\
|
||||
<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\">A = Q R</text>\
|
||||
fn draw_qr(_factor: &Value, th: &Theme) -> String {
|
||||
let body = format!(
|
||||
"<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\" fill=\"{}\">A = Q R</text>\
|
||||
{}\
|
||||
{}\
|
||||
</svg>",
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "Q", "#e8f1ff"),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "R", "#ffe8e8"),
|
||||
)
|
||||
{}",
|
||||
th.ink,
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "Q", th.box_a, th),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "R", th.box_b, th),
|
||||
);
|
||||
root(420.0, 120.0, "qr", th, &body)
|
||||
}
|
||||
|
||||
fn draw_lu(factor: &Value) -> String {
|
||||
let _ = factor;
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"420\" height=\"120\" data-linalg=\"lu\">\
|
||||
<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\">A = L U</text>\
|
||||
fn draw_lu(_factor: &Value, th: &Theme) -> String {
|
||||
let body = format!(
|
||||
"<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\" fill=\"{}\">A = L U</text>\
|
||||
{}\
|
||||
{}\
|
||||
</svg>",
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "L", "#e8ffe8"),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "U", "#ffe8e8"),
|
||||
)
|
||||
{}",
|
||||
th.ink,
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "L", th.box_c, th),
|
||||
box_svg(130.0, 48.0, 70.0, 50.0, "U", th.box_b, th),
|
||||
);
|
||||
root(420.0, 120.0, "lu", th, &body)
|
||||
}
|
||||
|
||||
fn draw_chol(factor: &Value) -> String {
|
||||
let _ = factor;
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"420\" height=\"120\" data-linalg=\"chol\">\
|
||||
<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\">A = L L⊤</text>\
|
||||
fn draw_chol(_factor: &Value, th: &Theme) -> String {
|
||||
let body = format!(
|
||||
"<text x=\"16\" y=\"28\" font-size=\"18\" font-family=\"serif\" fill=\"{}\">A = L L⊤</text>\
|
||||
{}\
|
||||
{}\
|
||||
</svg>",
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "L", "#e8ffe8"),
|
||||
box_svg(130.0, 48.0, 80.0, 50.0, "L⊤", "#e8ffe8"),
|
||||
)
|
||||
{}",
|
||||
th.ink,
|
||||
box_svg(40.0, 48.0, 70.0, 50.0, "L", th.box_c, th),
|
||||
box_svg(130.0, 48.0, 80.0, 50.0, "L⊤", th.box_c, th),
|
||||
);
|
||||
root(420.0, 120.0, "chol", th, &body)
|
||||
}
|
||||
|
||||
fn draw_structure(factor: &Value) -> String {
|
||||
fn draw_structure(factor: &Value, th: &Theme) -> String {
|
||||
let label = if let (Some(r), Some(c)) = (factor.get("rows"), factor.get("cols")) {
|
||||
format!("{}×{}", r, c)
|
||||
} else if let Some(Value::Array(a)) = factor.get("shape") {
|
||||
@@ -159,25 +258,17 @@ fn draw_structure(factor: &Value) -> String {
|
||||
.unwrap_or("matrix")
|
||||
.to_string()
|
||||
};
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"280\" height=\"120\" data-linalg=\"structure\">\
|
||||
{}\
|
||||
</svg>",
|
||||
box_svg(40.0, 30.0, 160.0, 60.0, &label, "#f4f4f4")
|
||||
)
|
||||
let body = box_svg(40.0, 30.0, 160.0, 60.0, &label, th.box_a, th);
|
||||
root(280.0, 120.0, "structure", th, &body)
|
||||
}
|
||||
|
||||
fn draw_heatmap(factor: &Value, hinton: bool) -> String {
|
||||
fn draw_heatmap(factor: &Value, hinton: bool, th: &Theme) -> String {
|
||||
let data = factor
|
||||
.get("data")
|
||||
.or_else(|| {
|
||||
factor
|
||||
.get("eigenvectors")
|
||||
.and_then(|v| v.get("data"))
|
||||
})
|
||||
.or_else(|| factor.get("eigenvectors").and_then(|v| v.get("data")))
|
||||
.and_then(|d| d.as_array());
|
||||
let Some(rows) = data else {
|
||||
return draw_structure(factor);
|
||||
return draw_structure(factor, th);
|
||||
};
|
||||
let n = rows.len().min(16);
|
||||
let m = rows
|
||||
@@ -187,34 +278,35 @@ fn draw_heatmap(factor: &Value, hinton: bool) -> String {
|
||||
.unwrap_or(0)
|
||||
.min(16);
|
||||
if n == 0 || m == 0 {
|
||||
return draw_structure(factor);
|
||||
return draw_structure(factor, th);
|
||||
}
|
||||
let mut max_abs: f64 = 1e-12;
|
||||
for row in rows.iter().take(n) {
|
||||
if let Some(cells) = row.as_array() {
|
||||
for c in cells.iter().take(m) {
|
||||
if let Some(v) = c.as_f64() {
|
||||
max_abs = max_abs.max(v.abs());
|
||||
}
|
||||
let v = cell_mag(c);
|
||||
max_abs = max_abs.max(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let cell = 18.0;
|
||||
let w = 40.0 + m as f64 * cell;
|
||||
let h = 40.0 + n as f64 * cell;
|
||||
let tag = if hinton { "hinton" } else { "heatmap" };
|
||||
let mut parts = vec![format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\" data-linalg=\"{}\">",
|
||||
if hinton { "hinton" } else { "heatmap" }
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\" data-linalg=\"{tag}\" data-theme=\"{}\" style=\"background:{}\">",
|
||||
th.name.as_str(),
|
||||
th.bg
|
||||
)];
|
||||
for (i, row) in rows.iter().take(n).enumerate() {
|
||||
let Some(cells) = row.as_array() else { continue };
|
||||
for (j, c) in cells.iter().take(m).enumerate() {
|
||||
let v = c.as_f64().unwrap_or(0.0);
|
||||
let v = cell_signed(c);
|
||||
let x = 20.0 + j as f64 * cell;
|
||||
let y = 20.0 + i as f64 * cell;
|
||||
if hinton {
|
||||
let s = (v.abs() / max_abs).sqrt() * (cell - 4.0);
|
||||
let fill = if v >= 0.0 { "#2266aa" } else { "#cc3333" };
|
||||
let fill = if v >= 0.0 { th.heat_pos } else { th.heat_neg };
|
||||
parts.push(format!(
|
||||
"<rect x=\"{}\" y=\"{}\" width=\"{s}\" height=\"{s}\" fill=\"{fill}\"/>",
|
||||
x + (cell - s) / 2.0,
|
||||
@@ -224,8 +316,15 @@ fn draw_heatmap(factor: &Value, hinton: bool) -> String {
|
||||
let t = ((v / max_abs) + 1.0) * 0.5;
|
||||
let r = (255.0 * (1.0 - t)) as u8;
|
||||
let b = (255.0 * t) as u8;
|
||||
let fill = if th.name == ThemeName::Bw {
|
||||
let g = (255.0 * (1.0 - v.abs() / max_abs)) as u8;
|
||||
format!("rgb({g},{g},{g})")
|
||||
} else {
|
||||
format!("rgb({r},80,{b})")
|
||||
};
|
||||
parts.push(format!(
|
||||
"<rect x=\"{x}\" y=\"{y}\" width=\"{cell}\" height=\"{cell}\" fill=\"rgb({r},80,{b})\" stroke=\"#fff\" stroke-width=\"0.5\"/>"
|
||||
"<rect x=\"{x}\" y=\"{y}\" width=\"{cell}\" height=\"{cell}\" fill=\"{fill}\" stroke=\"{}\" stroke-width=\"0.5\"/>",
|
||||
th.bg
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -233,3 +332,30 @@ fn draw_heatmap(factor: &Value, hinton: bool) -> String {
|
||||
parts.push("</svg>".into());
|
||||
parts.join("")
|
||||
}
|
||||
|
||||
fn cell_mag(c: &Value) -> f64 {
|
||||
if let Some(v) = c.as_f64() {
|
||||
return v.abs();
|
||||
}
|
||||
if let Some(a) = c.as_array() {
|
||||
if a.len() >= 2 {
|
||||
let re = a[0].as_f64().unwrap_or(0.0);
|
||||
let im = a[1].as_f64().unwrap_or(0.0);
|
||||
return (re * re + im * im).sqrt();
|
||||
}
|
||||
}
|
||||
0.0
|
||||
}
|
||||
|
||||
fn cell_signed(c: &Value) -> f64 {
|
||||
if let Some(v) = c.as_f64() {
|
||||
return v;
|
||||
}
|
||||
// complex: use real part for signed heatmap, magnitude for abs
|
||||
if let Some(a) = c.as_array() {
|
||||
if a.len() >= 2 {
|
||||
return a[0].as_f64().unwrap_or(0.0);
|
||||
}
|
||||
}
|
||||
0.0
|
||||
}
|
||||
@@ -15,6 +15,10 @@ fn check_side(n: usize, label: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn check_side_limit(n: usize, label: &str) -> Result<(), String> {
|
||||
check_side(n, label)
|
||||
}
|
||||
|
||||
fn check_mat(m: &Mat) -> Result<(usize, usize), String> {
|
||||
let (r, c) = dense::shape(m)?;
|
||||
dense::check_elems(r, c)?;
|
||||
|
||||
+76
-21
@@ -1,9 +1,11 @@
|
||||
//! Marqdo linalg plugin (C ABI v2): formula-first matrix expressions.
|
||||
|
||||
mod complex;
|
||||
mod dense;
|
||||
mod draw;
|
||||
mod factor;
|
||||
mod matexpr;
|
||||
mod metrics;
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
@@ -225,6 +227,11 @@ la_ffi!(linalg_ping, |_args: &Value| {
|
||||
"kron",
|
||||
"factorize",
|
||||
"draw",
|
||||
"lstsq",
|
||||
"norm",
|
||||
"cond",
|
||||
"rank",
|
||||
"complex",
|
||||
],
|
||||
}))
|
||||
});
|
||||
@@ -258,26 +265,11 @@ la_ffi!(linalg_from_list, |args: &Value| {
|
||||
.get("data")
|
||||
.or_else(|| args.get("数据"))
|
||||
.ok_or_else(|| "missing `data`".to_string())?;
|
||||
let rows = data
|
||||
.as_array()
|
||||
.ok_or_else(|| "`data` must be list of rows".to_string())?;
|
||||
let mut mat = Vec::new();
|
||||
for row in rows {
|
||||
let cells = row
|
||||
.as_array()
|
||||
.ok_or_else(|| "each row must be a list".to_string())?;
|
||||
let mut r = Vec::new();
|
||||
for c in cells {
|
||||
let n = c
|
||||
.as_f64()
|
||||
.or_else(|| c.as_i64().map(|i| i as f64))
|
||||
.or_else(|| c.as_u64().map(|u| u as f64))
|
||||
.ok_or_else(|| "cell must be a number".to_string())?;
|
||||
r.push(n);
|
||||
}
|
||||
mat.push(r);
|
||||
if complex::data_has_complex(data) {
|
||||
return complex::to_dense_value(&complex::from_data(data)?);
|
||||
}
|
||||
wrap(matexpr::from_list(mat)?)
|
||||
let m = dense::from_value(data)?;
|
||||
wrap(matexpr::from_list(m)?)
|
||||
});
|
||||
|
||||
la_ffi!(linalg_mul, |args: &Value| {
|
||||
@@ -476,23 +468,82 @@ la_ffi!(linalg_draw, |args: &Value| {
|
||||
.or_else(|| args.get("路径"))
|
||||
.and_then(|x| x.as_str())
|
||||
.filter(|s| !s.is_empty());
|
||||
let svg = draw::draw_factor(factor_v, kind, path)?;
|
||||
let theme = args
|
||||
.get("theme")
|
||||
.or_else(|| args.get("主题"))
|
||||
.and_then(|x| x.as_str())
|
||||
.map(draw::ThemeName::parse)
|
||||
.transpose()?
|
||||
.unwrap_or(draw::ThemeName::Light);
|
||||
let svg = draw::draw_factor(factor_v, kind, path, theme)?;
|
||||
let _ = record_plot(&svg, path);
|
||||
Ok(json!({
|
||||
"_type": "linalg_svg",
|
||||
"kind": kind
|
||||
.or_else(|| factor_v.get("kind").and_then(|k| k.as_str()))
|
||||
.unwrap_or("structure"),
|
||||
"theme": theme.as_str(),
|
||||
"svg": svg,
|
||||
}))
|
||||
});
|
||||
|
||||
la_ffi!(linalg_lstsq, |args: &Value| {
|
||||
let a = dense_arg(args, &["a", "A", "matrix", "矩阵", "左"])?;
|
||||
let b = dense_arg(args, &["b", "B", "rhs", "右"])?;
|
||||
metrics::lstsq(&a, &b)
|
||||
});
|
||||
|
||||
la_ffi!(linalg_norm, |args: &Value| {
|
||||
let ord = args
|
||||
.get("ord")
|
||||
.or_else(|| args.get("order"))
|
||||
.or_else(|| args.get("范数"))
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or("fro");
|
||||
if let Some(v) = args
|
||||
.get("expr")
|
||||
.or_else(|| args.get("a"))
|
||||
.or_else(|| args.get("matrix"))
|
||||
.or_else(|| args.get("式"))
|
||||
.or_else(|| args.get("矩阵"))
|
||||
{
|
||||
if v.get("dtype").and_then(|d| d.as_str()) == Some("complex")
|
||||
|| complex::from_value(v).is_ok()
|
||||
{
|
||||
if !matches!(ord, "fro" | "frobenius" | "f" | "") {
|
||||
return Err("complex norm only supports fro for now".into());
|
||||
}
|
||||
let cm = complex::from_value(v).or_else(|_| {
|
||||
v.get("data")
|
||||
.ok_or_else(|| "missing complex data".to_string())
|
||||
.and_then(complex::from_data)
|
||||
})?;
|
||||
return Ok(json!(complex::frobenius_norm(&cm)?));
|
||||
}
|
||||
}
|
||||
let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?;
|
||||
Ok(json!(metrics::norm(&m, ord)?))
|
||||
});
|
||||
|
||||
la_ffi!(linalg_cond, |args: &Value| {
|
||||
let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?;
|
||||
metrics::cond(&m)
|
||||
});
|
||||
|
||||
la_ffi!(linalg_rank, |args: &Value| {
|
||||
let m = dense_arg(args, &["expr", "a", "matrix", "式", "矩阵"])?;
|
||||
Ok(json!(metrics::rank(&m)?))
|
||||
});
|
||||
|
||||
fn dense_arg(args: &Value, keys: &[&str]) -> Result<dense::Mat, String> {
|
||||
for k in keys {
|
||||
if let Some(v) = args.get(*k) {
|
||||
if v.is_null() {
|
||||
continue;
|
||||
}
|
||||
if v.get("dtype").and_then(|d| d.as_str()) == Some("complex") {
|
||||
return Err("real dense op got dtype=complex (use norm fro on complex; factorize/solve stay real)".into());
|
||||
}
|
||||
if let Ok(e) = Expr::from_value(v) {
|
||||
return dense::explicit(&e);
|
||||
}
|
||||
@@ -550,7 +601,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
("linalg_block", "blocks", linalg_block as PluginFn),
|
||||
("linalg_collapse", "expr", linalg_collapse as PluginFn),
|
||||
("linalg_factorize", "matrix,kind", linalg_factorize as PluginFn),
|
||||
("linalg_draw", "factor,kind,path", linalg_draw as PluginFn),
|
||||
("linalg_draw", "factor,kind,path,theme", linalg_draw as PluginFn),
|
||||
("linalg_lstsq", "a,b", linalg_lstsq as PluginFn),
|
||||
("linalg_norm", "expr,ord", linalg_norm as PluginFn),
|
||||
("linalg_cond", "expr", linalg_cond as PluginFn),
|
||||
("linalg_rank", "expr", linalg_rank as PluginFn),
|
||||
];
|
||||
for (name, params, f) in regs {
|
||||
let c_name = CString::new(name).unwrap();
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Real dense metrics: lstsq, norm, cond, rank (L6).
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::dense::{self, Mat};
|
||||
use crate::factor;
|
||||
|
||||
/// Least squares `min ||A x - b||_2`. Tall: thin QR; wide/square: SVD pseudoinverse.
|
||||
pub fn lstsq(a: &Mat, b: &Mat) -> Result<Value, String> {
|
||||
let (m, n) = dense::shape(a)?;
|
||||
let (br, bc) = dense::shape(b)?;
|
||||
if br != m {
|
||||
return Err(format!("lstsq: A is {m}×{n} but b has {br} rows"));
|
||||
}
|
||||
factor::check_side_limit(m.max(n), "lstsq")?;
|
||||
let (x, residual_fro, method) = if m >= n {
|
||||
lstsq_qr(a, b)?
|
||||
} else {
|
||||
lstsq_svd(a, b)?
|
||||
};
|
||||
let residual_fro = if bc == 1 {
|
||||
residual_fro
|
||||
} else {
|
||||
// recompute full residual for multi-RHS
|
||||
let ax = dense::matmul(a, &x)?;
|
||||
frobenius_diff(&ax, b)
|
||||
};
|
||||
Ok(json!({
|
||||
"_type": "linalg_lstsq",
|
||||
"method": method,
|
||||
"x": dense::to_dense_value(&x)?,
|
||||
"residual_fro": residual_fro,
|
||||
}))
|
||||
}
|
||||
|
||||
fn lstsq_qr(a: &Mat, b: &Mat) -> Result<(Mat, f64, &'static str), String> {
|
||||
let (q, r) = factor::qr_decomp(a)?;
|
||||
let qt = dense::transpose(&q);
|
||||
let qtb = dense::matmul(&qt, b)?;
|
||||
let x = dense::solve(&r, &qtb)?;
|
||||
let ax = dense::matmul(a, &x)?;
|
||||
Ok((x, frobenius_diff(&ax, b), "qr"))
|
||||
}
|
||||
|
||||
fn lstsq_svd(a: &Mat, b: &Mat) -> Result<(Mat, f64, &'static str), String> {
|
||||
let (m, n) = dense::shape(a)?;
|
||||
let (_, bc) = dense::shape(b)?;
|
||||
let (u, s, vt) = factor::svd_decomp(a)?;
|
||||
let rank = n.min(m);
|
||||
let mut s_inv = vec![0.0; rank];
|
||||
let smax = s.first().copied().unwrap_or(0.0);
|
||||
let tol = smax * (m.max(n) as f64) * f64::EPSILON * 100.0;
|
||||
for i in 0..rank {
|
||||
if s[i] > tol {
|
||||
s_inv[i] = 1.0 / s[i];
|
||||
}
|
||||
}
|
||||
// x = V Σ⁺ Uᵀ b ; U is m×rank, Vt is rank×n
|
||||
let ut = dense::transpose(&u);
|
||||
let utb = dense::matmul(&ut, b)?; // rank×bc
|
||||
let mut mid = dense::zeros(rank, bc);
|
||||
for i in 0..rank {
|
||||
for j in 0..bc {
|
||||
mid[i][j] = s_inv[i] * utb[i][j];
|
||||
}
|
||||
}
|
||||
let v = dense::transpose(&vt); // n×rank
|
||||
let x = dense::matmul(&v, &mid)?;
|
||||
let ax = dense::matmul(a, &x)?;
|
||||
Ok((x, frobenius_diff(&ax, b), "svd"))
|
||||
}
|
||||
|
||||
fn frobenius_diff(a: &Mat, b: &Mat) -> f64 {
|
||||
let mut s = 0.0;
|
||||
for (ra, rb) in a.iter().zip(b.iter()) {
|
||||
for (&x, &y) in ra.iter().zip(rb.iter()) {
|
||||
let d = x - y;
|
||||
s += d * d;
|
||||
}
|
||||
}
|
||||
s.sqrt()
|
||||
}
|
||||
|
||||
/// Matrix norm: `fro` (default), `1`, `inf`, `2`.
|
||||
pub fn norm(m: &Mat, ord: &str) -> Result<f64, String> {
|
||||
let (rows, cols) = dense::shape(m)?;
|
||||
match ord.trim().to_ascii_lowercase().as_str() {
|
||||
"fro" | "frobenius" | "f" | "" => {
|
||||
let mut s = 0.0;
|
||||
for row in m {
|
||||
for &v in row {
|
||||
s += v * v;
|
||||
}
|
||||
}
|
||||
Ok(s.sqrt())
|
||||
}
|
||||
"1" | "one" => {
|
||||
let mut best: f64 = 0.0;
|
||||
for j in 0..cols {
|
||||
let mut col = 0.0;
|
||||
for i in 0..rows {
|
||||
col += m[i][j].abs();
|
||||
}
|
||||
best = best.max(col);
|
||||
}
|
||||
Ok(best)
|
||||
}
|
||||
"inf" | "infty" | "∞" => {
|
||||
let mut best: f64 = 0.0;
|
||||
for row in m {
|
||||
let mut r = 0.0;
|
||||
for &v in row {
|
||||
r += v.abs();
|
||||
}
|
||||
best = best.max(r);
|
||||
}
|
||||
Ok(best)
|
||||
}
|
||||
"2" | "spectral" => {
|
||||
let (_, s, _) = factor::svd_decomp(m)?;
|
||||
Ok(s.first().copied().unwrap_or(0.0))
|
||||
}
|
||||
other => Err(format!(
|
||||
"unknown norm `{other}` (want fro|1|inf|2)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 2-norm condition number σ_max / σ_min (∞ if rank-deficient).
|
||||
pub fn cond(m: &Mat) -> Result<Value, String> {
|
||||
let (rows, cols) = dense::shape(m)?;
|
||||
let (_, s, _) = factor::svd_decomp(m)?;
|
||||
let smax = s.first().copied().unwrap_or(0.0);
|
||||
let smin = s
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&x| x > 0.0)
|
||||
.last()
|
||||
.unwrap_or(0.0);
|
||||
let tol = smax * (rows.max(cols) as f64) * f64::EPSILON * 100.0;
|
||||
let (value, infinite) = if smin <= tol {
|
||||
(f64::INFINITY, true)
|
||||
} else {
|
||||
(smax / smin, false)
|
||||
};
|
||||
Ok(json!({
|
||||
"_type": "linalg_cond",
|
||||
"ord": 2,
|
||||
"value": if infinite { Value::Null } else { json!(value) },
|
||||
"infinite": infinite,
|
||||
"sigma_max": smax,
|
||||
"sigma_min": smin,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Numerical rank via SVD.
|
||||
pub fn rank(m: &Mat) -> Result<usize, String> {
|
||||
let (rows, cols) = dense::shape(m)?;
|
||||
let (_, s, _) = factor::svd_decomp(m)?;
|
||||
let smax = s.first().copied().unwrap_or(0.0);
|
||||
let tol = smax * (rows.max(cols) as f64) * f64::EPSILON * 100.0;
|
||||
Ok(s.iter().filter(|&&x| x > tol).count())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lstsq_line_fit() {
|
||||
// points (0,1), (1,2), (2,2) → line ≈ 1.1667 + 0.5 t
|
||||
let a = vec![vec![1.0, 0.0], vec![1.0, 1.0], vec![1.0, 2.0]];
|
||||
let b = vec![vec![1.0], vec![2.0], vec![2.0]];
|
||||
let out = lstsq(&a, &b).unwrap();
|
||||
let x = dense::from_value(out.get("x").unwrap()).unwrap();
|
||||
assert!((x[0][0] - 7.0 / 6.0).abs() < 1e-9);
|
||||
assert!((x[1][0] - 0.5).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fro_identity() {
|
||||
let i = dense::eye(3);
|
||||
assert!((norm(&i, "fro").unwrap() - 3f64.sqrt()).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cond_diag() {
|
||||
let m = vec![vec![2.0, 0.0], vec![0.0, 1.0]];
|
||||
let c = cond(&m).unwrap();
|
||||
assert_eq!(c["infinite"], false);
|
||||
assert!((c["value"].as_f64().unwrap() - 2.0).abs() < 1e-9);
|
||||
assert_eq!(rank(&m).unwrap(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
title: linalg metrics smoke (L6)
|
||||
description: lstsq, norm, cond, rank, complex fro, themed draw.
|
||||
import la:ext/linalg/linalg.mq.md
|
||||
import math:lib/math.mq.md
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`A` =
|
||||
$$
|
||||
\begin{bmatrix}1&0\\1&1\\1&2\end{bmatrix}
|
||||
$$
|
||||
|
||||
`b` =
|
||||
$$
|
||||
\begin{pmatrix}1\\2\\2\end{pmatrix}
|
||||
$$
|
||||
|
||||
*`A` = > la.from_formula formula=`A`*
|
||||
*`b` = > la.from_formula formula=`b`*
|
||||
*`eps` = > math.div a=1 b=1000*
|
||||
|
||||
*`ls` = > la.lstsq a=`A` b=`b`*
|
||||
*`x` = ls[^x]*
|
||||
*`xd` = x[^data]*
|
||||
*`r0` = > at value=`xd` index=0*
|
||||
*`x0` = > at value=`r0` index=0*
|
||||
*`e0` = > math.sub a=`x0` b=1.1666666667*
|
||||
*`e0` = > math.abs value=`e0`*
|
||||
1. `e0` < `eps`
|
||||
> print text=lstsq-ok
|
||||
2. *
|
||||
> print text=lstsq-fail
|
||||
|
||||
*`nf` = > la.norm expr=`A` ord="fro"*
|
||||
*`n0` = > math.sub a=`nf` b=2.8284271247*
|
||||
*`n0` = > math.abs value=`n0`*
|
||||
1. `n0` < `eps`
|
||||
> print text=norm-ok
|
||||
2. *
|
||||
> print text=norm-fail
|
||||
|
||||
`D` =
|
||||
$$
|
||||
\begin{bmatrix}2&0\\0&1\end{bmatrix}
|
||||
$$
|
||||
|
||||
*`D` = > la.from_formula formula=`D`*
|
||||
*`c` = > la.cond expr=`D`*
|
||||
*`cv` = c[^value]*
|
||||
*`ce` = > math.sub a=`cv` b=2*
|
||||
*`ce` = > math.abs value=`ce`*
|
||||
1. `ce` < `eps`
|
||||
> print text=cond-ok
|
||||
2. *
|
||||
> print text=cond-fail
|
||||
|
||||
*`rk` = > la.rank expr=`D`*
|
||||
1. `rk` == 2
|
||||
> print text=rank-ok
|
||||
2. *
|
||||
> print text=rank-fail
|
||||
|
||||
*`raw` = > json.parse text="[[[0,1],[1,0]],[[1,0],[0,-1]]]"*
|
||||
*`Z` = > la.from_list data=`raw`*
|
||||
*`dt` = Z[^dtype]*
|
||||
1. `dt` == complex
|
||||
> print text=complex-dtype-ok
|
||||
2. *
|
||||
> print text=complex-dtype-fail
|
||||
|
||||
*`zn` = > la.norm expr=`Z` ord="fro"*
|
||||
*`ze` = > math.sub a=`zn` b=2*
|
||||
*`ze` = > math.abs value=`ze`*
|
||||
1. `ze` < `eps`
|
||||
> print text=complex-norm-ok
|
||||
2. *
|
||||
> print text=complex-norm-fail
|
||||
|
||||
*`img` = > la.draw factor=`D` kind="heatmap" theme="dark" path="linalg-metrics-heat.svg"*
|
||||
*`th` = img[^theme]*
|
||||
1. `th` == dark
|
||||
> print text=theme-ok
|
||||
2. *
|
||||
> print text=theme-fail
|
||||
|
||||
*`svg` = img[^svg]*
|
||||
*`parts` = > split value=`svg` sep="data-theme=\"dark\""*
|
||||
*`pn` = > len value=`parts`*
|
||||
1. `pn` > 1
|
||||
> print text=theme-mark-ok
|
||||
2. *
|
||||
> print text=theme-mark-fail
|
||||
@@ -2464,6 +2464,25 @@ txn-rollback-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_linalg_metrics_smoke() {
|
||||
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-metrics-smoke.mq.md",
|
||||
"lstsq-ok\nnorm-ok\ncond-ok\nrank-ok\ncomplex-dtype-ok\ncomplex-norm-ok\ntheme-ok\ntheme-mark-ok",
|
||||
);
|
||||
let svg = std::fs::read_to_string("tests/ext/linalg-metrics-heat.svg").unwrap_or_default();
|
||||
assert!(
|
||||
svg.contains(r#"data-theme="dark""#) && svg.contains(r#"data-linalg="heatmap""#),
|
||||
"expected themed heatmap svg"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_linalg_factor_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
|
||||
Reference in new issue
Block a user