prepona 0.1.0

A graph crate with simplicity in mind
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
use anyhow::Result;
use magnitude::Magnitude;
use num_traits::Zero;
use std::any::Any;
use std::collections::HashMap;

use crate::algo::Error;
use crate::graph::Edge;
use crate::provide;

/// Finds shortest path from all vertices to all the other ones using floyd-warshall algorithm.
///
/// # Examples
/// ```
/// use prepona::prelude::*;
/// use prepona::storage::DiMat;
/// use prepona::graph::MatGraph;
/// use prepona::algo::FloydWarshall;
/// use std::collections::HashMap;
/// use magnitude::Magnitude;
///
/// // Given: Graph
/// //          6       1
/// //      a  -->  b  <--  c ---
/// //    1 |       |           |
/// //      |  2 /`````\ 2      |
/// //      |````       ````|   |
/// //      v               v   | 1
/// //      d  ---------->  e --'
/// //              1
/// let mut graph = MatGraph::init(DiMat::<usize>::init());
/// let a = graph.add_vertex(); // 0
/// let b = graph.add_vertex(); // 1
/// let c = graph.add_vertex(); // 2
/// let d = graph.add_vertex(); // 3
/// let e = graph.add_vertex(); // 4
///
/// graph.add_edge_unchecked(a, b, 6.into());
/// graph.add_edge_unchecked(a, d, 1.into());
/// graph.add_edge_unchecked(b, d, 2.into());
/// graph.add_edge_unchecked(b, e, 2.into());
/// graph.add_edge_unchecked(c, b, 1.into());
/// graph.add_edge_unchecked(e, c, 1.into());
/// graph.add_edge_unchecked(d, e, 1.into());
///
/// // When: Performing FloydWarshall algorithm.
/// let distance_map = FloydWarshall::init().execute(&graph);
///
/// // Then:
/// assert!(distance_map.is_ok());
/// let distance_map = distance_map.unwrap();
///
/// let expected: HashMap<(usize, usize), Magnitude<usize>> = [
///     ((a, a), 0.into()),
///     ((a, b), 4.into()),
///     ((a, c), 3.into()),
///     ((a, d), 1.into()),
///     ((a, e), 2.into()),
///     ((b, b), 0.into()),
///     ((b, c), 3.into()),
///     ((b, d), 2.into()),
///     ((b, e), 2.into()),
///     ((c, b), 1.into()),
///     ((c, c), 0.into()),
///     ((c, d), 3.into()),
///     ((c, e), 3.into()),
///     ((d, b), 3.into()),
///     ((d, c), 2.into()),
///     ((d, d), 0.into()),
///     ((d, e), 1.into()),
///     ((e, b), 2.into()),
///     ((e, c), 1.into()),
///     ((e, d), 4.into()),
///     ((e, e), 0.into()),
/// ]
/// .iter()
/// .copied()
/// .collect();
///
/// let vertices = [a, b, c, d, e];
/// for v1_id in &vertices {
///     for v2_id in &vertices {
///         if let Some(dist) = expected.get(&(*v1_id, *v2_id)) {
///             assert_eq!(distance_map.get(&(*v1_id, *v2_id)).unwrap(), dist)
///         } else {
///             assert!(distance_map
///                 .get(&(*v1_id, *v2_id))
///                 .unwrap()
///                 .is_pos_infinite())
///         }
///     }
/// }
/// ```
pub struct FloydWarshall {}

impl FloydWarshall {
    /// Initializes the structure.
    pub fn init() -> Self {
        FloydWarshall {}
    }

    /// Finds shortest path from all vertices to all the other ones.
    ///
    /// # Arguments
    /// * `graph`: Graph to search for the shortest paths in.
    /// * `src_id`: Id of the source vertex(Shortest path will be calculated from this vertex to all other vertices)
    ///
    /// # Returns
    /// * `Ok`: Containing shortest path information in the form of: (src_id, dst_id) -> distance.
    /// * `Err`: If graph contains negative cycle.
    pub fn execute<G, W: Copy + Zero + Any + Ord, E: Edge<W>>(
        self,
        graph: &G,
    ) -> Result<HashMap<(usize, usize), Magnitude<W>>>
    where
        G: provide::Edges<W, E> + provide::Vertices,
    {
        let vertices = graph.vertices();
        let vertex_count = vertices.len();

        let id_map = graph.continuos_id_map();

        let mut dist = vec![vec![Magnitude::PosInfinite; vertex_count]; vertex_count];

        for &u_real_id in &vertices {
            let u_virt_id = id_map.virt_id_of(u_real_id);
            dist[u_virt_id][u_virt_id] = W::zero().into();
        }

        for &u_real_id in &vertices {
            let u_virt_id = id_map.virt_id_of(u_real_id);

            for (v_real_id, edge) in graph.edges_from_unchecked(u_real_id) {
                let v_virt_id = id_map.virt_id_of(v_real_id);
                dist[u_virt_id][v_virt_id] = edge.get_weight().clone();
            }
        }

        for k in 0..vertex_count {
            for &i in &vertices {
                let i_virt_id = id_map.virt_id_of(i);
                for &j in &vertices {
                    let j_virt_id = id_map.virt_id_of(j);

                    if (dist[i_virt_id][k] + dist[k][j_virt_id]).is_finite()
                        && dist[i_virt_id][j_virt_id] > dist[i_virt_id][k] + dist[k][j_virt_id]
                    {
                        dist[i_virt_id][j_virt_id] = dist[i_virt_id][k] + dist[k][j_virt_id]
                    }
                }

                // check for negative cycle
                for v_id in &vertices {
                    let v_virt_id = id_map.virt_id_of(*v_id);
                    if dist[v_virt_id][v_virt_id] < W::zero().into() {
                        Err(Error::new_ncd())?
                    }
                }
            }
        }

        let mut distance_map = HashMap::new();
        for i in 0..vertex_count {
            let i_real_id = id_map.real_id_of(i);
            for j in 0..vertex_count {
                let j_real_id = id_map.real_id_of(j);

                distance_map.insert((i_real_id, j_real_id), dist[i][j].clone());
            }
        }

        Ok(distance_map)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::MatGraph;
    use crate::provide::*;
    use crate::storage::{DiMat, Mat};

    #[test]
    fn empty_directed_graph() {
        // Given:
        let graph = MatGraph::init(DiMat::<usize>::init());

        let distance_map = FloydWarshall::init().execute(&graph);

        assert_eq!(distance_map.unwrap().keys().len(), 0);
    }

    #[test]
    fn empty_undirected_graph() {
        // Given:
        let graph = MatGraph::init(Mat::<usize>::init());

        let distance_map = FloydWarshall::init().execute(&graph);

        assert_eq!(distance_map.unwrap().keys().len(), 0);
    }

    #[test]
    fn trivial_undirected_graph() {
        // Given: Graph
        //          6       5
        //      a  ---  b  ---  c
        //    1 |       |       | 5
        //      |  2 /`````\ 2  |
        //      |````       ````|
        //      d  -----------  e
        //              1
        let mut graph = MatGraph::init(Mat::<usize>::init());
        let a = graph.add_vertex();
        let b = graph.add_vertex();
        let c = graph.add_vertex();
        let d = graph.add_vertex();
        let e = graph.add_vertex();

        graph.add_edge_unchecked(a, b, 6.into());
        graph.add_edge_unchecked(a, d, 1.into());
        graph.add_edge_unchecked(b, d, 2.into());
        graph.add_edge_unchecked(b, c, 5.into());
        graph.add_edge_unchecked(b, e, 2.into());
        graph.add_edge_unchecked(c, e, 5.into());
        graph.add_edge_unchecked(d, e, 1.into());

        // When: Performing FloydWarshall algorithm.
        let distance_map = FloydWarshall::init().execute(&graph);

        // Then:
        assert!(distance_map.is_ok());
        let distance_map = distance_map.unwrap();

        let expected: HashMap<(usize, usize), Magnitude<usize>> = [
            ((a, a), 0.into()),
            ((a, b), 3.into()),
            ((a, c), 7.into()),
            ((a, d), 1.into()),
            ((a, e), 2.into()),
            ((b, a), 3.into()),
            ((b, b), 0.into()),
            ((b, c), 5.into()),
            ((b, d), 2.into()),
            ((b, e), 2.into()),
            ((c, a), 7.into()),
            ((c, b), 5.into()),
            ((c, c), 0.into()),
            ((c, d), 6.into()),
            ((c, e), 5.into()),
            ((d, a), 1.into()),
            ((d, b), 2.into()),
            ((d, c), 6.into()),
            ((d, d), 0.into()),
            ((d, e), 1.into()),
            ((e, a), 2.into()),
            ((e, b), 2.into()),
            ((e, c), 5.into()),
            ((e, d), 1.into()),
            ((e, e), 0.into()),
        ]
        .iter()
        .copied()
        .collect();

        let vertices = [a, b, c, d, e];
        for v1_id in &vertices {
            for v2_id in &vertices {
                assert_eq!(
                    distance_map.get(&(*v1_id, *v2_id)),
                    expected.get(&(*v1_id, *v2_id))
                )
            }
        }
    }

    #[test]
    fn trivial_directed_graph() {
        // Given: Graph
        //          6       1
        //      a  -->  b  <--  c ---
        //    1 |       |           |
        //      |  2 /`````\ 2      |
        //      |````       ````|   |
        //      v               v   | 1
        //      d  ---------->  e --'
        //              1
        let mut graph = MatGraph::init(DiMat::<usize>::init());
        let a = graph.add_vertex(); // 0
        let b = graph.add_vertex(); // 1
        let c = graph.add_vertex(); // 2
        let d = graph.add_vertex(); // 3
        let e = graph.add_vertex(); // 4

        graph.add_edge_unchecked(a, b, 6.into());
        graph.add_edge_unchecked(a, d, 1.into());
        graph.add_edge_unchecked(b, d, 2.into());
        graph.add_edge_unchecked(b, e, 2.into());
        graph.add_edge_unchecked(c, b, 1.into());
        graph.add_edge_unchecked(e, c, 1.into());
        graph.add_edge_unchecked(d, e, 1.into());

        // When: Performing FloydWarshall algorithm.
        let distance_map = FloydWarshall::init().execute(&graph);

        // Then:
        assert!(distance_map.is_ok());
        let distance_map = distance_map.unwrap();

        let expected: HashMap<(usize, usize), Magnitude<usize>> = [
            ((a, a), 0.into()),
            ((a, b), 4.into()),
            ((a, c), 3.into()),
            ((a, d), 1.into()),
            ((a, e), 2.into()),
            ((b, b), 0.into()),
            ((b, c), 3.into()),
            ((b, d), 2.into()),
            ((b, e), 2.into()),
            ((c, b), 1.into()),
            ((c, c), 0.into()),
            ((c, d), 3.into()),
            ((c, e), 3.into()),
            ((d, b), 3.into()),
            ((d, c), 2.into()),
            ((d, d), 0.into()),
            ((d, e), 1.into()),
            ((e, b), 2.into()),
            ((e, c), 1.into()),
            ((e, d), 4.into()),
            ((e, e), 0.into()),
        ]
        .iter()
        .copied()
        .collect();

        let vertices = [a, b, c, d, e];
        for v1_id in &vertices {
            for v2_id in &vertices {
                if let Some(dist) = expected.get(&(*v1_id, *v2_id)) {
                    assert_eq!(distance_map.get(&(*v1_id, *v2_id)).unwrap(), dist)
                } else {
                    assert!(distance_map
                        .get(&(*v1_id, *v2_id))
                        .unwrap()
                        .is_pos_infinite())
                }
            }
        }
    }

    #[test]
    fn undirected_graph_with_negative_cycle() {
        // Given: Graph
        //          1
        //      a ----- b
        //      |       | 2
        //      '------ c
        //          -5
        //
        let mut graph = MatGraph::init(Mat::<isize>::init());
        let a = graph.add_vertex();
        let b = graph.add_vertex();
        let c = graph.add_vertex();
        graph.add_edge_unchecked(a, b, 1.into());
        graph.add_edge_unchecked(b, c, 2.into());
        graph.add_edge_unchecked(c, a, (-5).into());

        // When: Performing FloydWarshall algorithm.
        let distance_map = FloydWarshall::init().execute(&graph);

        assert!(distance_map.is_err());
    }

    #[test]
    fn undirected_graph_with_negative_walk() {
        // Given: Graph
        //          -1
        //      a ----- b
        //
        let mut graph = MatGraph::init(Mat::<isize>::init());
        let a = graph.add_vertex();
        let b = graph.add_vertex();
        graph.add_edge_unchecked(a, b, (-1).into());

        let shortest_paths = FloydWarshall::init().execute(&graph);

        assert!(shortest_paths.is_err());
    }

    #[test]
    fn directed_graph_with_negative_cycle() {
        // Given: Graph
        //          1
        //      a ----> b
        //      ^       | 2
        //      |       v
        //      '------ c
        //          -5
        //
        let mut graph = MatGraph::init(DiMat::<isize>::init());
        let a = graph.add_vertex();
        let b = graph.add_vertex();
        let c = graph.add_vertex();
        graph.add_edge_unchecked(a, b, 1.into());
        graph.add_edge_unchecked(b, c, 2.into());
        graph.add_edge_unchecked(c, a, (-5).into());

        // When: Performing FloydWarshall algorithm.
        let shortest_paths = FloydWarshall::init().execute(&graph);

        assert!(shortest_paths.is_err());
    }
}