#![cfg(feature = "numerical")]
use crate::core::{CacheManager, CalcError, EvalContext, EvalResult, evaluate};
use nalgebra::{DMatrix, DVector};
use serde_json::{Value, json};
pub(crate) fn derivative(f: &str, var: &str, x: f64) -> Result<f64, CalcError> {
let eval_at = |t: f64| -> Result<f64, CalcError> {
let mut ctx = EvalContext::new();
ctx.vars.insert(var.to_string(), t);
let cache = CacheManager::new();
let (result, _, _, _) = evaluate(f, &ctx, None, &cache)?;
match result {
EvalResult::Scalar(v) => Ok(v),
_ => Err(CalcError::domain(
"derivative: expression did not evaluate to a scalar".to_string(),
)
.with_i18n("msg.numerical.derivative_not_scalar", vec![])),
}
};
let h = f64::EPSILON.cbrt() * x.abs().max(1.0);
let d1 = (eval_at(x + h)? - eval_at(x - h)?) / (2.0 * h);
let h2 = h * 0.5;
let d2 = (eval_at(x + h2)? - eval_at(x - h2)?) / (2.0 * h2);
let d = (4.0 * d2 - d1) / 3.0;
if !d.is_finite() {
return Err(CalcError::nan_or_inf());
}
Ok(d)
}
pub fn lu(matrix: DMatrix<f64>) -> Result<EvalResult, CalcError> {
let (l, u, p) = crate::math::numerical::lu(&matrix)?;
Ok(EvalResult::Json(json!({
"L": dmatrix_to_json(&l),
"U": dmatrix_to_json(&u),
"P": dmatrix_to_json(&p),
})))
}
pub fn qr(matrix: DMatrix<f64>) -> Result<EvalResult, CalcError> {
let (q, r) = crate::math::numerical::qr(&matrix)?;
Ok(EvalResult::Json(json!({
"Q": dmatrix_to_json(&q),
"R": dmatrix_to_json(&r),
})))
}
pub fn eig(matrix: DMatrix<f64>) -> Result<EvalResult, CalcError> {
let (values, vectors) = crate::math::numerical::eig(&matrix)?;
Ok(EvalResult::Json(json!({
"values": values,
"vectors": dmatrix_to_json(&vectors),
})))
}
pub fn eig_general(matrix: DMatrix<f64>) -> Result<EvalResult, CalcError> {
let result = crate::math::numerical::eig_general(&matrix)?;
Ok(EvalResult::Json(json!({
"values_re": result.values.iter().map(|c| c.re).collect::<Vec<_>>(),
"values_im": result.values.iter().map(|c| c.im).collect::<Vec<_>>(),
"vectors_re": result
.vectors
.iter()
.map(|v| v.iter().map(|c| c.re).collect::<Vec<_>>())
.collect::<Vec<_>>(),
"vectors_im": result
.vectors
.iter()
.map(|v| v.iter().map(|c| c.im).collect::<Vec<_>>())
.collect::<Vec<_>>(),
})))
}
pub fn svd(matrix: DMatrix<f64>) -> Result<EvalResult, CalcError> {
let (u, s, vt) = crate::math::numerical::svd(&matrix)?;
Ok(EvalResult::Json(json!({
"U": dmatrix_to_json(&u),
"S": s,
"Vt": dmatrix_to_json(&vt),
})))
}
pub fn solve(matrix: DMatrix<f64>, b: DVector<f64>) -> Result<EvalResult, CalcError> {
let x = crate::math::numerical::solve(&matrix, &b)?;
Ok(EvalResult::Vector(x.iter().copied().collect()))
}
fn dmatrix_to_json(m: &DMatrix<f64>) -> Value {
let rows: Vec<Vec<f64>> = (0..m.nrows())
.map(|i| (0..m.ncols()).map(|j| m[(i, j)]).collect())
.collect();
json!(rows)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::ErrorKind;
use nalgebra::{LU, QR, SVD, SymmetricEigen};
fn matrix_from_json(v: &Value) -> DMatrix<f64> {
let rows = v.as_array().expect("expected JSON array");
let ncols = rows[0].as_array().expect("row not array").len();
let data: Vec<f64> = rows
.iter()
.flat_map(|row| {
row.as_array()
.expect("row not array")
.iter()
.map(|x| x.as_f64().expect("element not f64"))
})
.collect();
DMatrix::from_row_slice(rows.len(), ncols, &data)
}
fn assert_matrices_approx(a: &DMatrix<f64>, b: &DMatrix<f64>, tol: f64) {
assert_eq!(a.shape(), b.shape(), "shape mismatch");
for i in 0..a.nrows() {
for j in 0..a.ncols() {
assert!(
(a[(i, j)] - b[(i, j)]).abs() < tol,
"mismatch at ({},{}): {} vs {}",
i,
j,
a[(i, j)],
b[(i, j)]
);
}
}
}
#[test]
fn nalgebra_decompose_symbols_available() {
let m: DMatrix<f64> = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let _lu = LU::new(m.clone());
let _qr = QR::new(m.clone());
let _svd = SVD::new(m.clone(), true, true);
let sym: DMatrix<f64> = DMatrix::from_row_slice(2, 2, &[2.0, 1.0, 1.0, 2.0]);
let _eig = SymmetricEigen::new(sym);
}
#[test]
fn lu_2x2_reconstructs_pa_equals_lu() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let result = lu(m.clone()).unwrap();
let json = match result {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let l = matrix_from_json(&json["L"]);
let u = matrix_from_json(&json["U"]);
let p = matrix_from_json(&json["P"]);
let mut pa_native = m.clone();
LU::new(m.clone()).p().permute_rows(&mut pa_native);
assert_matrices_approx(&pa_native, &(&l * &u), 1e-9);
assert_matrices_approx(&(&p * &m), &(&l * &u), 1e-9);
}
#[test]
fn lu_3x3_reconstructs() {
let m = DMatrix::from_row_slice(3, 3, &[2.0, 1.0, 1.0, 1.0, 3.0, 2.0, 1.0, 0.0, 0.0]);
let result = lu(m.clone()).unwrap();
let json = match result {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let l = matrix_from_json(&json["L"]);
let u = matrix_from_json(&json["U"]);
let p = matrix_from_json(&json["P"]);
assert!((l[(0, 0)] - 1.0).abs() < 1e-9);
assert!((l[(1, 1)] - 1.0).abs() < 1e-9);
assert!((l[(2, 2)] - 1.0).abs() < 1e-9);
assert!(u[(1, 0)].abs() < 1e-9);
assert!(u[(2, 0)].abs() < 1e-9);
assert!(u[(2, 1)].abs() < 1e-9);
assert_matrices_approx(&(&p * &m), &(&l * &u), 1e-9);
}
#[test]
fn lu_returns_json_with_l_u_p_keys() {
let m = DMatrix::from_row_slice(2, 2, &[4.0, 3.0, 6.0, 3.0]);
let json = match lu(m).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let obj = json.as_object().expect("expected JSON object");
assert!(obj.contains_key("L"));
assert!(obj.contains_key("U"));
assert!(obj.contains_key("P"));
assert_eq!(obj.len(), 3);
}
#[test]
fn lu_non_square_errors() {
let m = DMatrix::from_row_slice(2, 3, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let result = lu(m);
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn qr_2x2_reconstructs_and_q_orthogonal() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let json = match qr(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let q = matrix_from_json(&json["Q"]);
let r = matrix_from_json(&json["R"]);
assert_matrices_approx(&(&q * &r), &m, 1e-9);
let k = q.ncols();
let qtq = q.transpose() * &q;
assert_matrices_approx(&qtq, &DMatrix::<f64>::identity(k, k), 1e-9);
assert!(r[(1, 0)].abs() < 1e-9);
}
#[test]
fn qr_3x3_reconstructs() {
let m = DMatrix::from_row_slice(
3,
3,
&[12.0, -51.0, 4.0, 6.0, 167.0, -68.0, -4.0, 24.0, -41.0],
);
let json = match qr(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let q = matrix_from_json(&json["Q"]);
let r = matrix_from_json(&json["R"]);
assert_matrices_approx(&(&q * &r), &m, 1e-7);
assert!(r[(1, 0)].abs() < 1e-7);
assert!(r[(2, 0)].abs() < 1e-7);
assert!(r[(2, 1)].abs() < 1e-7);
}
#[test]
fn qr_non_square_2x3_reconstructs() {
let m = DMatrix::from_row_slice(2, 3, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let json = match qr(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let q = matrix_from_json(&json["Q"]);
let r = matrix_from_json(&json["R"]);
assert_eq!(q.shape(), (2, 2));
assert_eq!(r.shape(), (2, 3));
assert_matrices_approx(&(&q * &r), &m, 1e-9);
}
#[test]
fn qr_returns_json_with_q_r_keys() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 1.0]);
let json = match qr(m).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let obj = json.as_object().expect("expected JSON object");
assert!(obj.contains_key("Q"));
assert!(obj.contains_key("R"));
assert_eq!(obj.len(), 2);
}
#[test]
fn eig_symmetric_2x2_eigenrelation_and_sorted() {
let m = DMatrix::from_row_slice(2, 2, &[2.0, 1.0, 1.0, 2.0]);
let json = match eig(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let values: Vec<f64> = json["values"]
.as_array()
.expect("values not array")
.iter()
.map(|x| x.as_f64().expect("value not f64"))
.collect();
let vectors = matrix_from_json(&json["vectors"]);
assert!((values[0] - 1.0).abs() < 1e-9);
assert!((values[1] - 3.0).abs() < 1e-9);
for (i, &val) in values.iter().enumerate() {
let v: nalgebra::DVector<f64> = vectors.column(i).into_owned();
let mv = &m * &v;
let lv = val * &v;
assert!(
(mv - lv).norm() < 1e-9,
"eigenrelation failed for col {}",
i
);
}
}
#[test]
fn eig_symmetric_3x3_eigenrelation() {
let m = DMatrix::from_row_slice(3, 3, &[4.0, 1.0, 2.0, 1.0, 5.0, 3.0, 2.0, 3.0, 6.0]);
let json = match eig(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let values: Vec<f64> = json["values"]
.as_array()
.expect("values not array")
.iter()
.map(|x| x.as_f64().expect("value not f64"))
.collect();
let vectors = matrix_from_json(&json["vectors"]);
assert!(values[0] <= values[1] + 1e-9);
assert!(values[1] <= values[2] + 1e-9);
for (i, &val) in values.iter().enumerate() {
let v: nalgebra::DVector<f64> = vectors.column(i).into_owned();
let mv = &m * &v;
let lv = val * &v;
assert!(
(mv - lv).norm() < 1e-8,
"eigenrelation failed for col {}",
i
);
}
}
#[test]
fn eig_non_symmetric_errors() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let result = eig(m);
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn eig_non_square_errors() {
let m = DMatrix::from_row_slice(2, 3, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let result = eig(m);
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn svd_2x2_reconstructs_and_sorted() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let json = match svd(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let u = matrix_from_json(&json["U"]);
let s: Vec<f64> = json["S"]
.as_array()
.expect("S not array")
.iter()
.map(|x| x.as_f64().expect("sv not f64"))
.collect();
let vt = matrix_from_json(&json["Vt"]);
assert!(s[0] >= s[1], "singular values not descending: {:?}", s);
let k = s.len();
let mut diag = DMatrix::<f64>::zeros(k, k);
for i in 0..k {
diag[(i, i)] = s[i];
}
let recon = &u * &diag * &vt;
assert_matrices_approx(&recon, &m, 1e-9);
let utu = u.transpose() * &u;
assert_matrices_approx(&utu, &DMatrix::<f64>::identity(k, k), 1e-9);
let vtvt = &vt * vt.transpose();
assert_matrices_approx(&vtvt, &DMatrix::<f64>::identity(k, k), 1e-9);
}
#[test]
fn svd_3x2_thin_decomposition() {
let m = DMatrix::from_row_slice(3, 2, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let json = match svd(m.clone()).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let u = matrix_from_json(&json["U"]);
let s: Vec<f64> = json["S"]
.as_array()
.expect("S not array")
.iter()
.map(|x| x.as_f64().expect("sv not f64"))
.collect();
let vt = matrix_from_json(&json["Vt"]);
assert_eq!(u.shape(), (3, 2));
assert_eq!(s.len(), 2);
assert_eq!(vt.shape(), (2, 2));
assert!(s[0] >= s[1]);
let mut diag = DMatrix::<f64>::zeros(2, 2);
for i in 0..2 {
diag[(i, i)] = s[i];
}
let recon = &u * &diag * &vt;
assert_matrices_approx(&recon, &m, 1e-9);
}
#[test]
fn svd_returns_json_with_u_s_vt_keys() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 1.0]);
let json = match svd(m).unwrap() {
EvalResult::Json(v) => v,
other => panic!("expected Json, got {:?}", other),
};
let obj = json.as_object().expect("expected JSON object");
assert!(obj.contains_key("U"));
assert!(obj.contains_key("S"));
assert!(obj.contains_key("Vt"));
assert_eq!(obj.len(), 3);
}
#[test]
fn solve_2x2_reconstructs() {
let a = DMatrix::from_row_slice(2, 2, &[2.0, 1.0, 1.0, 3.0]);
let b = DVector::from_row_slice(&[1.0, 2.0]);
let result = solve(a.clone(), b.clone()).unwrap();
let x = match result {
EvalResult::Vector(v) => v,
other => panic!("expected Vector, got {:?}", other),
};
let xv = DVector::from_row_slice(&x);
let diff = &a * &xv - &b;
assert!(diff.norm() < 1e-9, "A·x != b: {:?}", x);
}
#[test]
fn solve_3x3_reconstructs() {
let a = DMatrix::from_row_slice(3, 3, &[3.0, 2.0, -1.0, 2.0, -2.0, 0.5, -1.0, 0.5, -1.0]);
let b = DVector::from_row_slice(&[1.0, -2.0, 0.0]);
let result = solve(a.clone(), b.clone()).unwrap();
let x = match result {
EvalResult::Vector(v) => v,
other => panic!("expected Vector, got {:?}", other),
};
let xv = DVector::from_row_slice(&x);
let diff = &a * &xv - &b;
assert!(diff.norm() < 1e-9, "A·x != b: {:?}", x);
}
#[test]
fn solve_singular_errors() {
let a = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 2.0, 4.0]);
let b = DVector::from_row_slice(&[1.0, 2.0]);
let result = solve(a, b);
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn solve_dim_mismatch_errors() {
let a = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let b = DVector::from_row_slice(&[1.0, 2.0, 3.0]); let result = solve(a, b);
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn solve_non_square_a_errors() {
let a = DMatrix::from_row_slice(2, 3, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let b = DVector::from_row_slice(&[1.0, 2.0]);
let result = solve(a, b);
assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
}
#[test]
fn lu_rejects_nan_matrix() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, f64::NAN, 2.0, 4.0]);
assert!(matches!(lu(m), Err(e) if e.kind == ErrorKind::NaNOrInf));
}
#[test]
fn eig_rejects_inf_matrix() {
let m = DMatrix::from_row_slice(2, 2, &[1.0, f64::INFINITY, f64::INFINITY, 4.0]);
assert!(matches!(eig(m), Err(e) if e.kind == ErrorKind::NaNOrInf));
}
#[test]
fn solve_rejects_nan_b() {
let a = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
let b = DVector::from_row_slice(&[1.0, f64::NAN]);
assert!(matches!(solve(a, b), Err(e) if e.kind == ErrorKind::NaNOrInf));
}
#[test]
fn derivative_sin_at_zero() {
let d = derivative("sin(x)", "x", 0.0).unwrap();
assert!((d - 1.0).abs() < 1e-6, "d={d}");
}
#[test]
fn derivative_quadratic_at_three() {
let d = derivative("x^2", "x", 3.0).unwrap();
assert!((d - 6.0).abs() < 1e-6, "d={d}");
}
}