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
//! Persistent Homology Computation
//!
//! Compute birth-death pairs from a filtration using the standard algorithm.

use super::{BettiNumbers, Filtration, Simplex};
use std::collections::{HashMap, HashSet};

/// Birth-death pair in persistence diagram
#[derive(Debug, Clone, PartialEq)]
pub struct BirthDeathPair {
    /// Dimension of the feature (0 = component, 1 = loop, ...)
    pub dimension: usize,
    /// Birth time
    pub birth: f64,
    /// Death time (None = essential, lives forever)
    pub death: Option<f64>,
}

impl BirthDeathPair {
    /// Create finite interval
    pub fn finite(dimension: usize, birth: f64, death: f64) -> Self {
        Self {
            dimension,
            birth,
            death: Some(death),
        }
    }

    /// Create essential (infinite) interval
    pub fn essential(dimension: usize, birth: f64) -> Self {
        Self {
            dimension,
            birth,
            death: None,
        }
    }

    /// Persistence (lifetime) of feature
    pub fn persistence(&self) -> f64 {
        match self.death {
            Some(d) => d - self.birth,
            None => f64::INFINITY,
        }
    }

    /// Is this an essential feature (never dies)?
    pub fn is_essential(&self) -> bool {
        self.death.is_none()
    }

    /// Midpoint of interval
    pub fn midpoint(&self) -> f64 {
        match self.death {
            Some(d) => (self.birth + d) / 2.0,
            None => f64::INFINITY,
        }
    }
}

/// Persistence diagram: collection of birth-death pairs
#[derive(Debug, Clone)]
pub struct PersistenceDiagram {
    /// Birth-death pairs
    pub pairs: Vec<BirthDeathPair>,
    /// Maximum dimension
    pub max_dim: usize,
}

impl PersistenceDiagram {
    /// Create empty diagram
    pub fn new() -> Self {
        Self {
            pairs: Vec::new(),
            max_dim: 0,
        }
    }

    /// Add a pair
    pub fn add(&mut self, pair: BirthDeathPair) {
        self.max_dim = self.max_dim.max(pair.dimension);
        self.pairs.push(pair);
    }

    /// Get pairs of dimension d
    pub fn pairs_of_dim(&self, d: usize) -> impl Iterator<Item = &BirthDeathPair> {
        self.pairs.iter().filter(move |p| p.dimension == d)
    }

    /// Get Betti numbers at scale t
    pub fn betti_at(&self, t: f64) -> BettiNumbers {
        let mut b0 = 0;
        let mut b1 = 0;
        let mut b2 = 0;

        for pair in &self.pairs {
            let alive = pair.birth <= t && pair.death.map(|d| d > t).unwrap_or(true);
            if alive {
                match pair.dimension {
                    0 => b0 += 1,
                    1 => b1 += 1,
                    2 => b2 += 1,
                    _ => {}
                }
            }
        }

        BettiNumbers::new(b0, b1, b2)
    }

    /// Get total persistence (sum of lifetimes)
    pub fn total_persistence(&self) -> f64 {
        self.pairs
            .iter()
            .filter(|p| !p.is_essential())
            .map(|p| p.persistence())
            .sum()
    }

    /// Get average persistence
    pub fn average_persistence(&self) -> f64 {
        let finite: Vec<f64> = self
            .pairs
            .iter()
            .filter(|p| !p.is_essential())
            .map(|p| p.persistence())
            .collect();

        if finite.is_empty() {
            0.0
        } else {
            finite.iter().sum::<f64>() / finite.len() as f64
        }
    }

    /// Filter by minimum persistence
    pub fn filter_by_persistence(&self, min_persistence: f64) -> Self {
        Self {
            pairs: self
                .pairs
                .iter()
                .filter(|p| p.persistence() >= min_persistence)
                .cloned()
                .collect(),
            max_dim: self.max_dim,
        }
    }

    /// Number of features of each dimension
    pub fn feature_counts(&self) -> Vec<usize> {
        let mut counts = vec![0; self.max_dim + 1];
        for pair in &self.pairs {
            if pair.dimension <= self.max_dim {
                counts[pair.dimension] += 1;
            }
        }
        counts
    }
}

impl Default for PersistenceDiagram {
    fn default() -> Self {
        Self::new()
    }
}

/// Persistent homology computation
pub struct PersistentHomology {
    /// Working column representation (reduced boundary matrix)
    columns: Vec<Option<HashSet<usize>>>,
    /// Pivot to column mapping
    pivot_to_col: HashMap<usize, usize>,
    /// Birth times
    birth_times: Vec<f64>,
    /// Simplex dimensions
    dimensions: Vec<usize>,
}

impl PersistentHomology {
    /// Compute persistence from filtration
    pub fn compute(filtration: &Filtration) -> PersistenceDiagram {
        let mut ph = Self {
            columns: Vec::new(),
            pivot_to_col: HashMap::new(),
            birth_times: Vec::new(),
            dimensions: Vec::new(),
        };

        ph.run(filtration)
    }

    fn run(&mut self, filtration: &Filtration) -> PersistenceDiagram {
        let n = filtration.simplices.len();
        if n == 0 {
            return PersistenceDiagram::new();
        }

        // Build simplex index mapping
        let simplex_to_idx: HashMap<&Simplex, usize> = filtration
            .simplices
            .iter()
            .enumerate()
            .map(|(i, fs)| (&fs.simplex, i))
            .collect();

        // Initialize
        self.columns = Vec::with_capacity(n);
        self.birth_times = filtration.simplices.iter().map(|fs| fs.birth).collect();
        self.dimensions = filtration
            .simplices
            .iter()
            .map(|fs| fs.simplex.dim())
            .collect();

        // Build boundary matrix columns
        for fs in &filtration.simplices {
            let boundary = self.boundary(&fs.simplex, &simplex_to_idx);
            self.columns.push(if boundary.is_empty() {
                None
            } else {
                Some(boundary)
            });
        }

        // Reduce matrix
        self.reduce();

        // Extract persistence pairs
        self.extract_pairs()
    }

    /// Compute boundary of simplex as set of face indices
    fn boundary(&self, simplex: &Simplex, idx_map: &HashMap<&Simplex, usize>) -> HashSet<usize> {
        let mut boundary = HashSet::new();
        for face in simplex.faces() {
            if let Some(&idx) = idx_map.get(&face) {
                boundary.insert(idx);
            }
        }
        boundary
    }

    /// Reduce using standard persistence algorithm
    fn reduce(&mut self) {
        let n = self.columns.len();

        for j in 0..n {
            // Reduce column j
            while let Some(pivot) = self.get_pivot(j) {
                if let Some(&other) = self.pivot_to_col.get(&pivot) {
                    // Add column 'other' to column j (mod 2)
                    self.add_columns(j, other);
                } else {
                    // No collision, record pivot
                    self.pivot_to_col.insert(pivot, j);
                    break;
                }
            }
        }
    }

    /// Get pivot (largest index) of column
    fn get_pivot(&self, col: usize) -> Option<usize> {
        self.columns[col]
            .as_ref()
            .and_then(|c| c.iter().max().copied())
    }

    /// Add column src to column dst (XOR / mod 2)
    fn add_columns(&mut self, dst: usize, src: usize) {
        let src_col = self.columns[src].clone();
        if let (Some(ref mut dst_col), Some(ref src_col)) = (&mut self.columns[dst], &src_col) {
            // Symmetric difference
            let mut new_col = HashSet::new();
            for &idx in dst_col.iter() {
                if !src_col.contains(&idx) {
                    new_col.insert(idx);
                }
            }
            for &idx in src_col.iter() {
                if !dst_col.contains(&idx) {
                    new_col.insert(idx);
                }
            }
            if new_col.is_empty() {
                self.columns[dst] = None;
            } else {
                *dst_col = new_col;
            }
        }
    }

    /// Extract birth-death pairs from reduced matrix
    fn extract_pairs(&self) -> PersistenceDiagram {
        let n = self.columns.len();
        let mut diagram = PersistenceDiagram::new();
        let mut paired = HashSet::new();

        // Process pivot pairs (death creates pair with birth)
        for (&pivot, &col) in &self.pivot_to_col {
            let birth = self.birth_times[pivot];
            let death = self.birth_times[col];
            let dim = self.dimensions[pivot];

            if death > birth {
                diagram.add(BirthDeathPair::finite(dim, birth, death));
            }

            paired.insert(pivot);
            paired.insert(col);
        }

        // Remaining columns are essential (infinite persistence)
        for j in 0..n {
            if !paired.contains(&j) && self.columns[j].is_none() {
                let dim = self.dimensions[j];
                let birth = self.birth_times[j];
                diagram.add(BirthDeathPair::essential(dim, birth));
            }
        }

        diagram
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::homology::{PointCloud, VietorisRips};

    #[test]
    fn test_birth_death_pair() {
        let finite = BirthDeathPair::finite(0, 0.0, 1.0);
        assert_eq!(finite.persistence(), 1.0);
        assert!(!finite.is_essential());

        let essential = BirthDeathPair::essential(0, 0.0);
        assert!(essential.is_essential());
        assert_eq!(essential.persistence(), f64::INFINITY);
    }

    #[test]
    fn test_persistence_diagram() {
        let mut diagram = PersistenceDiagram::new();
        diagram.add(BirthDeathPair::essential(0, 0.0));
        diagram.add(BirthDeathPair::finite(0, 0.0, 1.0));
        diagram.add(BirthDeathPair::finite(1, 0.5, 2.0));

        assert_eq!(diagram.pairs.len(), 3);

        let betti = diagram.betti_at(0.75);
        assert_eq!(betti.b0, 2); // Both 0-dim features alive
        assert_eq!(betti.b1, 1); // 1-dim feature alive
    }

    #[test]
    fn test_persistent_homology_simple() {
        // Two points
        let cloud = PointCloud::from_flat(&[0.0, 0.0, 1.0, 0.0], 2);
        let rips = VietorisRips::new(1, 2.0);
        let filtration = rips.build(&cloud);

        let diagram = PersistentHomology::compute(&filtration);

        // Should have:
        // - One essential H0 (final connected component)
        // - One finite H0 that dies when edge connects the points
        let h0_pairs: Vec<_> = diagram.pairs_of_dim(0).collect();
        assert!(!h0_pairs.is_empty());
    }

    #[test]
    fn test_persistent_homology_triangle() {
        // Three points forming triangle
        let cloud = PointCloud::from_flat(&[0.0, 0.0, 1.0, 0.0, 0.5, 0.866], 2);
        let rips = VietorisRips::new(2, 2.0);
        let filtration = rips.build(&cloud);

        let diagram = PersistentHomology::compute(&filtration);

        // Should have H0 features (components merging)
        let h0_count = diagram.pairs_of_dim(0).count();
        assert!(h0_count > 0);
    }

    #[test]
    fn test_filter_by_persistence() {
        let mut diagram = PersistenceDiagram::new();
        diagram.add(BirthDeathPair::finite(0, 0.0, 0.1));
        diagram.add(BirthDeathPair::finite(0, 0.0, 1.0));
        diagram.add(BirthDeathPair::essential(0, 0.0));

        let filtered = diagram.filter_by_persistence(0.5);
        assert_eq!(filtered.pairs.len(), 2); // Only persistence >= 0.5
    }

    #[test]
    fn test_feature_counts() {
        let mut diagram = PersistenceDiagram::new();
        diagram.add(BirthDeathPair::finite(0, 0.0, 1.0));
        diagram.add(BirthDeathPair::finite(0, 0.0, 1.0));
        diagram.add(BirthDeathPair::finite(1, 0.0, 1.0));

        let counts = diagram.feature_counts();
        assert_eq!(counts[0], 2);
        assert_eq!(counts[1], 1);
    }
}