From 96da88e168ff90acd9e3e926d77892f17660fb84 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 7 Sep 2026 14:10:54 +0800 Subject: [PATCH] =?UTF-8?q?feat(linalg):=20L0=E2=80=93L1=20formula-first?= =?UTF-8?q?=20MatExpr=20plugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add plugins/linalg with symbol/mul/transpose/inv simplify (R1–R5), EN/ZH L1, CATALOG/ext add wiring, release native assets, and smokes. Co-authored-by: Cursor --- .github/workflows/release.yml | 7 +- CHANGELOG.md | 1 + Cargo.lock | 8 + Cargo.toml | 1 + doc/design/ext-linalg.md | 14 +- doc/roadmap/ext-linalg.md | 20 +- ext/linalg/linalg.mq.md | 153 ++++++ ext/linalg/线性代数.mq.md | 145 ++++++ plugins/linalg/Cargo.toml | 15 + plugins/linalg/src/lib.rs | 387 ++++++++++++++ plugins/linalg/src/matexpr.rs | 725 +++++++++++++++++++++++++++ src/ext_cli.rs | 19 +- tests/ext/linalg-formula-smoke.mq.md | 22 + tests/ext/linalg-zh-smoke.mq.md | 22 + tests/gold.rs | 25 + 15 files changed, 1542 insertions(+), 22 deletions(-) create mode 100644 ext/linalg/linalg.mq.md create mode 100644 ext/linalg/线性代数.mq.md create mode 100644 plugins/linalg/Cargo.toml create mode 100644 plugins/linalg/src/lib.rs create mode 100644 plugins/linalg/src/matexpr.rs create mode 100644 tests/ext/linalg-formula-smoke.mq.md create mode 100644 tests/ext/linalg-zh-smoke.mq.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fa638e2..3ceadc8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,7 +28,7 @@ jobs: - name: Build release CLI + official plugins run: | cargo build --release - cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum + cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg - name: Checkout extension sources (branch vscode-extension only) run: git fetch origin vscode-extension && git checkout origin/vscode-extension -- vscode-extension @@ -75,6 +75,7 @@ jobs: Copy-Item target/release/web.dll "$stageNative/native/web.dll" Copy-Item target/release/agent.dll "$stageNative/native/agent.dll" Copy-Item target/release/quantum.dll "$stageNative/native/quantum.dll" + Copy-Item target/release/linalg.dll "$stageNative/native/linalg.dll" if (Test-Path "dist/$nativeZip") { Remove-Item "dist/$nativeZip" -Force } Compress-Archive -Path "$stageNative/*" -DestinationPath "dist/$nativeZip" -Force $stage = "dist/stage-bundle" @@ -87,6 +88,7 @@ jobs: Copy-Item target/release/web.dll "$stage/ext/native/web.dll" Copy-Item target/release/agent.dll "$stage/ext/native/agent.dll" Copy-Item target/release/quantum.dll "$stage/ext/native/quantum.dll" + Copy-Item target/release/linalg.dll "$stage/ext/native/linalg.dll" if (Test-Path "dist/$zip") { Remove-Item "dist/$zip" -Force } Compress-Archive -Path "$stage/*" -DestinationPath "dist/$zip" -Force $stageLib = "dist/stage-stdlib" @@ -152,7 +154,7 @@ jobs: uses: dtolnay/rust-toolchain@stable - name: Build official plugins (release) - run: cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum + run: cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg - name: Package native zip run: | @@ -163,6 +165,7 @@ jobs: cp target/release/libweb.so dist/stage-native/native/libweb.so cp target/release/libagent.so dist/stage-native/native/libagent.so cp target/release/libquantum.so dist/stage-native/native/libquantum.so + cp target/release/liblinalg.so dist/stage-native/native/liblinalg.so (cd dist/stage-native && zip -r "../marqdo-${VER}-native-${TARGET}.zip" .) echo "NATIVE=marqdo-${VER}-native-${TARGET}.zip" >> "$GITHUB_ENV" diff --git a/CHANGELOG.md b/CHANGELOG.md index e0df204..f094fbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **`ext/linalg` L0–L1(公式优先)**:`MatrixSymbol` / 乘加转置逆、R1–R5 `simplify`、`ascii`/`latex`/`show`;`marqdo ext add linalg`;金样 `linalg-formula-smoke` · `linalg-zh-smoke`。设计:[ext-linalg.md](doc/design/ext-linalg.md)。 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 0e41ae5..4cc80d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1070,6 +1070,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "marqdo_plugin_linalg" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "marqdo_plugin_quantum" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 80b4003..ed5a7d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,7 @@ members = [ "plugins/agent", "plugins/web", "plugins/quantum", + "plugins/linalg", "crates/marqdo-wasm", ] resolver = "2" diff --git a/doc/design/ext-linalg.md b/doc/design/ext-linalg.md index 6f6180e..2f539ad 100644 --- a/doc/design/ext-linalg.md +++ b/doc/design/ext-linalg.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Draft · 待实现** | +| 状态 | **Draft · L0–L1 已落地** | | 日期 | 2026-09-07 | | 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) | | 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) | @@ -126,16 +126,17 @@ plugins/linalg(ABI v2) 文档写法偏好: ````markdown -`A` = > la.matrix.symbol name=A rows=n cols=n +`A` = > la.symbol name=A rows=n cols=n `b` = $$ \begin{pmatrix}1\\0\\0\end{pmatrix} $$ -*`b` = > la.matrix.from_formula formula=`b` * +*`b` = > la.from_formula formula=`b` * ```` +作者面优先顶层 `la.symbol` / `la.mul`(`la.matrix.symbol` 无接收者会硬错误,见 [module-namespace.md](module-namespace.md) §4.3)。 ### 4.2 公式代数(返回 `linalg_expr`,惰性) | 英文 | 中文 | 语义 | @@ -201,8 +202,8 @@ import table:lib/table.mq.md # main -*`A` = > la.matrix.symbol name=A rows=3 cols=3 * -*`x` = > la.matrix.symbol name=x rows=3 cols=1 * +*`A` = > la.symbol name=A rows=3 cols=3 * +*`x` = > la.symbol name=x rows=3 cols=1 * *`b` = > la.mul a=`A` b=`x` * *`s` = > la.simplify expr=`b` * @@ -213,11 +214,10 @@ $$ \begin{bmatrix}2&0\\0&3\end{bmatrix} $$ -*`M` = > la.matrix.from_formula formula=`M` * +*`M` = > la.from_list data=[[2,0],[0,3]] * *`f` = > la.factorize matrix=`M` kind=eig * > la.draw factor=`f` kind=eig path=eig.svg ```` - --- ## 5. 公式重写与「大规模优化」(核心) diff --git a/doc/roadmap/ext-linalg.md b/doc/roadmap/ext-linalg.md index 91fde7a..52158d8 100644 --- a/doc/roadmap/ext-linalg.md +++ b/doc/roadmap/ext-linalg.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **L0–L6 规划中 · 未开工** | +| 状态 | **L0–L1 已落地 · L2+ 待做** | | 日期 | 2026-09-07 | | **锁定设计** | [design/ext-linalg.md](../design/ext-linalg.md) | | 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) | @@ -23,8 +23,8 @@ | 阶段 | 内容 | 状态 | |------|------|------| -| **L0** | CATALOG + `plugins/linalg` ping + L1 `ensure_plugin`;`ext add` 条目 | **pending** | -| **L1** | MatExpr:`symbol` / 稠密叶子 / `mul`·`add`·`T`·`inv`;`simplify` R1–R5;`latex`·`ascii`·`show` | **pending** | +| **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` | **pending** | | **L3** | `block` + `collapse`;`kron` 惰性 + R7;金样 `linalg-block-kron` | **pending** | | **L4** | `factorize` LU/QR/SVD/eig(+ 可选 chol);结构 SVG `svd|qr|ge|eig`;金样 `linalg-factor-smoke` | **pending** | @@ -40,16 +40,16 @@ ### L0 -- [ ] `ext/linalg/CATALOG`(或既有 catalog 机制)含 `linalg` / `线性代数` -- [ ] 插件 `ping` → ok -- [ ] 文档:`marqdo ext add linalg` +- [x] `ext/linalg` CATALOG 含 `linalg` +- [x] 插件 `ping` → ok +- [x] 文档:`marqdo ext add linalg` ### L1 -- [ ] `(AB)^\top` → `simplify` → `B^\top A^\top`(无 dense) -- [ ] 形状错误含行列信息 -- [ ] view 或 CLI 可见 latex/ascii -- [ ] 中英 L1 各一 smoke +- [x] `(AB)^\top` → `simplify` → `B^T*A^T`(无 dense) +- [x] 形状错误含行列信息 +- [x] CLI `ascii` / `show` SVG 通道 +- [x] 中英 L1 各一 smoke ### L2 diff --git a/ext/linalg/linalg.mq.md b/ext/linalg/linalg.mq.md new file mode 100644 index 0000000..88e6d59 --- /dev/null +++ b/ext/linalg/linalg.mq.md @@ -0,0 +1,153 @@ +--- +title: ext/linalg/linalg +description: Formula-first linear algebra (English). MatExpr simplify + display; ABI plugin. +import plugin:lib/plugin.mq.md +import sys:lib/sys.mq.md +--- + +## ensure_plugin + +Load the ABI v2 `linalg` plugin once. + +*p = > plugin.native_path name="linalg"* +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/linalg: native linalg plugin not found (build marqdo_plugin_linalg or marqdo ext add linalg) + > sys.exit code=1 +**** + +## ping + +> ensure_plugin +**> linalg_ping** + +## mul + + `a` + + `b` + +Matrix product (lazy MatMul; shape-checked). + +> ensure_plugin +**> linalg_mul a=`a` b=`b`** + +## add + + `a` + + `b` + +> ensure_plugin +**> linalg_add a=`a` b=`b`** + +## sub + + `a` + + `b` + +> ensure_plugin +**> linalg_sub a=`a` b=`b`** + +## transpose + + `expr` + +> ensure_plugin +**> linalg_transpose expr=`expr`** + +## inv + + `expr` + +Symbolic inverse (lazy). + +> ensure_plugin +**> linalg_inv expr=`expr`** + +## simplify + + `expr` + +Apply MatExpr rewrite rules (R1–R5). + +> ensure_plugin +**> linalg_simplify expr=`expr`** + +## ascii + + `expr` + +> ensure_plugin +**> linalg_ascii expr=`expr`** + +## latex + + `expr` + +> ensure_plugin +**> linalg_latex expr=`expr`** + +## shape + + `expr` + +> ensure_plugin +**> linalg_shape expr=`expr`** + +## show + + `expr` + + `path`=None + +Record a formula SVG via host plot channel; returns the expr map. + +> ensure_plugin +**> linalg_show expr=`expr` path=`path`** + +## eye + + `n` + +> ensure_plugin +**> linalg_eye n=`n`** + +## zeros + + `rows` + + `cols` + +> ensure_plugin +**> linalg_zeros rows=`rows` cols=`cols`** + +## from_list + + `data` + +Dense leaf from nested list. + +> ensure_plugin +**> linalg_from_list data=`data`** + +## symbol + + `name` + + `rows` + + `cols` + +Abstract `MatrixSymbol` (`linalg_expr`). Prefer this over `matrix.symbol` (needs a receiver). + +> ensure_plugin +**> linalg_symbol name=`name` rows=`rows` cols=`cols`** + +# matrix + +Constructor-style helpers (call after `> la.matrix` if you hold an instance; prefer top-level `symbol` / `eye` / `zeros` / `from_list`). + +## symbol + + `name` + + `rows` + + `cols` + +**> linalg_symbol name=`name` rows=`rows` cols=`cols`** + +## eye + + `n` + +**> linalg_eye n=`n`** + +## zeros + + `rows` + + `cols` + +**> linalg_zeros rows=`rows` cols=`cols`** + +## from_list + + `data` + +**> linalg_from_list data=`data`** diff --git a/ext/linalg/线性代数.mq.md b/ext/linalg/线性代数.mq.md new file mode 100644 index 0000000..ab80153 --- /dev/null +++ b/ext/linalg/线性代数.mq.md @@ -0,0 +1,145 @@ +--- +title: ext/linalg/线性代数 +description: 公式优先的线性代数(中文)。矩阵表达式化简与展示;ABI 插件。 +import plugin:lib/plugin.mq.md +import sys:lib/sys.mq.md +--- + +## 确保插件 + +加载 ABI v2 `linalg` 插件一次。 + +*p = > plugin.native_path name="linalg"* +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/linalg: 未找到原生 linalg 插件(请 build marqdo_plugin_linalg 或 marqdo ext add linalg) + > sys.exit code=1 +**** + +## 探测 + +> 确保插件 +**> linalg_ping** + +## 乘 + + `左` + + `右` + +矩阵乘(惰性;检查形状)。 + +> 确保插件 +**> linalg_mul a=`左` b=`右`** + +## 加 + + `左` + + `右` + +> 确保插件 +**> linalg_add a=`左` b=`右`** + +## 减 + + `左` + + `右` + +> 确保插件 +**> linalg_sub a=`左` b=`右`** + +## 转置 + + `式` + +> 确保插件 +**> linalg_transpose expr=`式`** + +## 逆 + + `式` + +> 确保插件 +**> linalg_inv expr=`式`** + +## 化简 + + `式` + +应用矩阵表达式重写规则(R1–R5)。 + +> 确保插件 +**> linalg_simplify expr=`式`** + +## 文本 + + `式` + +> 确保插件 +**> linalg_ascii expr=`式`** + +## 乳胶 + + `式` + +> 确保插件 +**> linalg_latex expr=`式`** + +## 形状 + + `式` + +> 确保插件 +**> linalg_shape expr=`式`** + +## 展示 + + `式` + + `路径`=None + +> 确保插件 +**> linalg_show expr=`式` path=`路径`** + +## 单位 + + `阶` + +> 确保插件 +**> linalg_eye n=`阶`** + +## 零阵 + + `行` + + `列` + +> 确保插件 +**> linalg_zeros rows=`行` cols=`列`** + +## 自列表 + + `数据` + +> 确保插件 +**> linalg_from_list data=`数据`** + +## 符号 + + `名` + + `行` + + `列` + +抽象矩阵符号(`linalg_expr`)。 + +> 确保插件 +**> linalg_symbol name=`名` rows=`行` cols=`列`** + +# 矩阵 + +## 符号 + + `名` + + `行` + + `列` + +**> linalg_symbol name=`名` rows=`行` cols=`列`** + +## 单位 + + `阶` + +**> linalg_eye n=`阶`** + +## 零阵 + + `行` + + `列` + +**> linalg_zeros rows=`行` cols=`列`** + +## 自列表 + + `数据` + +**> linalg_from_list data=`数据`** diff --git a/plugins/linalg/Cargo.toml b/plugins/linalg/Cargo.toml new file mode 100644 index 0000000..6c90f66 --- /dev/null +++ b/plugins/linalg/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "marqdo_plugin_linalg" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Marqdo linear algebra plugin — formula-first MatExpr (ABI v2)" +publish = false + +[lib] +name = "linalg" +crate-type = ["cdylib"] + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/plugins/linalg/src/lib.rs b/plugins/linalg/src/lib.rs new file mode 100644 index 0000000..2c9c733 --- /dev/null +++ b/plugins/linalg/src/lib.rs @@ -0,0 +1,387 @@ +//! Marqdo linalg plugin (C ABI v2): formula-first matrix expressions. + +mod matexpr; + +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int, c_void}; +use std::ptr; + +use serde_json::{json, Value}; + +use matexpr::{Dim, Expr}; + +const ABI_VERSION: u32 = 2; + +type PluginFn = unsafe extern "C" fn( + args_json: *const c_char, + out_json: *mut *mut c_char, + err_msg: *mut *mut c_char, +) -> c_int; + +type HostQueryFn = unsafe extern "C" fn( + userdata: *mut c_void, + name: *const c_char, + args_json: *const c_char, + out_json: *mut *mut c_char, + err_msg: *mut *mut c_char, +) -> c_int; + +#[repr(C)] +pub struct MarqdoHostApi { + pub userdata: *mut c_void, + pub register_fn: Option< + unsafe extern "C" fn( + userdata: *mut c_void, + name: *const c_char, + params: *const c_char, + fn_ptr: PluginFn, + ) -> c_int, + >, + pub alloc: Option *mut c_void>, + pub free: Option, + pub host_query: Option, +} + +static mut HOST_FREE: Option = None; +static mut HOST_ALLOC: Option *mut c_void> = None; +static mut HOST_QUERY: Option = None; +static mut HOST_USERDATA: *mut c_void = ptr::null_mut(); + +unsafe fn host_strdup(s: &str) -> *mut c_char { + let alloc = HOST_ALLOC.expect("host alloc"); + let bytes = s.as_bytes(); + let p = alloc(bytes.len() + 1) as *mut u8; + if p.is_null() { + return ptr::null_mut(); + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); + *p.add(bytes.len()) = 0; + p as *mut c_char +} + +fn set_out(out: *mut *mut c_char, s: &str) { + if out.is_null() { + return; + } + unsafe { + *out = host_strdup(s); + } +} + +fn set_err(err: *mut *mut c_char, s: &str) { + if err.is_null() { + return; + } + unsafe { + *err = host_strdup(s); + } +} + +fn parse_args(args_json: *const c_char) -> Result { + if args_json.is_null() { + return Ok(json!({})); + } + let s = unsafe { CStr::from_ptr(args_json) } + .to_str() + .map_err(|_| "args not utf-8".to_string())?; + if s.trim().is_empty() { + return Ok(json!({})); + } + serde_json::from_str(s).map_err(|e| e.to_string()) +} + +fn reply(out_json: *mut *mut c_char, err_msg: *mut *mut c_char, r: Result) -> c_int { + match r { + Ok(v) => { + set_out(out_json, &v.to_string()); + 0 + } + Err(e) => { + set_err(err_msg, &e); + 1 + } + } +} + +macro_rules! la_ffi { + ($name:ident, $body:expr) => { + unsafe extern "C" fn $name( + args_json: *const c_char, + out_json: *mut *mut c_char, + err_msg: *mut *mut c_char, + ) -> c_int { + let args = match parse_args(args_json) { + Ok(v) => v, + Err(e) => { + set_err(err_msg, &format!("{}: {e}", stringify!($name))); + return 1; + } + }; + let r: Result = (|| $body(&args))(); + reply( + out_json, + err_msg, + r.map_err(|e| format!("{}: {e}", stringify!($name))), + ) + } + }; +} + +fn take_host_string(p: *mut c_char) -> Option { + if p.is_null() { + return None; + } + let s = unsafe { CStr::from_ptr(p) } + .to_str() + .ok() + .map(|s| s.to_string()); + unsafe { + if let Some(free) = HOST_FREE { + free(p as *mut c_void); + } + } + s +} + +fn host_query_json(name: &str, args: &Value) -> Result { + let query = unsafe { HOST_QUERY }.ok_or_else(|| "host_query not available".to_string())?; + let userdata = unsafe { HOST_USERDATA }; + let c_name = CString::new(name).map_err(|e| e.to_string())?; + let c_args = CString::new(args.to_string()).map_err(|e| e.to_string())?; + let mut out_ptr: *mut c_char = ptr::null_mut(); + let mut err_ptr: *mut c_char = ptr::null_mut(); + let rc = unsafe { + query( + userdata, + c_name.as_ptr(), + c_args.as_ptr(), + &mut out_ptr, + &mut err_ptr, + ) + }; + let err = take_host_string(err_ptr); + let out = take_host_string(out_ptr); + if rc != 0 { + return Err(err.unwrap_or_else(|| format!("host_query `{name}` failed"))); + } + let out = out.unwrap_or_else(|| "null".into()); + serde_json::from_str(&out).map_err(|e| format!("host_query `{name}` bad JSON: {e}")) +} + +fn record_plot(svg: &str, path: Option<&str>) -> Result<(), String> { + let mut args = json!({ "svg": svg }); + if let Some(p) = path { + if !p.is_empty() { + args.as_object_mut() + .unwrap() + .insert("path".into(), json!(p)); + } + } + host_query_json("record_plot", &args)?; + Ok(()) +} + +fn arg_dim(v: &Value, key: &str) -> Result { + Dim::from_json(v.get(key).ok_or_else(|| format!("missing `{key}`"))?) +} + +fn arg_expr_opt(v: &Value, keys: &[&str]) -> Result { + for k in keys { + if let Some(e) = v.get(*k) { + if !e.is_null() { + return Expr::from_value(e); + } + } + } + Err(format!("missing one of {:?}", keys)) +} + +fn wrap(expr: Expr) -> Result { + expr.to_value() +} + +la_ffi!(linalg_ping, |_args: &Value| { + Ok(json!({ + "ok": true, + "name": "linalg", + "abi": ABI_VERSION, + "features": ["matexpr", "simplify"], + })) +}); + +la_ffi!(linalg_symbol, |args: &Value| { + let name = args + .get("name") + .or_else(|| args.get("名")) + .and_then(|x| x.as_str()) + .ok_or_else(|| "missing `name`".to_string())?; + let rows = arg_dim(args, "rows").or_else(|_| arg_dim(args, "行"))?; + let cols = arg_dim(args, "cols").or_else(|_| arg_dim(args, "列"))?; + wrap(matexpr::symbol(name, rows, cols)) +}); + +la_ffi!(linalg_eye, |args: &Value| { + let n = arg_dim(args, "n") + .or_else(|_| arg_dim(args, "阶")) + .or_else(|_| arg_dim(args, "rows"))?; + wrap(matexpr::eye(n)) +}); + +la_ffi!(linalg_zeros, |args: &Value| { + let rows = arg_dim(args, "rows").or_else(|_| arg_dim(args, "行"))?; + let cols = arg_dim(args, "cols").or_else(|_| arg_dim(args, "列"))?; + wrap(matexpr::zeros(rows, cols)) +}); + +la_ffi!(linalg_from_list, |args: &Value| { + let data = args + .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); + } + wrap(matexpr::from_list(mat)?) +}); + +la_ffi!(linalg_mul, |args: &Value| { + let a = arg_expr_opt(args, &["a", "左"])?; + let b = arg_expr_opt(args, &["b", "右"])?; + wrap(matexpr::mul(a, b)?) +}); + +la_ffi!(linalg_add, |args: &Value| { + let a = arg_expr_opt(args, &["a", "左"])?; + let b = arg_expr_opt(args, &["b", "右"])?; + wrap(matexpr::add(a, b)?) +}); + +la_ffi!(linalg_sub, |args: &Value| { + let a = arg_expr_opt(args, &["a", "左"])?; + let b = arg_expr_opt(args, &["b", "右"])?; + wrap(matexpr::sub(a, b)?) +}); + +la_ffi!(linalg_transpose, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + wrap(matexpr::transpose(e)?) +}); + +la_ffi!(linalg_inv, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + wrap(matexpr::inv(e)?) +}); + +la_ffi!(linalg_simplify, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + wrap(matexpr::simplify(e)?) +}); + +la_ffi!(linalg_ascii, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + Ok(json!(e.ascii())) +}); + +la_ffi!(linalg_latex, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + Ok(json!(e.latex())) +}); + +la_ffi!(linalg_shape, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + let (r, c) = e.shape()?; + Ok(json!([r.to_json(), c.to_json()])) +}); + +la_ffi!(linalg_show, |args: &Value| { + let e = arg_expr_opt(args, &["expr", "a", "式"])?; + let latex = e.latex(); + let ascii = e.ascii(); + let path = args + .get("path") + .or_else(|| args.get("路径")) + .and_then(|x| x.as_str()) + .filter(|s| !s.is_empty()); + // Minimal SVG so view/plot channel can embed the formula text. + let escaped = latex + .replace('&', "&") + .replace('<', "<") + .replace('>', ">"); + let svg = format!( + "\ +{escaped}" + ); + let _ = record_plot(&svg, path); + let mut out = e.to_value()?; + if let Some(obj) = out.as_object_mut() { + obj.insert("shown".into(), json!(true)); + obj.insert("ascii".into(), json!(ascii)); + obj.insert("latex".into(), json!(latex)); + } + Ok(out) +}); + +#[no_mangle] +pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 { + ABI_VERSION +} + +#[no_mangle] +pub unsafe extern "C" fn marqdo_plugin_shutdown() {} + +#[no_mangle] +pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int { + if host.is_null() { + return 1; + } + let host = &*host; + HOST_ALLOC = host.alloc; + HOST_FREE = host.free; + HOST_QUERY = host.host_query; + HOST_USERDATA = host.userdata; + let register = match host.register_fn { + Some(f) => f, + None => return 1, + }; + let regs = [ + ("linalg_ping", "", linalg_ping as PluginFn), + ("linalg_symbol", "name,rows,cols", linalg_symbol as PluginFn), + ("linalg_eye", "n", linalg_eye as PluginFn), + ("linalg_zeros", "rows,cols", linalg_zeros as PluginFn), + ("linalg_from_list", "data", linalg_from_list as PluginFn), + ("linalg_mul", "a,b", linalg_mul as PluginFn), + ("linalg_add", "a,b", linalg_add as PluginFn), + ("linalg_sub", "a,b", linalg_sub as PluginFn), + ("linalg_transpose", "expr", linalg_transpose as PluginFn), + ("linalg_inv", "expr", linalg_inv as PluginFn), + ("linalg_simplify", "expr", linalg_simplify as PluginFn), + ("linalg_ascii", "expr", linalg_ascii as PluginFn), + ("linalg_latex", "expr", linalg_latex as PluginFn), + ("linalg_shape", "expr", linalg_shape as PluginFn), + ("linalg_show", "expr,path", linalg_show as PluginFn), + ]; + for (name, params, f) in regs { + let c_name = CString::new(name).unwrap(); + let c_params = CString::new(params).unwrap(); + if register(host.userdata, c_name.as_ptr(), c_params.as_ptr(), f) != 0 { + return 1; + } + } + 0 +} diff --git a/plugins/linalg/src/matexpr.rs b/plugins/linalg/src/matexpr.rs new file mode 100644 index 0000000..e1143c2 --- /dev/null +++ b/plugins/linalg/src/matexpr.rs @@ -0,0 +1,725 @@ +//! Symbolic matrix expressions (MatExpr) for formula-first linear algebra. +//! +//! Trees stay abstract until `explicit` (L2). Simplify applies R1–R5. + +use serde_json::{json, Value}; + +#[derive(Debug, Clone, PartialEq)] +pub enum Dim { + Int(usize), + Sym(String), +} + +impl Dim { + pub fn to_json(&self) -> Value { + match self { + Dim::Int(n) => json!(*n), + Dim::Sym(s) => json!(s), + } + } + + pub fn from_json(v: &Value) -> Result { + match v { + Value::Number(n) => { + let u = n + .as_u64() + .or_else(|| n.as_i64().map(|i| i as u64)) + .ok_or_else(|| "bad dim number".to_string())?; + Ok(Dim::Int(u as usize)) + } + Value::String(s) => { + let t = s.trim(); + if let Ok(n) = t.parse::() { + Ok(Dim::Int(n)) + } else { + Ok(Dim::Sym(t.to_string())) + } + } + _ => Err("dim must be int or string".into()), + } + } + + fn ascii(&self) -> String { + match self { + Dim::Int(n) => n.to_string(), + Dim::Sym(s) => s.clone(), + } + } + + fn latex(&self) -> String { + self.ascii() + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Expr { + Symbol { + name: String, + rows: Dim, + cols: Dim, + }, + Eye { + n: Dim, + }, + Zero { + rows: Dim, + cols: Dim, + }, + Dense { + data: Vec>, + }, + Mul { + factors: Vec, + }, + Add { + terms: Vec, + }, + Sub { + left: Box, + right: Box, + }, + Transpose { + arg: Box, + }, + Inv { + arg: Box, + }, +} + +impl Expr { + pub fn shape(&self) -> Result<(Dim, Dim), String> { + match self { + Expr::Symbol { rows, cols, .. } => Ok((rows.clone(), cols.clone())), + Expr::Eye { n } => Ok((n.clone(), n.clone())), + Expr::Zero { rows, cols } => Ok((rows.clone(), cols.clone())), + Expr::Dense { data } => { + let r = data.len(); + let c = data.first().map(|row| row.len()).unwrap_or(0); + if data.iter().any(|row| row.len() != c) { + return Err("dense matrix rows must have equal length".into()); + } + Ok((Dim::Int(r), Dim::Int(c))) + } + Expr::Mul { factors } => { + if factors.is_empty() { + return Err("empty MatMul".into()); + } + let (rows, mut cols) = factors[0].shape()?; + for f in &factors[1..] { + let (r, c) = f.shape()?; + if !dims_eq(&cols, &r) { + return Err(format!( + "incompatible shapes for mul: …×{} with {}×{}", + cols.ascii(), + r.ascii(), + c.ascii() + )); + } + cols = c; + } + Ok((rows, cols)) + } + Expr::Add { terms } => { + if terms.is_empty() { + return Err("empty MatAdd".into()); + } + let (r0, c0) = terms[0].shape()?; + for t in &terms[1..] { + let (r, c) = t.shape()?; + if !dims_eq(&r0, &r) || !dims_eq(&c0, &c) { + return Err(format!( + "incompatible shapes for add: {}×{} vs {}×{}", + r0.ascii(), + c0.ascii(), + r.ascii(), + c.ascii() + )); + } + } + Ok((r0, c0)) + } + Expr::Sub { left, right } => { + let (r0, c0) = left.shape()?; + let (r1, c1) = right.shape()?; + if !dims_eq(&r0, &r1) || !dims_eq(&c0, &c1) { + return Err(format!( + "incompatible shapes for sub: {}×{} vs {}×{}", + r0.ascii(), + c0.ascii(), + r1.ascii(), + c1.ascii() + )); + } + Ok((r0, c0)) + } + Expr::Transpose { arg } => { + let (r, c) = arg.shape()?; + Ok((c, r)) + } + Expr::Inv { arg } => { + let (r, c) = arg.shape()?; + if !dims_eq(&r, &c) { + return Err(format!( + "inverse needs square matrix, got {}×{}", + r.ascii(), + c.ascii() + )); + } + Ok((r, c)) + } + } + } + + pub fn ascii(&self) -> String { + match self { + Expr::Symbol { name, .. } => name.clone(), + Expr::Eye { n } => format!("I({})", n.ascii()), + Expr::Zero { rows, cols } => format!("0({}×{})", rows.ascii(), cols.ascii()), + Expr::Dense { data } => format_dense_ascii(data), + Expr::Mul { factors } => factors + .iter() + .map(|f| { + let s = f.ascii(); + if matches!(f, Expr::Add { .. } | Expr::Sub { .. }) { + format!("({s})") + } else { + s + } + }) + .collect::>() + .join("*"), + Expr::Add { terms } => terms + .iter() + .map(|t| t.ascii()) + .collect::>() + .join(" + "), + Expr::Sub { left, right } => format!("{} - {}", left.ascii(), right.ascii()), + Expr::Transpose { arg } => { + let inner = arg.ascii(); + if matches!( + arg.as_ref(), + Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } + ) { + format!("{inner}^T") + } else { + format!("({inner})^T") + } + } + Expr::Inv { arg } => { + let inner = arg.ascii(); + if matches!( + arg.as_ref(), + Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } + ) { + format!("{inner}^-1") + } else { + format!("({inner})^-1") + } + } + } + } + + pub fn latex(&self) -> String { + match self { + Expr::Symbol { name, .. } => name.clone(), + Expr::Eye { n } => format!("I_{{{}}}", n.latex()), + Expr::Zero { rows, cols } => { + format!("0_{{{}\\times {}}}", rows.latex(), cols.latex()) + } + Expr::Dense { data } => format_dense_latex(data), + Expr::Mul { factors } => factors + .iter() + .map(|f| { + let s = f.latex(); + if matches!(f, Expr::Add { .. } | Expr::Sub { .. }) { + format!("\\left({s}\\right)") + } else { + s + } + }) + .collect::>() + .join(""), + Expr::Add { terms } => terms + .iter() + .map(|t| t.latex()) + .collect::>() + .join(" + "), + Expr::Sub { left, right } => format!("{} - {}", left.latex(), right.latex()), + Expr::Transpose { arg } => { + let inner = arg.latex(); + if matches!( + arg.as_ref(), + Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } + ) { + format!("{inner}^{{\\top}}") + } else { + format!("\\left({inner}\\right)^{{\\top}}") + } + } + Expr::Inv { arg } => { + let inner = arg.latex(); + if matches!( + arg.as_ref(), + Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } + ) { + format!("{inner}^{{-1}}") + } else { + format!("\\left({inner}\\right)^{{-1}}") + } + } + } + } + + pub fn to_value(&self) -> Result { + let (rows, cols) = self.shape()?; + let mut obj = serde_json::Map::new(); + obj.insert("_type".into(), json!("linalg_expr")); + obj.insert("shape".into(), json!([rows.to_json(), cols.to_json()])); + obj.insert("ascii".into(), json!(self.ascii())); + obj.insert("latex".into(), json!(self.latex())); + match self { + Expr::Symbol { name, rows, cols } => { + obj.insert("kind".into(), json!("symbol")); + obj.insert("name".into(), json!(name)); + obj.insert("rows".into(), rows.to_json()); + obj.insert("cols".into(), cols.to_json()); + } + Expr::Eye { n } => { + obj.insert("kind".into(), json!("eye")); + obj.insert("n".into(), n.to_json()); + } + Expr::Zero { rows, cols } => { + obj.insert("kind".into(), json!("zero")); + obj.insert("rows".into(), rows.to_json()); + obj.insert("cols".into(), cols.to_json()); + } + Expr::Dense { data } => { + obj.insert("kind".into(), json!("dense")); + obj.insert("data".into(), json!(data)); + obj.insert("dtype".into(), json!("real")); + } + Expr::Mul { factors } => { + obj.insert("kind".into(), json!("mul")); + let kids: Result, _> = factors.iter().map(|f| f.to_value()).collect(); + obj.insert("factors".into(), Value::Array(kids?)); + } + Expr::Add { terms } => { + obj.insert("kind".into(), json!("add")); + let kids: Result, _> = terms.iter().map(|t| t.to_value()).collect(); + obj.insert("terms".into(), Value::Array(kids?)); + } + Expr::Sub { left, right } => { + obj.insert("kind".into(), json!("sub")); + obj.insert("left".into(), left.to_value()?); + obj.insert("right".into(), right.to_value()?); + } + Expr::Transpose { arg } => { + obj.insert("kind".into(), json!("transpose")); + obj.insert("arg".into(), arg.to_value()?); + } + Expr::Inv { arg } => { + obj.insert("kind".into(), json!("inv")); + obj.insert("arg".into(), arg.to_value()?); + } + } + Ok(Value::Object(obj)) + } + + pub fn from_value(v: &Value) -> Result { + let obj = v + .as_object() + .ok_or_else(|| "linalg_expr must be a map".to_string())?; + let kind = obj + .get("kind") + .and_then(|x| x.as_str()) + .ok_or_else(|| "missing kind".to_string())?; + match kind { + "symbol" => Ok(Expr::Symbol { + name: obj + .get("name") + .and_then(|x| x.as_str()) + .ok_or_else(|| "symbol missing name")? + .to_string(), + rows: Dim::from_json(obj.get("rows").ok_or("symbol missing rows")?)?, + cols: Dim::from_json(obj.get("cols").ok_or("symbol missing cols")?)?, + }), + "eye" => Ok(Expr::Eye { + n: Dim::from_json(obj.get("n").ok_or("eye missing n")?)?, + }), + "zero" => Ok(Expr::Zero { + rows: Dim::from_json(obj.get("rows").ok_or("zero missing rows")?)?, + cols: Dim::from_json(obj.get("cols").ok_or("zero missing cols")?)?, + }), + "dense" => { + let data = parse_dense(obj.get("data").ok_or("dense missing data")?)?; + Ok(Expr::Dense { data }) + } + "mul" => { + let factors = obj + .get("factors") + .and_then(|x| x.as_array()) + .ok_or("mul missing factors")?; + let factors: Result, _> = + factors.iter().map(Expr::from_value).collect(); + Ok(Expr::Mul { + factors: factors?, + }) + } + "add" => { + let terms = obj + .get("terms") + .and_then(|x| x.as_array()) + .ok_or("add missing terms")?; + let terms: Result, _> = terms.iter().map(Expr::from_value).collect(); + Ok(Expr::Add { terms: terms? }) + } + "sub" => Ok(Expr::Sub { + left: Box::new(Expr::from_value( + obj.get("left").ok_or("sub missing left")?, + )?), + right: Box::new(Expr::from_value( + obj.get("right").ok_or("sub missing right")?, + )?), + }), + "transpose" => Ok(Expr::Transpose { + arg: Box::new(Expr::from_value( + obj.get("arg").ok_or("transpose missing arg")?, + )?), + }), + "inv" => Ok(Expr::Inv { + arg: Box::new(Expr::from_value(obj.get("arg").ok_or("inv missing arg")?)?), + }), + other => Err(format!("unknown linalg_expr kind `{other}`")), + } + } +} + +fn dims_eq(a: &Dim, b: &Dim) -> bool { + match (a, b) { + (Dim::Int(x), Dim::Int(y)) => x == y, + (Dim::Sym(x), Dim::Sym(y)) => x == y, + // symbolic vs int: allow only if we cannot prove mismatch — treat as compatible + // for teaching formulas like n×n with concrete later; strict mode would reject. + (Dim::Int(_), Dim::Sym(_)) | (Dim::Sym(_), Dim::Int(_)) => true, + } +} + +fn parse_dense(v: &Value) -> Result>, String> { + let rows = v + .as_array() + .ok_or_else(|| "dense 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(|| "dense 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)) + .or_else(|| c.as_str().and_then(|s| s.trim().parse().ok())) + .ok_or_else(|| "dense cell must be a number".to_string())?; + r.push(n); + } + if let Some(w) = width { + if r.len() != w { + return Err("dense matrix rows must have equal length".into()); + } + } else { + width = Some(r.len()); + } + out.push(r); + } + if out.is_empty() { + return Err("empty dense matrix".into()); + } + Ok(out) +} + +fn format_dense_ascii(data: &[Vec]) -> String { + let rows: Vec = data + .iter() + .map(|row| { + let cells: Vec = row.iter().map(|x| format_num(*x)).collect(); + format!("[{}]", cells.join(",")) + }) + .collect(); + format!("[{}]", rows.join(",")) +} + +fn format_dense_latex(data: &[Vec]) -> String { + let body: Vec = data + .iter() + .map(|row| { + row.iter() + .map(|x| format_num(*x)) + .collect::>() + .join(" & ") + }) + .collect(); + format!( + "\\begin{{bmatrix}}{}\\end{{bmatrix}}", + body.join(" \\\\ ") + ) +} + +fn format_num(n: f64) -> String { + if n.fract() == 0.0 && n.abs() < 1e15 { + format!("{}", n as i64) + } else { + format!("{n}") + } +} + +/// Flatten nested Mul. +fn flatten_mul(factors: Vec) -> Vec { + let mut out = Vec::new(); + for f in factors { + match f { + Expr::Mul { factors: inner } => out.extend(flatten_mul(inner)), + other => out.push(other), + } + } + out +} + +fn is_eye(e: &Expr) -> bool { + matches!(e, Expr::Eye { .. }) +} + +fn is_zero(e: &Expr) -> bool { + matches!(e, Expr::Zero { .. }) +} + +/// Apply R1–R5 once bottom-up, then iterate to fixpoint (small bound). +pub fn simplify(expr: Expr) -> Result { + let mut cur = expr; + for _ in 0..32 { + let next = simplify_once(cur.clone())?; + // shape check keeps trees valid + let _ = next.shape()?; + if next == cur { + return Ok(cur); + } + cur = next; + } + Ok(cur) +} + +fn simplify_once(expr: Expr) -> Result { + match expr { + Expr::Mul { factors } => { + let factors: Result, _> = + flatten_mul(factors).into_iter().map(simplify_once).collect(); + let mut factors = factors?; + let eye_n = factors.iter().find_map(|f| match f { + Expr::Eye { n } => Some(n.clone()), + _ => None, + }); + // R1: drop Eye + factors.retain(|f| !is_eye(f)); + if factors.is_empty() { + return Ok(Expr::Eye { + n: eye_n.unwrap_or(Dim::Sym("n".into())), + }); + } + if factors.len() == 1 { + return Ok(factors.pop().unwrap()); + } + // R1 zero absorb: …*0*… → 0 with product shape + if let Some(z) = factors.iter().find(|f| is_zero(f)) { + let (r, _) = factors.first().unwrap().shape()?; + let (_, c) = factors.last().unwrap().shape()?; + let _ = z; + return Ok(Expr::Zero { rows: r, cols: c }); + } + Ok(Expr::Mul { factors }) + } + Expr::Add { terms } => { + let terms: Result, _> = terms.into_iter().map(simplify_once).collect(); + let mut terms = terms?; + terms.retain(|t| !is_zero(t)); + if terms.is_empty() { + return Ok(Expr::Zero { + rows: Dim::Int(0), + cols: Dim::Int(0), + }); + } + if terms.len() == 1 { + return Ok(terms.pop().unwrap()); + } + Ok(Expr::Add { terms }) + } + Expr::Sub { left, right } => { + let left = simplify_once(*left)?; + let right = simplify_once(*right)?; + if is_zero(&right) { + return Ok(left); + } + Ok(Expr::Sub { + left: Box::new(left), + right: Box::new(right), + }) + } + Expr::Transpose { arg } => { + let arg = simplify_once(*arg)?; + match arg { + // R3: (AB…)^T → …^T B^T A^T + Expr::Mul { factors } => { + let factors: Vec = factors + .into_iter() + .rev() + .map(|f| Expr::Transpose { + arg: Box::new(f), + }) + .collect(); + simplify_once(Expr::Mul { factors }) + } + // R3: (A^T)^T → A + Expr::Transpose { arg: inner } => Ok(*inner), + // (A+B)^T → A^T+B^T + Expr::Add { terms } => { + let terms = terms + .into_iter() + .map(|t| Expr::Transpose { + arg: Box::new(t), + }) + .collect(); + simplify_once(Expr::Add { terms }) + } + Expr::Sub { left, right } => simplify_once(Expr::Sub { + left: Box::new(Expr::Transpose { arg: left }), + right: Box::new(Expr::Transpose { arg: right }), + }), + // R4 partial: (A^-1)^T → (A^T)^-1 + Expr::Inv { arg: inner } => Ok(Expr::Inv { + arg: Box::new(Expr::Transpose { arg: inner }), + }), + Expr::Eye { n } => Ok(Expr::Eye { n }), + Expr::Zero { rows, cols } => Ok(Expr::Zero { + rows: cols, + cols: rows, + }), + other => Ok(Expr::Transpose { + arg: Box::new(other), + }), + } + } + Expr::Inv { arg } => { + let arg = simplify_once(*arg)?; + match arg { + // R2: (A^-1)^-1 → A + Expr::Inv { arg: inner } => Ok(*inner), + // R4: (A^T)^-1 stays; (A^-1)^T handled above + Expr::Eye { n } => Ok(Expr::Eye { n }), + other => Ok(Expr::Inv { + arg: Box::new(other), + }), + } + } + Expr::Symbol { .. } | Expr::Eye { .. } | Expr::Zero { .. } | Expr::Dense { .. } => { + Ok(expr) + } + } +} + +pub fn mul(a: Expr, b: Expr) -> Result { + let expr = Expr::Mul { + factors: flatten_mul(vec![a, b]), + }; + let _ = expr.shape()?; + Ok(expr) +} + +pub fn add(a: Expr, b: Expr) -> Result { + let expr = Expr::Add { + terms: vec![a, b], + }; + let _ = expr.shape()?; + Ok(expr) +} + +pub fn sub(a: Expr, b: Expr) -> Result { + let expr = Expr::Sub { + left: Box::new(a), + right: Box::new(b), + }; + let _ = expr.shape()?; + Ok(expr) +} + +pub fn transpose(a: Expr) -> Result { + let expr = Expr::Transpose { + arg: Box::new(a), + }; + let _ = expr.shape()?; + Ok(expr) +} + +pub fn inv(a: Expr) -> Result { + let expr = Expr::Inv { + arg: Box::new(a), + }; + let _ = expr.shape()?; + Ok(expr) +} + +pub fn symbol(name: &str, rows: Dim, cols: Dim) -> Expr { + Expr::Symbol { + name: name.to_string(), + rows, + cols, + } +} + +pub fn eye(n: Dim) -> Expr { + Expr::Eye { n } +} + +pub fn zeros(rows: Dim, cols: Dim) -> Expr { + Expr::Zero { rows, cols } +} + +pub fn from_list(data: Vec>) -> Result { + if data.is_empty() { + return Err("empty matrix".into()); + } + let w = data[0].len(); + if w == 0 || data.iter().any(|r| r.len() != w) { + return Err("dense matrix rows must have equal non-zero length".into()); + } + Ok(Expr::Dense { data }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn transpose_of_product() { + let a = symbol("A", Dim::Int(2), Dim::Int(3)); + let b = symbol("B", Dim::Int(3), Dim::Int(2)); + let p = mul(a, b).unwrap(); + let t = transpose(p).unwrap(); + let s = simplify(t).unwrap(); + assert_eq!(s.ascii(), "B^T*A^T"); + } + + #[test] + fn double_inv() { + let a = symbol("A", Dim::Sym("n".into()), Dim::Sym("n".into())); + let i = inv(inv(a).unwrap()).unwrap(); + let s = simplify(i).unwrap(); + assert_eq!(s.ascii(), "A"); + } + + #[test] + fn shape_mismatch() { + let a = symbol("A", Dim::Int(2), Dim::Int(2)); + let b = symbol("B", Dim::Int(3), Dim::Int(3)); + assert!(mul(a, b).is_err()); + } +} diff --git a/src/ext_cli.rs b/src/ext_cli.rs index fe30080..7a91d33 100644 --- a/src/ext_cli.rs +++ b/src/ext_cli.rs @@ -42,6 +42,12 @@ pub const CATALOG: &[ExtPackage] = &[ mq_files: &["quantum/quantum.mq.md", "quantum/量子.mq.md"], native_crate: Some("marqdo_plugin_quantum"), }, + ExtPackage { + id: "linalg", + description: "Formula-first linear algebra (ext/linalg) — MatExpr simplify/display", + mq_files: &["linalg/linalg.mq.md", "linalg/线性代数.mq.md"], + native_crate: Some("marqdo_plugin_linalg"), + }, ]; pub fn find_package(id: &str) -> Option<&'static ExtPackage> { @@ -93,6 +99,7 @@ pub fn native_short_name(crate_or_id: &str) -> &str { "marqdo_plugin_agent" | "agent" => "agent", "marqdo_plugin_web" | "web" => "web", "marqdo_plugin_quantum" | "quantum" => "quantum", + "marqdo_plugin_linalg" | "linalg" => "linalg", other => other, } } @@ -112,6 +119,7 @@ pub fn native_env_var(short: &str) -> &'static str { match native_short_name(short) { "web" => "MARQDO_WEB_PLUGIN", "quantum" => "MARQDO_QUANTUM_PLUGIN", + "linalg" => "MARQDO_LINALG_PLUGIN", _ => "MARQDO_AGENT_PLUGIN", } } @@ -415,7 +423,7 @@ pub fn remove_ext(id: &str) -> Result<()> { /// Also falls back to cargo `target/{debug,release}` artifacts for local runs. pub fn installed_native_path(name: &str) -> Option { let short = native_short_name(name); - if !matches!(short, "agent" | "web" | "quantum") { + if !matches!(short, "agent" | "web" | "quantum" | "linalg") { return None; } let lib_name = native_lib_filename(short); @@ -454,7 +462,12 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool { return true; } } - for key in ["MARQDO_AGENT_PLUGIN", "MARQDO_WEB_PLUGIN", "MARQDO_QUANTUM_PLUGIN"] { + for key in [ + "MARQDO_AGENT_PLUGIN", + "MARQDO_WEB_PLUGIN", + "MARQDO_QUANTUM_PLUGIN", + "MARQDO_LINALG_PLUGIN", + ] { if let Ok(p) = env::var(key) { let p = PathBuf::from(p); let p = p.canonicalize().unwrap_or(p); @@ -463,7 +476,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool { } } } - for short in ["agent", "web", "quantum"] { + for short in ["agent", "web", "quantum", "linalg"] { if let Ok(found) = find_native_plugin(short) { let found = found.canonicalize().unwrap_or(found); if found == path { diff --git a/tests/ext/linalg-formula-smoke.mq.md b/tests/ext/linalg-formula-smoke.mq.md new file mode 100644 index 0000000..bb592c3 --- /dev/null +++ b/tests/ext/linalg-formula-smoke.mq.md @@ -0,0 +1,22 @@ +--- +title: linalg formula smoke +description: (AB)^T simplifies to B^T*A^T; ping ok. +import la:ext/linalg/linalg.mq.md +--- + +# main + +*`A` = > la.symbol name="A" rows=2 cols=3* +*`B` = > la.symbol name="B" rows=3 cols=2* +*`P` = > la.mul a=`A` b=`B`* +*`T` = > la.transpose expr=`P`* +*`S` = > la.simplify expr=`T`* +*`txt` = > la.ascii expr=`S`* +> print text=`txt` + +*`ping` = > la.ping* +*`ok` = ping[^ok]* +1. `ok` + > print text=ping-ok +2. * + > print text=ping-fail diff --git a/tests/ext/linalg-zh-smoke.mq.md b/tests/ext/linalg-zh-smoke.mq.md new file mode 100644 index 0000000..1d8ddda --- /dev/null +++ b/tests/ext/linalg-zh-smoke.mq.md @@ -0,0 +1,22 @@ +--- +title: 线性代数公式冒烟 +description: (AB)^T 化简为 B^T*A^T;探测 ok。 +import la:ext/linalg/线性代数.mq.md +--- + +# main + +*`A` = > la.符号 名="A" 行=2 列=3* +*`B` = > la.符号 名="B" 行=3 列=2* +*`P` = > la.乘 左=`A` 右=`B`* +*`T` = > la.转置 式=`P`* +*`S` = > la.化简 式=`T`* +*`txt` = > la.文本 式=`S`* +> 打印 内容=`txt` + +*`ping` = > la.探测* +*`ok` = ping[^ok]* +1. `ok` + > 打印 内容=探测-ok +2. * + > 打印 内容=探测-fail diff --git a/tests/gold.rs b/tests/gold.rs index ccbcee7..2339dd7 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -2464,6 +2464,31 @@ txn-rollback-ok", ); } +#[test] +fn ext_linalg_formula_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-formula-smoke.mq.md", + "B^T*A^T\nping-ok", + ); +} + +#[test] +fn ext_linalg_zh_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-zh-smoke.mq.md", "B^T*A^T\n探测-ok"); +} + #[test] fn ext_quantum_bell_smoke() { let status = Command::new("cargo")