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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! 向量核心函数:点积/叉积/模/归一化/加减/距离/投影/反射等。

use crate::core::CalcError;

/// 点积。要求等长。
pub fn dot(a: &[f64], b: &[f64]) -> Result<f64, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "dot(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.dot_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    Ok(a.iter().zip(b.iter()).map(|(x, y)| x * y).sum())
}

/// 三维叉积。仅支持 3 维向量。
pub fn cross(a: &[f64], b: &[f64]) -> Result<Vec<f64>, CalcError> {
    if a.len() != 3 || b.len() != 3 {
        return Err(
            CalcError::domain("cross() requires 3-dimensional vectors".to_string())
                .with_i18n("msg.vector.cross_3d_only", vec![]),
        );
    }
    Ok(vec![
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ])
}

/// 向量模长(L2 范数)。
pub fn magnitude(v: &[f64]) -> f64 {
    v.iter().map(|x| x * x).sum::<f64>().sqrt()
}

/// 归一化为单位向量。零向量返回错误。
pub fn normalize(v: &[f64]) -> Result<Vec<f64>, CalcError> {
    let norm = magnitude(v);
    if norm < 1e-15 {
        return Err(
            CalcError::domain("cannot normalize zero vector".to_string())
                .with_i18n("msg.vector.normalize_zero_vector", vec![]),
        );
    }
    Ok(v.iter().map(|x| x / norm).collect())
}

/// 逐元素加法。要求等长。
pub fn vector_add(a: &[f64], b: &[f64]) -> Result<Vec<f64>, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "vector_add: dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    Ok(a.iter().zip(b.iter()).map(|(x, y)| x + y).collect())
}

/// 逐元素减法。要求等长。
pub fn vector_sub(a: &[f64], b: &[f64]) -> Result<Vec<f64>, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "vector_sub: dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    Ok(a.iter().zip(b.iter()).map(|(x, y)| x - y).collect())
}

/// 标量乘法。
pub fn scalar_mul_vec(v: &[f64], s: f64) -> Vec<f64> {
    v.iter().map(|x| x * s).collect()
}

/// 两向量夹角(弧度)。零向量返回错误。
pub fn angle(a: &[f64], b: &[f64]) -> Result<f64, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "angle(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.angle_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    let norm_a = magnitude(a);
    let norm_b = magnitude(b);
    if norm_a < 1e-15 || norm_b < 1e-15 {
        return Err(
            CalcError::domain("angle(): zero vector has no angle".to_string())
                .with_i18n("msg.vector.angle_zero_vector", vec![]),
        );
    }
    let cos_theta = dot(a, b)? / (norm_a * norm_b);
    Ok(cos_theta.clamp(-1.0, 1.0).acos())
}

/// 三维混合积 a·(b×c)。仅支持 3 维。
pub fn scalar_triple(a: &[f64], b: &[f64], c: &[f64]) -> Result<f64, CalcError> {
    if a.len() != 3 || b.len() != 3 || c.len() != 3 {
        return Err(CalcError::domain(
            "scalar_triple() requires 3-dimensional vectors".to_string(),
        )
        .with_i18n("msg.vector.scalar_triple_3d_only", vec![]));
    }
    let cr = cross(b, c)?;
    dot(a, &cr)
}

/// 余弦相似度 = dot(a,b) / (norm(a) * norm(b))。零向量返回错误。
pub fn cosine_similarity(a: &[f64], b: &[f64]) -> Result<f64, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "cosine_similarity(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.cosine_similarity_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    let norm_a = magnitude(a);
    let norm_b = magnitude(b);
    if norm_a < 1e-15 || norm_b < 1e-15 {
        return Err(
            CalcError::domain("cosine_similarity(): zero vector".to_string())
                .with_i18n("msg.vector.cosine_similarity_zero_vector", vec![]),
        );
    }
    let cos = dot(a, b)? / (norm_a * norm_b);
    Ok(cos.clamp(-1.0, 1.0))
}

/// 投影 = (dot(a,b) / dot(b,b)) * b。零向量 b 返回错误。
pub fn project(a: &[f64], b: &[f64]) -> Result<Vec<f64>, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "project(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.project_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    let b_dot_b = dot(b, b)?;
    if b_dot_b == 0.0 {
        return Err(
            CalcError::domain("project(): cannot project onto zero vector".to_string())
                .with_i18n("msg.vector.project_zero_vector", vec![]),
        );
    }
    let scalar = dot(a, b)? / b_dot_b;
    Ok(scalar_mul_vec(b, scalar))
}

/// 反射 = v - 2 * (dot(v,n) / dot(n,n)) * n。零法向量返回错误。
pub fn reflect(v: &[f64], n: &[f64]) -> Result<Vec<f64>, CalcError> {
    if v.len() != n.len() {
        return Err(CalcError::domain(format!(
            "reflect(): dimension mismatch {} vs {}",
            v.len(),
            n.len()
        ))
        .with_i18n(
            "msg.vector.reflect_dim_mismatch",
            vec![
                ("a".to_string(), v.len().to_string()),
                ("b".to_string(), n.len().to_string()),
            ],
        ));
    }
    let n_dot_n = dot(n, n)?;
    if n_dot_n == 0.0 {
        return Err(
            CalcError::domain("reflect(): zero normal vector".to_string())
                .with_i18n("msg.vector.reflect_zero_vector", vec![]),
        );
    }
    let scalar = 2.0 * dot(v, n)? / n_dot_n;
    let scaled_n = scalar_mul_vec(n, scalar);
    vector_sub(v, &scaled_n)
}

/// 欧几里得距离。
pub fn euclidean(a: &[f64], b: &[f64]) -> Result<f64, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "euclidean(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.euclidean_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    Ok(a.iter()
        .zip(b.iter())
        .map(|(x, y)| (x - y).powi(2))
        .sum::<f64>()
        .sqrt())
}

/// 曼哈顿距离。
pub fn manhattan(a: &[f64], b: &[f64]) -> Result<f64, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "manhattan(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.manhattan_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    Ok(a.iter().zip(b.iter()).map(|(x, y)| (x - y).abs()).sum())
}

/// 外积 a × b^T,返回 `Vec<Vec<f64>>`(行优先矩阵)。
pub fn outer(a: &[f64], b: &[f64]) -> Vec<Vec<f64>> {
    a.iter()
        .map(|ai| b.iter().map(|bi| ai * bi).collect())
        .collect()
}

/// 线性插值(向量版):a + t * (b - a)。
pub fn lerp_vec(a: &[f64], b: &[f64], t: f64) -> Result<Vec<f64>, CalcError> {
    if a.len() != b.len() {
        return Err(CalcError::domain(format!(
            "lerp(): dimension mismatch {} vs {}",
            a.len(),
            b.len()
        ))
        .with_i18n(
            "msg.vector.lerp_dim_mismatch",
            vec![
                ("a".to_string(), a.len().to_string()),
                ("b".to_string(), b.len().to_string()),
            ],
        ));
    }
    Ok(a.iter()
        .zip(b.iter())
        .map(|(ai, bi)| ai + t * (bi - ai))
        .collect())
}

/// 线性插值(标量版)。
pub fn lerp_scalar(a: f64, b: f64, t: f64) -> f64 {
    a + t * (b - a)
}

// ===== 测试 =====

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_approx(actual: f64, expected: f64, tol: f64, label: &str) {
        assert!(
            (actual - expected).abs() < tol,
            "{}: expected {} but got {} (diff={})",
            label,
            expected,
            actual,
            (actual - expected).abs()
        );
    }

    #[test]
    fn test_dot() {
        assert_approx(
            dot(&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0]).unwrap(),
            32.0,
            1e-10,
            "dot",
        );
    }

    #[test]
    fn test_dot_dim_mismatch() {
        assert!(dot(&[1.0, 2.0], &[1.0, 2.0, 3.0]).is_err());
    }

    #[test]
    fn test_cross() {
        let r = cross(&[1.0, 0.0, 0.0], &[0.0, 1.0, 0.0]).unwrap();
        assert_approx(r[0], 0.0, 1e-10, "cross[0]");
        assert_approx(r[1], 0.0, 1e-10, "cross[1]");
        assert_approx(r[2], 1.0, 1e-10, "cross[2]");
    }

    #[test]
    fn test_cross_not_3d() {
        assert!(cross(&[1.0, 2.0], &[3.0, 4.0]).is_err());
    }

    #[test]
    fn test_magnitude() {
        assert_approx(magnitude(&[3.0, 4.0]), 5.0, 1e-10, "magnitude");
    }

    #[test]
    fn test_normalize() {
        let r = normalize(&[3.0, 4.0]).unwrap();
        assert_approx(r[0], 0.6, 1e-10, "normalize[0]");
        assert_approx(r[1], 0.8, 1e-10, "normalize[1]");
    }

    #[test]
    fn test_normalize_zero() {
        assert!(normalize(&[0.0, 0.0]).is_err());
    }

    #[test]
    fn test_vector_add_sub() {
        let s = vector_add(&[1.0, 2.0], &[3.0, 4.0]).unwrap();
        assert_approx(s[0], 4.0, 1e-10, "add[0]");
        let d = vector_sub(&[5.0, 6.0], &[1.0, 2.0]).unwrap();
        assert_approx(d[0], 4.0, 1e-10, "sub[0]");
    }

    #[test]
    fn test_scalar_mul_vec() {
        let r = scalar_mul_vec(&[1.0, 2.0, 3.0], 2.0);
        assert_approx(r[2], 6.0, 1e-10, "scalar_mul");
    }

    #[test]
    fn test_angle() {
        let a = angle(&[1.0, 0.0], &[0.0, 1.0]).unwrap();
        assert_approx(a, std::f64::consts::FRAC_PI_2, 1e-10, "angle perpendicular");
    }

    #[test]
    fn test_cosine_similarity() {
        let c = cosine_similarity(&[1.0, 0.0], &[1.0, 0.0]).unwrap();
        assert_approx(c, 1.0, 1e-10, "cosine same");
    }

    #[test]
    fn test_project() {
        let p = project(&[3.0, 4.0], &[1.0, 0.0]).unwrap();
        assert_approx(p[0], 3.0, 1e-10, "project[0]");
        assert_approx(p[1], 0.0, 1e-10, "project[1]");
    }

    #[test]
    fn test_reflect() {
        let r = reflect(&[1.0, 1.0], &[0.0, 1.0]).unwrap();
        assert_approx(r[0], 1.0, 1e-10, "reflect[0]");
        assert_approx(r[1], -1.0, 1e-10, "reflect[1]");
    }

    #[test]
    fn test_euclidean() {
        assert_approx(
            euclidean(&[0.0, 0.0], &[3.0, 4.0]).unwrap(),
            5.0,
            1e-10,
            "euclidean",
        );
    }

    #[test]
    fn test_manhattan() {
        assert_approx(
            manhattan(&[0.0, 0.0], &[3.0, 4.0]).unwrap(),
            7.0,
            1e-10,
            "manhattan",
        );
    }

    #[test]
    fn test_outer() {
        let m = outer(&[1.0, 2.0], &[3.0, 4.0]);
        assert_approx(m[0][0], 3.0, 1e-10, "outer[0][0]");
        assert_approx(m[1][1], 8.0, 1e-10, "outer[1][1]");
    }

    #[test]
    fn test_lerp_vec() {
        let r = lerp_vec(&[0.0, 0.0], &[10.0, 20.0], 0.5).unwrap();
        assert_approx(r[0], 5.0, 1e-10, "lerp[0]");
        assert_approx(r[1], 10.0, 1e-10, "lerp[1]");
    }

    #[test]
    fn test_lerp_scalar() {
        assert_approx(lerp_scalar(0.0, 10.0, 0.5), 5.0, 1e-10, "lerp_scalar");
    }
}