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
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user