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
use crate::{
    algorithms::algorithm_result::AlgorithmResult,
    core::{entities::VID, state::compute_state::ComputeStateVec},
    db::{
        api::view::{NodeViewOps, StaticGraphViewOps},
        task::{
            context::Context,
            node::eval_node::EvalNodeView,
            task::{ATask, Job, Step},
            task_runner::TaskRunner,
        },
    },
};
use std::cmp;

#[derive(Clone, Debug, Default)]
struct WccState {
    component: u64,
}

/// Computes the connected community_detection of a graph using the Simple Connected Components algorithm
///
/// # Arguments
///
/// * `g` - A reference to the graph
/// * `iter_count` - The number of iterations to run
/// * `threads` - Number of threads to use
///
/// Returns:
///
/// An AlgorithmResult containing the mapping from the node to its component ID
///
pub fn weakly_connected_components<G>(
    graph: &G,
    iter_count: usize,
    threads: Option<usize>,
) -> AlgorithmResult<G, u64, u64>
where
    G: StaticGraphViewOps,
{
    let ctx: Context<G, ComputeStateVec> = graph.into();
    let step1 = ATask::new(move |vv| {
        let min_neighbour_id = vv.neighbours().id().min();
        let id = vv.id();
        let state: &mut WccState = vv.get_mut();
        state.component = cmp::min(min_neighbour_id.unwrap_or(id), id);
        Step::Continue
    });

    let step2 = ATask::new(move |vv: &mut EvalNodeView<G, WccState>| {
        let prev: u64 = vv.prev().component;
        let current = vv
            .neighbours()
            .into_iter()
            .map(|n| n.prev().component)
            .min()
            .unwrap_or(prev);
        let state: &mut WccState = vv.get_mut();
        if current < prev {
            state.component = current;
            Step::Continue
        } else {
            Step::Done
        }
    });

    let mut runner: TaskRunner<G, _> = TaskRunner::new(ctx);
    let results_type = std::any::type_name::<u64>();

    let res = runner.run(
        vec![Job::new(step1)],
        vec![Job::read_only(step2)],
        None,
        |_, _, _, local: Vec<WccState>| {
            graph
                .nodes()
                .iter()
                .map(|node| {
                    let VID(id) = node.node;
                    (id, local[id].component)
                })
                .collect()
        },
        threads,
        iter_count,
        None,
        None,
    );

    AlgorithmResult::new(graph.clone(), "Connected Components", results_type, res)
}

#[cfg(test)]
mod cc_test {
    use super::*;
    use crate::{db::api::mutation::AdditionOps, prelude::*, test_storage};
    use itertools::*;
    use quickcheck_macros::quickcheck;
    use std::{cmp::Reverse, collections::HashMap, iter::once};

    #[test]
    fn run_loop_simple_connected_components() {
        let graph = Graph::new();

        let edges = vec![
            (1, 2, 1),
            (2, 3, 2),
            (3, 4, 3),
            (3, 5, 4),
            (6, 5, 5),
            (7, 8, 6),
            (8, 7, 7),
        ];

        for (src, dst, ts) in edges {
            graph.add_edge(ts, src, dst, NO_PROPS, None).unwrap();
        }

        test_storage!(&graph, |graph| {
            let results = weakly_connected_components(graph, usize::MAX, None).get_all_with_names();
            assert_eq!(
                results,
                vec![
                    ("1".to_string(), 1),
                    ("2".to_string(), 1),
                    ("3".to_string(), 1),
                    ("4".to_string(), 1),
                    ("5".to_string(), 1),
                    ("6".to_string(), 1),
                    ("7".to_string(), 7),
                    ("8".to_string(), 7),
                ]
                .into_iter()
                .collect::<HashMap<String, u64>>()
            );
        });
    }

    #[test]
    fn simple_connected_components_2() {
        let graph = Graph::new();

        let edges = vec![
            (1, 2, 1),
            (1, 3, 2),
            (1, 4, 3),
            (3, 1, 4),
            (3, 4, 5),
            (3, 5, 6),
            (4, 5, 7),
            (5, 6, 8),
            (5, 8, 9),
            (7, 5, 10),
            (8, 5, 11),
            (1, 9, 12),
            (9, 1, 13),
            (6, 3, 14),
            (4, 8, 15),
            (8, 3, 16),
            (5, 10, 17),
            (10, 5, 18),
            (10, 8, 19),
            (1, 11, 20),
            (11, 1, 21),
            (9, 11, 22),
            (11, 9, 23),
        ];

        for (src, dst, ts) in edges {
            graph.add_edge(ts, src, dst, NO_PROPS, None).unwrap();
        }

        test_storage!(&graph, |graph| {
            let results = weakly_connected_components(graph, usize::MAX, None).get_all_with_names();

            assert_eq!(
                results,
                vec![
                    ("1".to_string(), 1),
                    ("2".to_string(), 1),
                    ("3".to_string(), 1),
                    ("4".to_string(), 1),
                    ("5".to_string(), 1),
                    ("6".to_string(), 1),
                    ("7".to_string(), 1),
                    ("8".to_string(), 1),
                    ("9".to_string(), 1),
                    ("10".to_string(), 1),
                    ("11".to_string(), 1),
                ]
                .into_iter()
                .collect::<HashMap<String, u64>>()
            );
        });
    }

    // connected community_detection on a graph with 1 node and a self loop
    #[test]
    fn simple_connected_components_3() {
        let graph = Graph::new();

        let edges = vec![(1, 1, 1)];

        for (src, dst, ts) in edges {
            graph.add_edge(ts, src, dst, NO_PROPS, None).unwrap();
        }

        test_storage!(&graph, |graph| {
            let results = weakly_connected_components(graph, usize::MAX, None).get_all_with_names();

            assert_eq!(
                results,
                vec![("1".to_string(), 1)]
                    .into_iter()
                    .collect::<HashMap<String, u64>>()
            );
        });
    }

    #[test]
    fn windowed_connected_components() {
        let graph = Graph::new();
        graph.add_edge(0, 1, 2, NO_PROPS, None).expect("add edge");
        graph.add_edge(0, 2, 1, NO_PROPS, None).expect("add edge");
        graph.add_edge(9, 3, 4, NO_PROPS, None).expect("add edge");
        graph.add_edge(9, 4, 3, NO_PROPS, None).expect("add edge");

        test_storage!(&graph, |graph| {
            let results = weakly_connected_components(graph, usize::MAX, None).get_all_with_names();
            let expected = vec![
                ("1".to_string(), 1),
                ("2".to_string(), 1),
                ("3".to_string(), 3),
                ("4".to_string(), 3),
            ]
            .into_iter()
            .collect::<HashMap<String, u64>>();

            assert_eq!(results, expected);

            let wg = graph.window(0, 2);
            let results = weakly_connected_components(&wg, usize::MAX, None).get_all_with_names();

            let expected = vec![("1", 1), ("2", 1)]
                .into_iter()
                .map(|(k, v)| (k.to_string(), v))
                .collect::<HashMap<String, u64>>();

            assert_eq!(results, expected);
        });
    }

    #[quickcheck]
    fn circle_graph_edges(vs: Vec<u64>) {
        if !vs.is_empty() {
            let vs = vs.into_iter().unique().collect::<Vec<u64>>();

            let _smallest = vs.iter().min().unwrap();

            let first = vs[0];
            // pairs of nodes from vs one after the next
            let edges = vs
                .iter()
                .zip(chain!(vs.iter().skip(1), once(&first)))
                .map(|(a, b)| (*a, *b))
                .collect::<Vec<(u64, u64)>>();

            assert_eq!(edges[0].0, first);
            assert_eq!(edges.last().unwrap().1, first);
        }
    }

    #[quickcheck]
    fn circle_graph_the_smallest_value_is_the_cc(vs: Vec<u64>) {
        if !vs.is_empty() {
            let graph = Graph::new();

            let vs = vs.into_iter().unique().collect::<Vec<u64>>();

            let smallest = vs.iter().min().unwrap();

            let first = vs[0];

            // pairs of nodes from vs one after the next
            let edges = vs
                .iter()
                .zip(chain!(vs.iter().skip(1), once(&first)))
                .map(|(a, b)| (*a, *b))
                .collect::<Vec<(u64, u64)>>();

            for (src, dst) in edges.iter() {
                graph.add_edge(0, *src, *dst, NO_PROPS, None).unwrap();
            }

            test_storage!(&graph, |graph| {
                // now we do connected community_detection over window 0..1
                let res = weakly_connected_components(graph, usize::MAX, None).group_by();

                let actual = res
                    .into_iter()
                    .map(|(cc, group)| (cc, Reverse(group.len())))
                    .sorted_by(|l, r| l.1.cmp(&r.1))
                    .map(|(cc, count)| (cc, count.0))
                    .take(1)
                    .next()
                    .unwrap();

                assert_eq!(actual, (*smallest, edges.len()));
            });
        }
    }
}