rust-igraph 0.0.1-alpha.3

Pure-Rust, high-performance graph & network analysis library — 370+ algorithms, zero unsafe, igraph-compatible
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
//! All-pairs unweighted shortest distances (ALGO-SP-058).
//!
//! Counterpart of `igraph_distances()` (multi-source mode) from
//! `references/igraph/src/paths/unweighted.c`.
//!
//! Computes shortest-path distances between all pairs of vertices
//! using BFS from each source. Returns an n×n flat matrix.

use std::collections::VecDeque;

use crate::core::{Graph, IgraphError, IgraphResult, VertexId};

/// All-pairs unweighted shortest distances.
///
/// Returns a flat `Vec<Option<u32>>` of length `n * n` in row-major
/// order, where `result[i * n + j]` is the shortest-path distance
/// from vertex `i` to vertex `j`. `None` means unreachable.
///
/// For undirected graphs, the matrix is symmetric. For directed
/// graphs, follows outgoing edges by default; use
/// [`distances_all_with_mode`] for direction control.
///
/// # Errors
///
/// Returns an error if internal BFS encounters an issue (should not
/// happen for valid graphs).
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, distances_all};
///
/// // Triangle: all distances are 0 or 1.
/// let mut g = Graph::with_vertices(3);
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// g.add_edge(2, 0).unwrap();
/// let d = distances_all(&g).unwrap();
/// assert_eq!(d[0 * 3 + 1], Some(1)); // 0→1
/// assert_eq!(d[0 * 3 + 2], Some(1)); // 0→2
/// assert_eq!(d[1 * 3 + 2], Some(1)); // 1→2
/// assert_eq!(d[0 * 3 + 0], Some(0)); // self
/// ```
pub fn distances_all(graph: &Graph) -> IgraphResult<Vec<Option<u32>>> {
    let n = graph.vcount();
    let n_us = n as usize;

    if n == 0 {
        return Ok(Vec::new());
    }

    let mut result = vec![
        None;
        n_us.checked_mul(n_us).ok_or_else(|| {
            IgraphError::InvalidArgument("distances_all: n*n overflows usize".into())
        })?
    ];

    if graph.is_directed() {
        let adj = build_out_adj(graph, n_us)?;
        for src in 0..n {
            bfs_distances_with_adj(&adj, src, n_us, &mut result);
        }
    } else {
        for src in 0..n {
            bfs_distances_undirected(graph, src, n_us, &mut result)?;
        }
    }

    Ok(result)
}

/// Direction mode for [`distances_all_with_mode`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DistancesMode {
    /// Follow outgoing edges.
    Out,
    /// Follow incoming edges.
    In,
    /// Ignore edge direction.
    All,
}

/// All-pairs shortest distances with direction control.
///
/// For undirected graphs, `mode` is ignored.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, distances_all_with_mode, DistancesMode};
///
/// // Directed: 0→1→2
/// let mut g = Graph::new(3, true).unwrap();
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// let d = distances_all_with_mode(&g, DistancesMode::Out).unwrap();
/// assert_eq!(d[0 * 3 + 2], Some(2)); // 0→1→2
/// assert_eq!(d[2 * 3 + 0], None);    // 2 cannot reach 0
/// let d_in = distances_all_with_mode(&g, DistancesMode::In).unwrap();
/// assert_eq!(d_in[2 * 3 + 0], Some(2)); // follow incoming from 2
/// ```
pub fn distances_all_with_mode(
    graph: &Graph,
    mode: DistancesMode,
) -> IgraphResult<Vec<Option<u32>>> {
    let n = graph.vcount();
    let n_us = n as usize;

    if n == 0 {
        return Ok(Vec::new());
    }

    let mut result = vec![
        None;
        n_us.checked_mul(n_us).ok_or_else(|| {
            IgraphError::InvalidArgument("distances_all_with_mode: n*n overflows usize".into())
        })?
    ];

    if !graph.is_directed() {
        for src in 0..n {
            bfs_distances_undirected(graph, src, n_us, &mut result)?;
        }
        return Ok(result);
    }

    let adj = match mode {
        DistancesMode::Out => build_out_adj(graph, n_us)?,
        DistancesMode::In => build_in_adj(graph, n_us)?,
        DistancesMode::All => build_all_adj(graph, n_us)?,
    };

    for src in 0..n {
        bfs_distances_with_adj(&adj, src, n_us, &mut result);
    }

    Ok(result)
}

/// BFS from `source` using `graph.neighbors()` (undirected).
fn bfs_distances_undirected(
    graph: &Graph,
    source: VertexId,
    n_us: usize,
    result: &mut [Option<u32>],
) -> IgraphResult<()> {
    let src_us = source as usize;
    let row_offset = src_us * n_us;

    let mut visited = vec![false; n_us];
    let mut queue = VecDeque::new();

    visited[src_us] = true;
    result[row_offset + src_us] = Some(0);
    queue.push_back((source, 0u32));

    while let Some((cur, dist)) = queue.pop_front() {
        let neighbors = graph.neighbors(cur)?;
        let next_dist = dist + 1;
        for &nb in &neighbors {
            let nb_idx = nb as usize;
            if !visited[nb_idx] {
                visited[nb_idx] = true;
                result[row_offset + nb_idx] = Some(next_dist);
                queue.push_back((nb, next_dist));
            }
        }
    }

    Ok(())
}

/// BFS from `source` using a pre-built adjacency list.
fn bfs_distances_with_adj(
    adj: &[Vec<VertexId>],
    source: VertexId,
    n_us: usize,
    result: &mut [Option<u32>],
) {
    let src_us = source as usize;
    let row_offset = src_us * n_us;

    let mut visited = vec![false; n_us];
    let mut queue = VecDeque::new();

    visited[src_us] = true;
    result[row_offset + src_us] = Some(0);
    queue.push_back((source, 0u32));

    while let Some((cur, dist)) = queue.pop_front() {
        let next_dist = dist + 1;
        for &nb in &adj[cur as usize] {
            let nb_idx = nb as usize;
            if !visited[nb_idx] {
                visited[nb_idx] = true;
                result[row_offset + nb_idx] = Some(next_dist);
                queue.push_back((nb, next_dist));
            }
        }
    }
}

fn build_out_adj(graph: &Graph, n_us: usize) -> IgraphResult<Vec<Vec<VertexId>>> {
    let m =
        u32::try_from(graph.ecount()).map_err(|_| IgraphError::Internal("ecount overflows u32"))?;
    let mut adj: Vec<Vec<VertexId>> = vec![Vec::new(); n_us];
    for eid in 0..m {
        let (from, to) = graph.edge(eid)?;
        adj[from as usize].push(to);
    }
    Ok(adj)
}

fn build_in_adj(graph: &Graph, n_us: usize) -> IgraphResult<Vec<Vec<VertexId>>> {
    let m =
        u32::try_from(graph.ecount()).map_err(|_| IgraphError::Internal("ecount overflows u32"))?;
    let mut adj: Vec<Vec<VertexId>> = vec![Vec::new(); n_us];
    for eid in 0..m {
        let (from, to) = graph.edge(eid)?;
        adj[to as usize].push(from);
    }
    Ok(adj)
}

fn build_all_adj(graph: &Graph, n_us: usize) -> IgraphResult<Vec<Vec<VertexId>>> {
    let m =
        u32::try_from(graph.ecount()).map_err(|_| IgraphError::Internal("ecount overflows u32"))?;
    let mut adj: Vec<Vec<VertexId>> = vec![Vec::new(); n_us];
    for eid in 0..m {
        let (from, to) = graph.edge(eid)?;
        adj[from as usize].push(to);
        if from != to {
            adj[to as usize].push(from);
        }
    }
    Ok(adj)
}

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

    #[test]
    fn empty_graph() {
        let g = Graph::with_vertices(0);
        let d = distances_all(&g).unwrap();
        assert!(d.is_empty());
    }

    #[test]
    fn singleton() {
        let g = Graph::with_vertices(1);
        let d = distances_all(&g).unwrap();
        assert_eq!(d, vec![Some(0)]);
    }

    #[test]
    fn path_graph() {
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 3).unwrap();
        let d = distances_all(&g).unwrap();
        let n = 4usize;
        assert_eq!(d[0], Some(0)); // row 0, col 0
        assert_eq!(d[1], Some(1)); // row 0, col 1
        assert_eq!(d[2], Some(2)); // row 0, col 2
        assert_eq!(d[3], Some(3)); // row 0, col 3
        assert_eq!(d[3 * n], Some(3)); // row 3, col 0
        assert_eq!(d[n + 3], Some(2)); // row 1, col 3
    }

    #[test]
    fn triangle() {
        let mut g = Graph::with_vertices(3);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 0).unwrap();
        let d = distances_all(&g).unwrap();
        let n = 3;
        for i in 0..n {
            assert_eq!(d[i * n + i], Some(0));
            for j in 0..n {
                if i != j {
                    assert_eq!(d[i * n + j], Some(1));
                }
            }
        }
    }

    #[test]
    fn two_components() {
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(2, 3).unwrap();
        let d = distances_all(&g).unwrap();
        let n = 4usize;
        assert_eq!(d[1], Some(1)); // row 0, col 1
        assert_eq!(d[2 * n + 3], Some(1));
        assert_eq!(d[2], None); // row 0, col 2
        assert_eq!(d[n + 3], None); // row 1, col 3
    }

    #[test]
    fn cycle_5() {
        let mut g = Graph::with_vertices(5);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 3).unwrap();
        g.add_edge(3, 4).unwrap();
        g.add_edge(4, 0).unwrap();
        let d = distances_all(&g).unwrap();
        // Row 0: distances from vertex 0
        assert_eq!(d[0], Some(0));
        assert_eq!(d[1], Some(1));
        assert_eq!(d[2], Some(2));
        assert_eq!(d[3], Some(2));
        assert_eq!(d[4], Some(1));
    }

    #[test]
    fn directed_out() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let d = distances_all(&g).unwrap();
        let n = 3usize;
        assert_eq!(d[2], Some(2)); // row 0, col 2
        assert_eq!(d[2 * n], None); // row 2, col 0
        assert_eq!(d[n], None); // row 1, col 0
    }

    #[test]
    fn directed_in_mode() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let d = distances_all_with_mode(&g, DistancesMode::In).unwrap();
        let n = 3usize;
        // Following incoming edges: from 2 we can reach 1 (in 1 hop) and 0 (in 2 hops)
        assert_eq!(d[2 * n + 1], Some(1));
        assert_eq!(d[2 * n], Some(2)); // row 2, col 0
        assert_eq!(d[1], None); // row 0, col 1: 0 has no incoming
    }

    #[test]
    fn directed_all_mode() {
        let mut g = Graph::new(3, true).unwrap();
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        let d = distances_all_with_mode(&g, DistancesMode::All).unwrap();
        let n = 3;
        // All mode: treat as undirected
        assert_eq!(d[2], Some(2));
        assert_eq!(d[2 * n], Some(2));
    }

    #[test]
    fn symmetric_undirected() {
        let mut g = Graph::with_vertices(5);
        g.add_edge(0, 1).unwrap();
        g.add_edge(1, 2).unwrap();
        g.add_edge(2, 3).unwrap();
        g.add_edge(3, 4).unwrap();
        let d = distances_all(&g).unwrap();
        let n = 5;
        for i in 0..n {
            for j in 0..n {
                assert_eq!(d[i * n + j], d[j * n + i], "not symmetric at ({i},{j})");
            }
        }
    }

    #[test]
    fn isolated_vertices() {
        let g = Graph::with_vertices(3);
        let d = distances_all(&g).unwrap();
        let n = 3;
        for i in 0..n {
            assert_eq!(d[i * n + i], Some(0));
            for j in 0..n {
                if i != j {
                    assert_eq!(d[i * n + j], None);
                }
            }
        }
    }

    #[test]
    fn oracle_star() {
        // Star: center 0, leaves 1,2,3.
        // Verified against python-igraph.
        let mut g = Graph::with_vertices(4);
        g.add_edge(0, 1).unwrap();
        g.add_edge(0, 2).unwrap();
        g.add_edge(0, 3).unwrap();
        let d = distances_all(&g).unwrap();
        let n = 4;
        // Center to leaves: 1
        for item in d.iter().take(4).skip(1) {
            assert_eq!(*item, Some(1));
        }
        // Leaf to leaf: 2
        assert_eq!(d[n + 2], Some(2));
        assert_eq!(d[n + 3], Some(2));
        assert_eq!(d[2 * n + 3], Some(2));
    }
}