Repository navigation
Expand file tree
/
Copy pathmap_graph_utils.rs
More file actions
91 lines (86 loc) · 2.61 KB
/
Copy pathmap_graph_utils.rs
File metadata and controls
91 lines (86 loc) · 2.61 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
84
85
86
87
88
89
90
91
use crate::graph_utils::vec_graph_utils::VecGraph;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs::File;
use std::io::Write;
pub type MapGraph = HashMap<u32, HashSet<u32>>;
#[must_use]
pub fn map_of_vec(vec: &VecGraph) -> MapGraph {
vec.iter()
.enumerate()
.map(|(id, parents)| {
(
id as u32,
parents.iter().map(|&v| v as u32).collect::<HashSet<_>>(),
)
})
.collect::<HashMap<_, _>>()
}
#[must_use]
pub fn filtered_map_of_vec(graph: &VecGraph, kept_vertexes: &HashSet<usize>) -> MapGraph {
graph
.iter()
.enumerate()
.filter(|(id, _)| kept_vertexes.contains(id))
.map(|(id, parents)| {
(
id as u32,
parents
.iter()
.filter(|&v| kept_vertexes.contains(v))
.map(|&v| v as u32)
.collect::<HashSet<_>>(),
)
})
.collect::<HashMap<_, _>>()
}
pub fn remove_vertex(vertex: u32, graph: &mut MapGraph, reversed: &mut MapGraph) -> bool {
if !graph.contains_key(&vertex) {
return false;
}
let parents = graph.remove(&vertex).unwrap();
let children = reversed.remove(&vertex).unwrap();
for parent in parents {
reversed.get_mut(&parent).unwrap().remove(&vertex);
}
for child in children {
graph.get_mut(&child).unwrap().remove(&vertex);
}
true
}
pub fn export_as_csv(
graph: &MapGraph,
name_from_id: Option<&Vec<String>>,
separator: &str,
path: &str,
) {
let sorted_graph = graph
.iter()
.map(|(k, v)| (k, v.iter().collect::<BTreeSet<_>>()))
.collect::<BTreeMap<_, _>>();
let write_item = |id: usize, content: &mut String| {
if let Some(name_from_id) = name_from_id {
assert!(!name_from_id[id].contains(separator));
content.push_str(&name_from_id[id]);
} else {
content.push_str(&id.to_string());
}
};
let mut file = File::create(path).unwrap();
let mut is_first_line = true;
for (&id, parents) in sorted_graph {
let mut content = String::new();
if is_first_line {
is_first_line = false;
} else {
content += "\n";
}
write_item(id as usize, &mut content);
content += separator;
for &parent in parents {
write_item(parent as usize, &mut content);
content += separator;
}
content.pop(); // Removes trailing separator
file.write_all(content.as_bytes()).unwrap();
}
}