-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtriangles.rs
More file actions
83 lines (73 loc) · 2.05 KB
/
triangles.rs
File metadata and controls
83 lines (73 loc) · 2.05 KB
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
/*!
Parallel triangle counting algorithms
*/
use rayon::prelude::*;
use std::collections::HashMap;
use crate::core::types::{BaseGraph, GraphConstructor, NodeId};
use petgraph::EdgeType;
/// Parallel triangle counting for all nodes.
///
/// Counts the number of triangles each node participates in, in parallel.
///
/// # Example
///
/// ```rust
/// use graphina::core::types::Graph;
/// use graphina::parallel::triangles_parallel;
///
/// let mut g = Graph::<i32, f64>::new();
/// let n1 = g.add_node(1);
/// let n2 = g.add_node(2);
/// let n3 = g.add_node(3);
/// g.add_edge(n1, n2, 1.0);
/// g.add_edge(n2, n3, 1.0);
/// g.add_edge(n3, n1, 1.0);
///
/// let triangles = triangles_parallel(&g);
/// assert_eq!(triangles[&n1], 1);
/// ```
pub fn triangles_parallel<A, W, Ty>(graph: &BaseGraph<A, W, Ty>) -> HashMap<NodeId, usize>
where
A: Sync,
W: Sync,
Ty: GraphConstructor<A, W> + EdgeType + Sync,
{
let nodes: Vec<NodeId> = graph.node_ids().collect();
nodes
.par_iter()
.map(|&node| {
let neighbors: Vec<NodeId> = graph.neighbors(node).collect();
let mut count = 0;
for i in 0..neighbors.len() {
for j in (i + 1)..neighbors.len() {
if graph.contains_edge(neighbors[i], neighbors[j]) {
count += 1;
}
}
}
(node, count)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::types::Graph;
#[test]
fn test_triangles_parallel() {
let mut g = Graph::<i32, f64>::new();
let n1 = g.add_node(1);
let n2 = g.add_node(2);
let n3 = g.add_node(3);
let n4 = g.add_node(4);
g.add_edge(n1, n2, 1.0);
g.add_edge(n2, n3, 1.0);
g.add_edge(n3, n1, 1.0);
g.add_edge(n1, n4, 1.0);
let triangles = triangles_parallel(&g);
assert_eq!(triangles[&n1], 1);
assert_eq!(triangles[&n2], 1);
assert_eq!(triangles[&n3], 1);
assert_eq!(triangles[&n4], 0);
}
}