ruvector-math 2.0.6

Advanced mathematics for next-gen vector search: Optimal Transport, Information Geometry, Product Manifolds
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
//! Spherical Geometry
//!
//! Operations on the n-sphere S^n = {x ∈ R^{n+1} : ||x|| = 1}
//!
//! ## Use Cases in Vector Search
//!
//! - **Cyclical patterns**: Time-of-day, day-of-week, seasonal data
//! - **Directional data**: Wind directions, compass bearings
//! - **Normalized embeddings**: Common in NLP (unit-normalized word vectors)
//! - **Angular similarity**: Natural for cosine similarity
//!
//! ## Key Operations
//!
//! - Geodesic distance: d(x, y) = arccos(⟨x, y⟩)
//! - Exponential map: Move from x in direction v
//! - Logarithmic map: Find direction from x to y
//! - Fréchet mean: Spherical centroid

use crate::error::{MathError, Result};
use crate::utils::{dot, norm, normalize, EPS};

/// Configuration for spherical operations
#[derive(Debug, Clone)]
pub struct SphericalConfig {
    /// Maximum iterations for iterative algorithms
    pub max_iterations: usize,
    /// Convergence threshold
    pub threshold: f64,
}

impl Default for SphericalConfig {
    fn default() -> Self {
        Self {
            max_iterations: 100,
            threshold: 1e-8,
        }
    }
}

/// Spherical space operations
#[derive(Debug, Clone)]
pub struct SphericalSpace {
    /// Dimension of the sphere (ambient dimension - 1)
    dim: usize,
    /// Configuration
    config: SphericalConfig,
}

impl SphericalSpace {
    /// Create a new spherical space S^{n-1} embedded in R^n
    ///
    /// # Arguments
    /// * `ambient_dim` - Dimension of ambient Euclidean space
    pub fn new(ambient_dim: usize) -> Self {
        Self {
            dim: ambient_dim.max(1),
            config: SphericalConfig::default(),
        }
    }

    /// Set configuration
    pub fn with_config(mut self, config: SphericalConfig) -> Self {
        self.config = config;
        self
    }

    /// Get ambient dimension
    pub fn ambient_dim(&self) -> usize {
        self.dim
    }

    /// Get intrinsic dimension (ambient_dim - 1)
    pub fn intrinsic_dim(&self) -> usize {
        self.dim.saturating_sub(1)
    }

    /// Project a point onto the sphere
    pub fn project(&self, point: &[f64]) -> Result<Vec<f64>> {
        if point.len() != self.dim {
            return Err(MathError::dimension_mismatch(self.dim, point.len()));
        }

        let n = norm(point);
        if n < EPS {
            // Return north pole for zero vector
            let mut result = vec![0.0; self.dim];
            result[0] = 1.0;
            return Ok(result);
        }

        Ok(normalize(point))
    }

    /// Check if point is on the sphere
    pub fn is_on_sphere(&self, point: &[f64]) -> bool {
        if point.len() != self.dim {
            return false;
        }
        let n = norm(point);
        (n - 1.0).abs() < 1e-6
    }

    /// Geodesic distance on the sphere: d(x, y) = arccos(⟨x, y⟩)
    ///
    /// This is the great-circle distance.
    pub fn distance(&self, x: &[f64], y: &[f64]) -> Result<f64> {
        if x.len() != self.dim || y.len() != self.dim {
            return Err(MathError::dimension_mismatch(self.dim, x.len()));
        }

        let cos_angle = dot(x, y).clamp(-1.0, 1.0);
        Ok(cos_angle.acos())
    }

    /// Squared geodesic distance (useful for optimization)
    pub fn squared_distance(&self, x: &[f64], y: &[f64]) -> Result<f64> {
        let d = self.distance(x, y)?;
        Ok(d * d)
    }

    /// Exponential map: exp_x(v) - move from x in direction v
    ///
    /// exp_x(v) = cos(||v||) x + sin(||v||) (v / ||v||)
    pub fn exp_map(&self, x: &[f64], v: &[f64]) -> Result<Vec<f64>> {
        if x.len() != self.dim || v.len() != self.dim {
            return Err(MathError::dimension_mismatch(self.dim, x.len()));
        }

        let v_norm = norm(v);

        if v_norm < EPS {
            return Ok(x.to_vec());
        }

        let cos_t = v_norm.cos();
        let sin_t = v_norm.sin();

        let result: Vec<f64> = x
            .iter()
            .zip(v.iter())
            .map(|(&xi, &vi)| cos_t * xi + sin_t * vi / v_norm)
            .collect();

        // Ensure on sphere
        Ok(normalize(&result))
    }

    /// Logarithmic map: log_x(y) - tangent vector at x pointing toward y
    ///
    /// log_x(y) = (θ / sin(θ)) (y - cos(θ) x)
    /// where θ = d(x, y) = arccos(⟨x, y⟩)
    pub fn log_map(&self, x: &[f64], y: &[f64]) -> Result<Vec<f64>> {
        if x.len() != self.dim || y.len() != self.dim {
            return Err(MathError::dimension_mismatch(self.dim, x.len()));
        }

        let cos_theta = dot(x, y).clamp(-1.0, 1.0);
        let theta = cos_theta.acos();

        if theta < EPS {
            // Points are the same
            return Ok(vec![0.0; self.dim]);
        }

        if (theta - std::f64::consts::PI).abs() < EPS {
            // Points are antipodal - log map is not well-defined
            return Err(MathError::numerical_instability(
                "Antipodal points have undefined log map",
            ));
        }

        let scale = theta / theta.sin();

        let result: Vec<f64> = x
            .iter()
            .zip(y.iter())
            .map(|(&xi, &yi)| scale * (yi - cos_theta * xi))
            .collect();

        Ok(result)
    }

    /// Parallel transport vector v from x to y
    ///
    /// Transports tangent vector at x along geodesic to y
    pub fn parallel_transport(&self, x: &[f64], y: &[f64], v: &[f64]) -> Result<Vec<f64>> {
        if x.len() != self.dim || y.len() != self.dim || v.len() != self.dim {
            return Err(MathError::dimension_mismatch(self.dim, x.len()));
        }

        let cos_theta = dot(x, y).clamp(-1.0, 1.0);

        if (cos_theta - 1.0).abs() < EPS {
            // Same point, no transport needed
            return Ok(v.to_vec());
        }

        let theta = cos_theta.acos();

        // Direction from x to y (unit tangent)
        let u: Vec<f64> = x
            .iter()
            .zip(y.iter())
            .map(|(&xi, &yi)| yi - cos_theta * xi)
            .collect();
        let u = normalize(&u);

        // Component of v along u
        let v_u = dot(v, &u);

        // Transport formula
        let result: Vec<f64> = (0..self.dim)
            .map(|i| {
                let v_perp = v[i] - v_u * u[i] - dot(v, x) * x[i];
                v_perp + v_u * (-theta.sin() * x[i] + theta.cos() * u[i])
                    - dot(v, x) * (theta.cos() * x[i] + theta.sin() * u[i])
            })
            .collect();

        Ok(result)
    }

    /// Fréchet mean on the sphere (spherical centroid)
    ///
    /// Minimizes: Σᵢ wᵢ d(m, xᵢ)²
    pub fn frechet_mean(&self, points: &[Vec<f64>], weights: Option<&[f64]>) -> Result<Vec<f64>> {
        if points.is_empty() {
            return Err(MathError::empty_input("points"));
        }

        let n = points.len();
        let uniform_weight = 1.0 / n as f64;
        let weights: Vec<f64> = match weights {
            Some(w) => {
                let sum: f64 = w.iter().sum();
                w.iter().map(|&wi| wi / sum).collect()
            }
            None => vec![uniform_weight; n],
        };

        // Initialize with weighted Euclidean mean, then project
        let mut mean: Vec<f64> = vec![0.0; self.dim];
        for (p, &w) in points.iter().zip(weights.iter()) {
            for (mi, &pi) in mean.iter_mut().zip(p.iter()) {
                *mi += w * pi;
            }
        }
        mean = self.project(&mean)?;

        // Iterative refinement (Riemannian gradient descent)
        for _ in 0..self.config.max_iterations {
            // Compute Riemannian gradient: Σ wᵢ log_{mean}(xᵢ)
            let mut gradient = vec![0.0; self.dim];

            for (p, &w) in points.iter().zip(weights.iter()) {
                if let Ok(log_v) = self.log_map(&mean, p) {
                    for (gi, &li) in gradient.iter_mut().zip(log_v.iter()) {
                        *gi += w * li;
                    }
                }
            }

            let grad_norm = norm(&gradient);
            if grad_norm < self.config.threshold {
                break;
            }

            // Step along geodesic
            mean = self.exp_map(&mean, &gradient)?;
        }

        Ok(mean)
    }

    /// Geodesic interpolation: point at fraction t along geodesic from x to y
    ///
    /// γ(t) = sin((1-t)θ)/sin(θ) x + sin(tθ)/sin(θ) y
    pub fn geodesic(&self, x: &[f64], y: &[f64], t: f64) -> Result<Vec<f64>> {
        if x.len() != self.dim || y.len() != self.dim {
            return Err(MathError::dimension_mismatch(self.dim, x.len()));
        }

        let t = t.clamp(0.0, 1.0);

        let cos_theta = dot(x, y).clamp(-1.0, 1.0);
        let theta = cos_theta.acos();

        if theta < EPS {
            return Ok(x.to_vec());
        }

        let sin_theta = theta.sin();
        let a = ((1.0 - t) * theta).sin() / sin_theta;
        let b = (t * theta).sin() / sin_theta;

        let result: Vec<f64> = x
            .iter()
            .zip(y.iter())
            .map(|(&xi, &yi)| a * xi + b * yi)
            .collect();

        // Ensure on sphere
        Ok(normalize(&result))
    }

    /// Sample uniformly from the sphere
    pub fn sample_uniform(&self, rng: &mut impl rand::Rng) -> Vec<f64> {
        use rand_distr::{Distribution, StandardNormal};

        let point: Vec<f64> = (0..self.dim).map(|_| StandardNormal.sample(rng)).collect();

        normalize(&point)
    }

    /// Von Mises-Fisher mean direction MLE
    ///
    /// Computes the mean direction (mode of vMF distribution)
    pub fn mean_direction(&self, points: &[Vec<f64>]) -> Result<Vec<f64>> {
        if points.is_empty() {
            return Err(MathError::empty_input("points"));
        }

        let mut sum = vec![0.0; self.dim];
        for p in points {
            if p.len() != self.dim {
                return Err(MathError::dimension_mismatch(self.dim, p.len()));
            }
            for (si, &pi) in sum.iter_mut().zip(p.iter()) {
                *si += pi;
            }
        }

        Ok(normalize(&sum))
    }
}

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

    #[test]
    fn test_project_onto_sphere() {
        let sphere = SphericalSpace::new(3);

        let point = vec![3.0, 4.0, 0.0];
        let projected = sphere.project(&point).unwrap();

        let norm: f64 = projected.iter().map(|&x| x * x).sum::<f64>().sqrt();
        assert!((norm - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_geodesic_distance() {
        let sphere = SphericalSpace::new(3);

        // Orthogonal unit vectors
        let x = vec![1.0, 0.0, 0.0];
        let y = vec![0.0, 1.0, 0.0];

        let dist = sphere.distance(&x, &y).unwrap();
        let expected = std::f64::consts::PI / 2.0;

        assert!((dist - expected).abs() < 1e-10);
    }

    #[test]
    fn test_exp_log_inverse() {
        let sphere = SphericalSpace::new(3);

        let x = vec![1.0, 0.0, 0.0];
        let y = sphere.project(&vec![1.0, 1.0, 0.0]).unwrap();

        // log then exp should return to y
        let v = sphere.log_map(&x, &y).unwrap();
        let y_recovered = sphere.exp_map(&x, &v).unwrap();

        for (yi, &yr) in y.iter().zip(y_recovered.iter()) {
            assert!((yi - yr).abs() < 1e-6, "Exp-log inverse failed");
        }
    }

    #[test]
    fn test_geodesic_interpolation() {
        let sphere = SphericalSpace::new(3);

        let x = vec![1.0, 0.0, 0.0];
        let y = vec![0.0, 1.0, 0.0];

        // Midpoint
        let mid = sphere.geodesic(&x, &y, 0.5).unwrap();

        // Should be on sphere
        let norm: f64 = mid.iter().map(|&m| m * m).sum::<f64>().sqrt();
        assert!((norm - 1.0).abs() < 1e-10);

        // Should be equidistant
        let d_x = sphere.distance(&x, &mid).unwrap();
        let d_y = sphere.distance(&mid, &y).unwrap();
        assert!((d_x - d_y).abs() < 1e-10);
    }

    #[test]
    fn test_frechet_mean() {
        let sphere = SphericalSpace::new(3);

        // Points near north pole
        let points = vec![
            vec![0.9, 0.1, 0.0],
            vec![0.9, -0.1, 0.0],
            vec![0.9, 0.0, 0.1],
            vec![0.9, 0.0, -0.1],
        ];

        let points: Vec<Vec<f64>> = points
            .into_iter()
            .map(|p| sphere.project(&p).unwrap())
            .collect();

        let mean = sphere.frechet_mean(&points, None).unwrap();

        // Mean should be close to (1, 0, 0)
        assert!(mean[0] > 0.95);
    }
}