rustygraph 0.4.2

A high-performance library for visibility graph computation from time series data
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
//! Graph-theoretic metrics and analysis.
//!
//! This module provides functions to compute various graph-theoretic
//! properties of visibility graphs.

use crate::core::VisibilityGraph;
use std::collections::{HashMap, HashSet, VecDeque};

/// Helper struct to store BFS results for shortest path computation.
struct ShortestPathsInfo {
    distances: Vec<usize>,
    num_paths: Vec<usize>,
}

impl<T> VisibilityGraph<T> {
    /// Helper: Computes shortest paths from a source node using BFS.
    /// Returns distances and number of shortest paths to each node.
    fn compute_shortest_paths_from_source(&self, source: usize) -> ShortestPathsInfo {
        let mut distances = vec![usize::MAX; self.node_count];
        let mut num_paths = vec![0usize; self.node_count];
        let mut queue = VecDeque::new();

        distances[source] = 0;
        num_paths[source] = 1;
        queue.push_back(source);

        while let Some(v) = queue.pop_front() {
            for &neighbor in &self.neighbor_indices(v) {
                if distances[neighbor] == usize::MAX {
                    distances[neighbor] = distances[v] + 1;
                    num_paths[neighbor] = num_paths[v];
                    queue.push_back(neighbor);
                } else if distances[neighbor] == distances[v] + 1 {
                    num_paths[neighbor] += num_paths[v];
                }
            }
        }

        ShortestPathsInfo {
            distances,
            num_paths,
        }
    }

    /// Helper: Checks if a node lies on a shortest path from source to target.
    fn is_on_shortest_path(
        &self,
        node: usize,
        source: usize,
        target: usize,
        info: &ShortestPathsInfo,
    ) -> bool {
        if info.distances[target] == usize::MAX || info.distances[node] == usize::MAX {
            return false;
        }

        let dist_to_target = self.shortest_path_length(node, target).unwrap_or(usize::MAX);
        info.distances[source] + info.distances[node] + dist_to_target == info.distances[target]
    }

    /// Helper: Counts the contribution to betweenness centrality for a specific source node.
    fn count_betweenness_from_source(&self, node: usize, source: usize) -> f64 {
        let info = self.compute_shortest_paths_from_source(source);
        let mut contribution = 0.0;

        for target in 0..self.node_count {
            if target == source || target == node {
                continue;
            }

            if self.is_on_shortest_path(node, source, target, &info) && info.num_paths[target] > 0 {
                contribution += (info.num_paths[node] as f64) / (info.num_paths[target] as f64);
            }
        }

        contribution
    }

    /// Helper: Checks if an edge exists between two nodes (in either direction).
    #[inline]
    fn has_edge_between(&self, n1: usize, n2: usize) -> bool {
        self.edges.contains_key(&(n1, n2)) || self.edges.contains_key(&(n2, n1))
    }

    /// Helper: Counts edges between neighbors for clustering coefficient.
    fn count_neighbor_edges(&self, neighbors: &[usize]) -> usize {
        let mut count = 0;
        for i in 0..neighbors.len() {
            for j in (i + 1)..neighbors.len() {
                if self.has_edge_between(neighbors[i], neighbors[j]) {
                    count += 1;
                }
            }
        }
        count
    }

    /// Computes the clustering coefficient for a specific node.
    ///
    /// The clustering coefficient measures the degree to which nodes in a graph
    /// tend to cluster together. For a node, it's the ratio of actual connections
    /// between its neighbors to the maximum possible connections.
    ///
    /// # Arguments
    ///
    /// - `node`: Node index
    ///
    /// # Returns
    ///
    /// Clustering coefficient (0.0 to 1.0), or None if node doesn't exist
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// if let Some(cc) = graph.clustering_coefficient(1) {
    ///     println!("Clustering coefficient for node 1: {}", cc);
    /// }
    /// ```
    pub fn clustering_coefficient(&self, node: usize) -> Option<f64> {
        if node >= self.node_count {
            return None;
        }

        let neighbors = self.neighbor_indices(node);
        let k = neighbors.len();

        if k < 2 {
            return Some(0.0);
        }

        let actual_edges = self.count_neighbor_edges(&neighbors);
        let max_edges = k * (k - 1) / 2;

        Some(actual_edges as f64 / max_edges as f64)
    }

    /// Computes the average clustering coefficient for the entire graph.
    ///
    /// # Returns
    ///
    /// Average clustering coefficient across all nodes
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// let avg_cc = graph.average_clustering_coefficient();
    /// println!("Average clustering coefficient: {}", avg_cc);
    /// ```
    pub fn average_clustering_coefficient(&self) -> f64 {
        let mut sum = 0.0;
        let mut count = 0;

        for i in 0..self.node_count {
            if let Some(cc) = self.clustering_coefficient(i) {
                sum += cc;
                count += 1;
            }
        }

        if count > 0 {
            sum / count as f64
        } else {
            0.0
        }
    }

    /// Computes the shortest path length between two nodes using BFS.
    ///
    /// # Arguments
    ///
    /// - `source`: Source node index
    /// - `target`: Target node index
    ///
    /// # Returns
    ///
    /// Shortest path length, or None if no path exists or nodes don't exist
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// if let Some(dist) = graph.shortest_path_length(0, 3) {
    ///     println!("Distance from 0 to 3: {}", dist);
    /// }
    /// ```
    pub fn shortest_path_length(&self, source: usize, target: usize) -> Option<usize> {
        if source >= self.node_count || target >= self.node_count {
            return None;
        }

        if source == target {
            return Some(0);
        }

        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back((source, 0));
        visited.insert(source);

        while let Some((node, dist)) = queue.pop_front() {
            // Get neighbors
            for &neighbor in &self.neighbor_indices(node) {
                if neighbor == target {
                    return Some(dist + 1);
                }

                if !visited.contains(&neighbor) {
                    visited.insert(neighbor);
                    queue.push_back((neighbor, dist + 1));
                }
            }
        }

        None // No path found
    }

    /// Computes the average shortest path length (characteristic path length).
    ///
    /// Computes the average shortest path length between all node pairs.
    ///
    /// ⚠️ **Performance Warning:** This method has **O(n² + n×m)** complexity where n is the
    /// number of nodes and m is the number of edges. It runs BFS from each node to all others.
    /// For large graphs (> 1,000 nodes), this can be slow. Consider sampling or using
    /// approximation methods for very large graphs.
    ///
    /// # Returns
    ///
    /// Average path length, or 0 if no paths exist
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// let avg_path = graph.average_path_length();
    /// println!("Average path length: {:.2}", avg_path);
    /// ```
    pub fn average_path_length(&self) -> f64 {
        let mut sum = 0.0;
        let mut count = 0;

        for i in 0..self.node_count {
            for j in (i + 1)..self.node_count {
                if let Some(dist) = self.shortest_path_length(i, j) {
                    sum += dist as f64;
                    count += 1;
                }
            }
        }

        if count > 0 {
            sum / count as f64
        } else {
            0.0
        }
    }

    /// Computes the diameter of the graph (longest shortest path).
    ///
    /// ⚠️ **Performance Warning:** This method has **O(n² + n×m)** complexity.
    /// Similar to `average_path_length`, it's expensive for large graphs (> 1,000 nodes).
    ///
    /// # Returns
    ///
    /// Graph diameter, or 0 if graph has no edges
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// let diameter = graph.diameter();
    /// println!("Graph diameter: {}", diameter);
    /// ```
    pub fn diameter(&self) -> usize {
        let mut max_dist = 0;

        for i in 0..self.node_count {
            for j in (i + 1)..self.node_count {
                if let Some(dist) = self.shortest_path_length(i, j) {
                    max_dist = max_dist.max(dist);
                }
            }
        }

        max_dist
    }

    /// Computes the degree distribution of the graph.
    ///
    /// # Returns
    ///
    /// HashMap mapping degree to count of nodes with that degree
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// let dist = graph.degree_distribution();
    /// for (degree, count) in dist {
    ///     println!("Degree {}: {} nodes", degree, count);
    /// }
    /// ```
    pub fn degree_distribution(&self) -> HashMap<usize, usize> {
        let mut distribution = HashMap::new();

        for degree in self.degree_sequence() {
            *distribution.entry(degree).or_insert(0) += 1;
        }

        distribution
    }

    /// Checks if the graph is connected.
    ///
    /// # Returns
    ///
    /// True if all nodes are reachable from any other node
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// if graph.is_connected() {
    ///     println!("Graph is connected");
    /// }
    /// ```
    pub fn is_connected(&self) -> bool {
        if self.node_count == 0 {
            return true;
        }

        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back(0);
        visited.insert(0);

        while let Some(node) = queue.pop_front() {
            for &neighbor in &self.neighbor_indices(node) {
                if !visited.contains(&neighbor) {
                    visited.insert(neighbor);
                    queue.push_back(neighbor);
                }
            }
        }

        visited.len() == self.node_count
    }

    /// Computes graph density (ratio of actual edges to possible edges).
    ///
    /// For an undirected graph with n nodes, the maximum number of edges
    /// is n*(n-1)/2.
    ///
    /// # Returns
    ///
    /// Graph density (0.0 to 1.0)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// let density = graph.density();
    /// println!("Graph density: {:.3}", density);
    /// ```
    pub fn density(&self) -> f64 {
        let n = self.node_count;
        if n < 2 {
            return 0.0;
        }

        let max_edges = n * (n - 1) / 2;
        let actual_edges = self.edges.len();

        actual_edges as f64 / max_edges as f64
    }

    /// Computes betweenness centrality for a specific node.
    ///
    /// Betweenness centrality measures how often a node appears on shortest
    /// paths between other nodes. High betweenness indicates the node is
    /// important for connectivity.
    ///
    /// # Arguments
    ///
    /// - `node`: Node index
    ///
    /// # Returns
    ///
    /// Betweenness centrality value, or None if node doesn't exist
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0, 1.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// if let Some(bc) = graph.betweenness_centrality(2) {
    ///     println!("Betweenness centrality for node 2: {:.4}", bc);
    /// }
    /// ```
    pub fn betweenness_centrality(&self, node: usize) -> Option<f64> {
        if node >= self.node_count {
            return None;
        }

        let centrality = (0..self.node_count)
            .filter(|&s| s != node)
            .map(|s| self.count_betweenness_from_source(node, s))
            .sum::<f64>();

        // Normalize by the number of pairs
        let normalized = if self.node_count > 2 {
            centrality / ((self.node_count - 1) * (self.node_count - 2)) as f64
        } else {
            centrality
        };

        Some(normalized)
    }

    /// Computes betweenness centrality for all nodes.
    ///
    /// ⚠️ **Performance Warning:** This method has **O(n×m)** complexity using Brandes' algorithm,
    /// where n is nodes and m is edges. For large graphs (> 1,000 nodes), this can take significant
    /// time. This is the optimal algorithm for exact betweenness centrality.
    ///
    /// # Returns
    ///
    /// Vector of betweenness centrality values for each node
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustygraph::{TimeSeries, VisibilityGraph};
    ///
    /// let series = TimeSeries::from_raw(vec![1.0, 3.0, 2.0, 4.0, 1.0]).unwrap();
    /// let graph = VisibilityGraph::from_series(&series)
    ///     .natural_visibility()
    ///     .unwrap();
    ///
    /// let centralities = graph.betweenness_centrality_all();
    /// for (i, bc) in centralities.iter().enumerate() {
    ///     println!("Node {}: {:.4}", i, bc);
    /// }
    /// ```
    pub fn betweenness_centrality_all(&self) -> Vec<f64> {
        (0..self.node_count)
            .map(|i| self.betweenness_centrality(i).unwrap_or(0.0))
            .collect()
    }
}