rugraph 1.3.0

Simple undirected, directed and multidirected graph library.
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
use crate::rugraph::IDiGraph;
use crate::rugraph::IGraph;
use std::cell::RefCell;
use std::fs::File;
use std::io::Write;
use std::rc::Rc;
use std::vec::Vec;

/// `DiGraph` is actually a `generic` directed graph where each node of type `T`
///  must implement: `T: Ord + Clone + std::fmt::Display + std::fmt::Debug`
pub struct DiGraph<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    /// Nodes are stored in the heap
    nodes: RefCell<Vec<Rc<Node<T>>>>,
}
/// A `Node` is represented as a generic `T` and a list of pointers to their neighbors (allocated in the heap)
struct Node<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    elem: T,
    neighbors: RefCell<Vec<Rc<Node<T>>>>,
}

impl<T> Node<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    pub fn new(elem: T) -> Self {
        Node::<T> {
            elem: elem,
            neighbors: RefCell::new(Vec::new()),
        }
    }
}

impl<T> DiGraph<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    pub fn new() -> Self {
        DiGraph::<T> {
            nodes: RefCell::new(vec![]),
        }
    }

    fn get_index_by_node_id(&self, from: T) -> Result<usize, &'static str> {
        let nodes = self.nodes.borrow();
        let idx_from = nodes.iter().position(|r| r.elem == from);
        match idx_from {
            None => Err("Element not found"),
            Some(value) => Ok(value),
        }
    }

    /// Deep first search. Helper function to get all the simple paths
    fn dfs(
        &self,
        from: T,
        to: T,
        simple_path: &mut Vec<Vec<T>>,
        current_path: &mut Vec<T>,
        visited: &mut Vec<T>,
    ) {
        if visited.contains(&from) {
            return;
        }
        visited.push(from.clone());
        current_path.push(from.clone());
        if from == to {
            simple_path.push(current_path.clone());
            if visited.contains(&from) {
                let index = visited.iter().position(|x| *x == from).unwrap();
                visited.remove(index);
                current_path.pop();
                return;
            }
        }

        let neighbors = self.get_neighbors(from.clone());
        for n in neighbors.iter() {
            self.dfs(n.clone(), to.clone(), simple_path, current_path, visited);
        }

        current_path.pop();
        if visited.contains(&from) {
            let index = visited.iter().position(|x| *x == from).unwrap();
            visited.remove(index);
        }
    }
}

impl<T> IGraph<T> for DiGraph<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    fn add_node(&mut self, elem: T) {
        if self.node_exists(elem.clone()) {
            return;
        }

        let mut nodes = self.nodes.borrow_mut();
        let n = Rc::new(Node::<T>::new(elem));

        //println!("Adding new node {}", n.elem);

        nodes.push(n);
        //println!("nodes length: {}", nodes.len());
    }

    fn node_exists(&self, node: T) -> bool {
        let nodes = self.nodes.borrow();
        let idx_from = nodes.iter().position(|r| r.elem == node);
        match idx_from {
            None => {
                return false;
            }
            Some(_value) => {
                return true;
            }
        }
    }

    fn is_connected(&self, from: T, to: T) -> bool {
        //println!("Checking from {} to {}", from, to);
        let mut seen = Vec::<T>::new();
        let mut to_process = Vec::<T>::new();
        seen.push(from.clone());
        to_process.push(from.clone());

        let mut end = false;
        while !end {
            let node_id = to_process.pop().unwrap().clone();

            let neighbors = self.get_neighbors(node_id.clone());
            //println!("  |-> Node {} neighbors {:?}", node_id, neighbors);
            if neighbors.contains(&to) {
                return true;
            } else {
                for n in neighbors.iter() {
                    if !seen.contains(n) {
                        to_process.push(n.clone());
                        seen.push(n.clone());
                    }
                }
            }

            end = to_process.is_empty();
        }

        return false;
    }

    fn is_directly_connected(&self, from: T, to: T) -> bool {
        let nodes = self.nodes.borrow();
        let ret_idx_from = self.get_index_by_node_id(from.clone());
        let idx_from;
        match ret_idx_from {
            Ok(v) => idx_from = v,
            Err(e) => {
                println!("Error {}", e);
                return false;
            }
        };

        let ret_idx_to = self.get_index_by_node_id(to.clone());
        let idx_to;
        match ret_idx_to {
            Ok(v) => idx_to = v,
            Err(e) => {
                println!("Error {}", e);
                return false;
            }
        };

        let n = &nodes[idx_from];
        let m = nodes[idx_to].clone();
        for e in n.neighbors.borrow().iter() {
            if Rc::ptr_eq(e, &m) {
                //println!("Node {} is connected to {}", from, to);
                return true;
            }
        }
        //println!("Node {} is NOT connected to {}", from, to);
        return false;
    }

    fn to_dot_file(&self, file: &mut File, graph_name: &str) {
        let s = self.to_dot_string(graph_name);
        file.write_all(s.as_bytes()).expect("Error writing file!");
    }

    fn to_dot_string(&self, graph_name: &str) -> String {
        let mut s = String::from("digraph ") + graph_name + &String::from(" {\n");
        let nodes = self.nodes.borrow();
        for n in nodes.iter() {
            s = s + &String::from("    ") + &n.elem.to_string();
            for m in n.neighbors.borrow().iter() {
                s = s + &String::from(" -> ") + &m.elem.to_string();
            }

            s = s + &String::from(";\n");
        }
        s = s + &String::from("}\n");
        return s;
    }

    fn is_empty(&self) -> bool {
        return self.nodes.borrow().is_empty();
    }

    fn count_nodes(&self) -> usize {
        return self.nodes.borrow().len();
    }

    fn get_nodes(&self) -> Vec<T> {
        let mut ret = Vec::<T>::new();
        for n in self.nodes.borrow().iter() {
            ret.push(n.elem.clone());
        }
        return ret;
    }
}

impl<T> IDiGraph<T> for DiGraph<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    fn add_edge(&mut self, from: T, to: T) {
        if !self.node_exists(from.clone())
            || !self.node_exists(to.clone())
            || self.is_directly_connected(from.clone(), to.clone())
        {
            return;
        }

        let nodes = self.nodes.borrow_mut();

        let idx_from = nodes.iter().position(|r| r.elem == from).unwrap();
        let idx_to = nodes.iter().position(|r| r.elem == to).unwrap();

        let n = &nodes[idx_from];
        let m = nodes[idx_to].clone();

        n.neighbors.borrow_mut().push(m);
    }

    fn all_simple_paths(&self, from: T, to: T) -> Vec<Vec<T>> {
        let mut ret = Vec::<Vec<T>>::new();
        let mut current_path = Vec::<T>::new();
        let mut visited = Vec::<T>::new();

        self.dfs(from, to, &mut ret, &mut current_path, &mut visited);

        return ret;
    }

    fn get_neighbors(&self, from: T) -> Vec<T> {
        let mut neighbors = Vec::<T>::new();

        if !self.node_exists(from.clone()) {
            return neighbors;
        }

        let nodes = self.nodes.borrow();

        let idx_from = nodes.iter().position(|r| r.elem == from).unwrap();

        let n = &nodes[idx_from];

        //n.neighbors
        for e in n.neighbors.borrow().iter() {
            neighbors.push(e.elem.clone());
        }

        return neighbors;
    }
}

impl<T> Drop for DiGraph<T>
where
    T: Ord + Clone + std::fmt::Display + std::fmt::Debug,
{
    fn drop(&mut self) {
        self.nodes.borrow_mut().clear();
    }
}

/// Returns a directed string graph `DiGraph<String>` from a dot file content
pub fn digraph_from_dot_string(content: &String) -> Result<DiGraph<String>, &'static str> {
    let mut graph = DiGraph::<String>::new();
    let idx1: usize;
    let idx2: usize;
    match content.chars().position(|c| c == '{') {
        None => {
            return Err("Dot file not correct. { not found.");
        }
        Some(i) => {
            idx1 = i + 1;
        }
    }

    match content.chars().position(|c| c == '}') {
        None => {
            return Err("Dot file not correct. } not found.");
        }
        Some(i) => {
            idx2 = i - 1;
        }
    }

    if idx2 < idx1 {
        return Err("Dot file not correct. } before {");
    }

    let c = &content[idx1..idx2];
    let v_c: Vec<&str> = c.split(';').collect();

    for line in v_c.iter() {
        let v_nodes: Vec<&str> = line.split("->").collect();
        let mut prev_node = String::new();
        for txt_node in v_nodes.iter() {
            let txt_n = txt_node.replace(";", "");
            let n = txt_n.trim().to_string();
            if !n.is_empty() {
                // println!("Adding node {}", n.clone());
                graph.add_node(n.clone());
            }
            if !prev_node.is_empty() {
                // println!("  |-> Edge {} to {}",prev_node, n);
                graph.add_edge(prev_node.clone(), n.clone());
            }
            prev_node = n.clone();
        }
    }

    Ok(graph)
}

#[cfg(test)]
mod tests {
    use super::DiGraph;
    use crate::digraph::digraph_from_dot_string;
    use crate::rugraph::IDiGraph;
    use crate::rugraph::IGraph;
    use std::fs::File;
    #[test]
    fn digraph_it_works() {
        let mut graph = DiGraph::<i32>::new();
        graph.add_node(1);

        let exists = graph.node_exists(1);
        assert_eq!(exists, true);
        let exists = graph.node_exists(99);
        assert_eq!(exists, false);

        graph.add_node(2);
        graph.add_node(3);
        graph.add_node(4);
        graph.add_node(5);
        graph.add_node(6);
        graph.add_node(7);
        graph.add_edge(1, 2);
        graph.add_edge(2, 3);
        graph.add_edge(2, 4);
        graph.add_edge(2, 5);
        graph.add_edge(5, 7);

        let ret = graph.is_directly_connected(1, 2);
        assert_eq!(ret, true);

        let ret = graph.is_directly_connected(1, 3);
        assert_eq!(ret, false);

        let s = graph.get_neighbors(2);
        assert_eq!(s, [3, 4, 5]);

        let ret = graph.is_connected(1, 7);
        assert_eq!(ret, true);

        let ret = graph.is_connected(1, 6);
        assert_eq!(ret, false);
    }

    #[test]
    fn digraph_paths() {
        let mut graph = DiGraph::<i32>::new();
        graph.add_node(1);
        graph.add_node(1);
        graph.add_node(1);
        graph.add_node(1);
        graph.add_node(2);
        graph.add_node(3);
        graph.add_node(4);
        graph.add_node(5);
        graph.add_node(6);
        graph.add_node(7);
        graph.add_node(8);
        graph.add_node(9);
        graph.add_node(10);
        graph.add_node(11);

        graph.add_edge(1, 2);
        graph.add_edge(1, 2);
        graph.add_edge(1, 2);
        graph.add_edge(1, 5);
        graph.add_edge(2, 3);
        graph.add_edge(3, 4);
        graph.add_edge(3, 9);
        graph.add_edge(9, 10);
        graph.add_edge(9, 11);

        graph.add_edge(4, 5);

        graph.add_edge(3, 7);
        graph.add_edge(7, 6);
        graph.add_edge(7, 8);

        graph.add_edge(8, 5);
        graph.add_edge(10, 5);

        let ret = graph.is_connected(1, 5);
        assert_eq!(ret, true);

        let paths = graph.all_simple_paths(1, 5);
        println!("{:?}", paths);
        assert_eq!(
            paths,
            vec![
                vec![1, 2, 3, 4, 5],
                vec![1, 2, 3, 9, 10, 5],
                vec![1, 2, 3, 7, 8, 5],
                vec![1, 5]
            ]
        );

        let mut fd = File::create("test2.dot").expect("error creating file");
        graph.to_dot_file(&mut fd, &String::from("paths_test"))
    }

    #[test]
    fn digraph_generics() {
        let mut graph = DiGraph::<String>::new();
        graph.add_node("a".to_string());
        graph.add_node("b".to_string());
        graph.add_node("c".to_string());
        graph.add_node("d".to_string());
        graph.add_edge("a".to_string(), "b".to_string());
        graph.add_edge("b".to_string(), "c".to_string());
        graph.add_edge("c".to_string(), "d".to_string());
        graph.add_edge("a".to_string(), "d".to_string());

        let paths = graph.all_simple_paths("a".to_string(), "d".to_string());
        println!("{:?}", paths);

        assert_eq!(paths, vec![vec!["a", "b", "c", "d"], vec!["a", "d"]]);
    }

    #[test]
    fn digraph_to_dot() {
        let mut fd = File::create("test1.dot").expect("error creating file");
        let mut graph = DiGraph::<String>::new();
        graph.add_node("a".to_string());
        graph.add_node("b".to_string());
        graph.add_node("c".to_string());
        graph.add_node("d".to_string());
        graph.add_edge("a".to_string(), "b".to_string());
        graph.add_edge("b".to_string(), "c".to_string());
        graph.add_edge("c".to_string(), "d".to_string());
        graph.add_edge("a".to_string(), "d".to_string());
        graph.to_dot_file(&mut fd, &String::from("to_dot_test"));
        let s = graph.to_dot_string(&String::from("to_dot_test"));
        println!("Dot:\n{}", s);
        assert_eq!(s.is_empty(), false);
    }

    #[test]
    fn digraph_from_dot_str() {
        let content =
            String::from("digraph from_dot_str{\na -> b -> d;\nb -> c;\nc -> d;\nd;\n};\n");

        let graph = match digraph_from_dot_string(&content) {
            Ok(v) => v,
            Err(e) => {
                println!("Error {}", e);
                DiGraph::<String>::new()
            }
        };

        assert_eq!(graph.count_nodes(), 4);
        let s = graph.to_dot_string(&String::from("from_dot_str"));
        println!("{}", s);
        //assert_eq!(s,content);
    }
}