calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! Numerical 线性代数分解(feature-gated)。
//! 委托层:调用 `math::numerical::*`,包装为 `EvalResult`;路由入口是 MatrixDomain。

#![cfg(feature = "numerical")]

use crate::core::{CacheManager, CalcError, EvalContext, EvalResult, evaluate};
use nalgebra::{DMatrix, DVector};
use serde_json::{Value, json};

/// 数值微分 derivative(f, var, x):中心差分 + Richardson 外推(误差 ~1e-10)。
/// 位于域层以复用表达式求值链(math 层不依赖 evaluator)。
/// 经 `ScalarMathImpl::derivative` 公开暴露(api 层委托本函数)。
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)
}

/// LU 分解 → `{"L":[[..]], "U":[[..]], "P":[[..]]}`,满足 P·A = L·U。
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),
    })))
}

/// QR 分解 → `{"Q":[[..]], "R":[[..]]}`,满足 A = Q·R。
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),
    })))
}

/// 实对称矩阵特征分解 → `{"values":[..], "vectors":[[..]]}`(特征值升序)。
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),
    })))
}

/// 实矩阵特征值(含复数)与特征向量 → `{"values_re","values_im","vectors_re","vectors_im"}`。
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<_>>(),
    })))
}

/// 奇异值分解 → `{"U":[[..]], "S":[..], "Vt":[[..]]}`(S 降序)。
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),
    })))
}

/// 解线性方程组 A·x = b → `Vector([..])`。
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()))
}

/// DMatrix → JSON 二维数组(行优先)。
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};

    /// 测试辅助:JSON 二维数组 → DMatrix。
    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)]
                );
            }
        }
    }

    /// 确认 nalgebra 0.35 下 LU/QR/SVD/SymmetricEigen 可用,无需额外 feature。
    #[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());
        // SVD::new 三参数:(matrix, compute_u, compute_v)
        let _svd = SVD::new(m.clone(), true, true);
        // SymmetricEigen 要求实对称矩阵
        let sym: DMatrix<f64> = DMatrix::from_row_slice(2, 2, &[2.0, 1.0, 1.0, 2.0]);
        let _eig = SymmetricEigen::new(sym);
    }

    /// lu(2x2) 返回 {L,U,P},P·A = L·U(双重验证:permute_rows + 返回的 P 矩阵)。
    #[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"]);

        // 验证 1:nalgebra 原生 permute_rows(A) == L*U
        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);

        // 验证 2:返回的 P 矩阵满足 P*A == L*U
        assert_matrices_approx(&(&p * &m), &(&l * &u), 1e-9);
    }

    /// lu(3x3) 同理(含行置换的非平凡情形)。
    #[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"]);
        // L 单位下三角:对角线全 1
        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);
        // U 上三角:下三角为 0
        assert!(u[(1, 0)].abs() < 1e-9);
        assert!(u[(2, 0)].abs() < 1e-9);
        assert!(u[(2, 1)].abs() < 1e-9);
        // P*A == L*U
        assert_matrices_approx(&(&p * &m), &(&l * &u), 1e-9);
    }

    /// lu 返回 JSON 含 L/U/P 三 key。
    #[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);
    }

    /// lu(非方阵) → DomainError。
    #[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));
    }

    /// qr(2x2) 返回 {Q,R},Q·R = A + Q^T·Q = I(正交)+ R 上三角。
    #[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"]);
        // A = Q·R
        assert_matrices_approx(&(&q * &r), &m, 1e-9);
        // Q^T·Q = I(列正交)
        let k = q.ncols();
        let qtq = q.transpose() * &q;
        assert_matrices_approx(&qtq, &DMatrix::<f64>::identity(k, k), 1e-9);
        // R 上三角(下三角为 0)
        assert!(r[(1, 0)].abs() < 1e-9);
    }

    /// qr(3x3) 经典维基例子(Householder)。
    #[test]
    fn qr_3x3_reconstructs() {
        // Wikipedia QR 经典例子
        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"]);
        // A = Q·R
        assert_matrices_approx(&(&q * &r), &m, 1e-7);
        // R 上三角:严格下三角为 0
        assert!(r[(1, 0)].abs() < 1e-7);
        assert!(r[(2, 0)].abs() < 1e-7);
        assert!(r[(2, 1)].abs() < 1e-7);
    }

    /// qr(非方阵 2x3) 瘦分解也成立(nalgebra 无 m≥n 要求)。
    #[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"]);
        // 瘦 QR:Q 是 2x2,R 是 2x3
        assert_eq!(q.shape(), (2, 2));
        assert_eq!(r.shape(), (2, 3));
        // A = Q·R
        assert_matrices_approx(&(&q * &r), &m, 1e-9);
    }

    /// qr 返回 JSON 含 Q/R 两 key。
    #[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);
    }

    /// eig([[2,1],[1,2]]) → 特征值 {1,3} 升序 + M·v=λ·v 还原。
    #[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"]);
        // 升序:[1, 3]
        assert!((values[0] - 1.0).abs() < 1e-9);
        assert!((values[1] - 3.0).abs() < 1e-9);
        // M·v_i = λ_i·v_i
        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
            );
        }
    }

    /// eig(3x3 对称) 特征值升序 + M·v=λ·v。
    #[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);
        // M·v_i = λ_i·v_i
        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
            );
        }
    }

    /// eig(非对称) → DomainError(显式校验,避免 SymmetricEigen panic)。
    #[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));
    }

    /// eig(非方阵) → DomainError。
    #[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));
    }

    /// svd(2x2) 还原 A = U·diag(S)·Vt + S 降序 + U/Vt 正交。
    #[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"]);
        // S 降序
        assert!(s[0] >= s[1], "singular values not descending: {:?}", s);
        // A = U·diag(S)·Vt
        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);
        // U 列正交:U^T·U = I
        let utu = u.transpose() * &u;
        assert_matrices_approx(&utu, &DMatrix::<f64>::identity(k, k), 1e-9);
        // Vt 行正交:Vt·Vt^T = I
        let vtvt = &vt * vt.transpose();
        assert_matrices_approx(&vtvt, &DMatrix::<f64>::identity(k, k), 1e-9);
    }

    /// svd(3x2) 瘦分解(m>n)形状 + 还原。
    #[test]
    fn svd_3x2_thin_decomposition() {
        // m=3, n=2 → k=2; U 3×2, S len 2, Vt 2×2
        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]);
        // A = U·diag(S)·Vt
        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);
    }

    /// svd 返回 JSON 含 U/S/Vt 三 key。
    #[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);
    }

    /// solve(2x2, b) 还原 A·x = b。
    #[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),
        };
        // A·x = b
        let xv = DVector::from_row_slice(&x);
        let diff = &a * &xv - &b;
        assert!(diff.norm() < 1e-9, "A·x != b: {:?}", x);
    }

    /// solve(3x3, b) 还原 A·x = b。
    #[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);
    }

    /// solve(奇异矩阵) → DomainError。
    #[test]
    fn solve_singular_errors() {
        // [[1,2],[2,4]] 行成比例 → 秩 1 < 2,奇异
        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));
    }

    /// solve(维度不匹配) → DomainError。
    #[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]); // len 3 != 2
        let result = solve(a, b);
        assert!(matches!(result, Err(e) if e.kind == ErrorKind::Domain));
    }

    /// solve(非方阵 A) → DomainError。
    #[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));
    }

    /// lu 拒绝 NaN 矩阵(NaN 会绕过对称/奇异校验触发 panic)。
    #[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));
    }

    /// eig 拒绝 Inf 矩阵(Inf 污染 SymmetricEigen 迭代)。
    #[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));
    }

    /// solve 拒绝 NaN 右端向量 b。
    #[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));
    }

    /// derivative 中心差分 + Richardson 外推:sin'(0)=1、x^2'(3)=6。
    #[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}");
    }
}