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
use super::Graph;
use crate::{Edge, Error, ErrorKind, GraphSpecs};
use std::collections::HashMap;
use std::fmt::Display;
use std::hash::Hash;
use std::sync::Arc;
pub enum ToUndirectedCollapseEdgeWeightsStrategy {
Max,
Min,
Sum,
}
impl<T, A> Graph<T, A>
where
T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display,
A: Clone,
{
/**
Reverses the edges in a directed graph.
# Examples
```
use graphrs::{Edge, Graph, GraphSpecs};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
Edge::new("n1", "n3"),
Edge::new("n2", "n3"),
]);
let graph = graph.reverse().unwrap();
assert!(graph.get_edge("n3", "n1").is_ok());
```
*/
pub fn reverse(&self) -> Result<Graph<T, A>, Error> {
if !self.specs.directed {
return Err(Error {
kind: ErrorKind::WrongMethod,
message: "The `reverse` method is not applicable to undirected graphs.".to_string(),
});
}
let new_nodes = self.get_all_nodes().into_iter().cloned().collect();
let new_edges = self
.get_all_edges()
.into_iter()
.map(|edge| edge.clone().reversed().into())
.collect();
Graph::new_from_nodes_and_edges(new_nodes, new_edges, self.specs.clone())
}
/**
Return a new graph with all the edge weights set to the specified value.
# Arguments
* `weight`: the value to set all the edge weights to
# Examples
```
use graphrs::{Edge, Graph, GraphSpecs};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs::directed_create_missing());
let result = graph.add_edges(vec![
Edge::new("n1", "n3"),
Edge::new("n2", "n3"),
]);
let new_graph = graph.set_all_edge_weights(2.0);
assert_eq!(new_graph.get_edge("n1", "n3").unwrap().weight, 2.0);
```
*/
pub fn set_all_edge_weights(&self, weight: f64) -> Graph<T, A> {
let new_nodes = self.get_all_nodes().into_iter().cloned().collect();
let new_edges = self
.get_all_edges()
.into_iter()
.map(|edge| {
let mut new_edge: Arc<Edge<T, A>> = edge.clone().into();
let new_edge_mut = Arc::make_mut(&mut new_edge);
new_edge_mut.weight = weight;
new_edge
})
.collect();
Graph::new_from_nodes_and_edges(new_nodes, new_edges, self.specs.clone()).unwrap()
}
/**
Convert a multi-edge graph to a single-edge graph.
Edge weights are summed.
Edge attributes are lost.
# Examples
```
use graphrs::{Edge, Graph, GraphSpecs, MissingNodeStrategy, Node};
let mut graph: Graph<&str, ()> = Graph::new(GraphSpecs {
missing_node_strategy: MissingNodeStrategy::Create,
multi_edges: true,
..GraphSpecs::directed()
});
graph.add_edges(vec![
Edge::with_weight("n1", "n2", 1.1),
Edge::with_weight("n1", "n2", 2.2),
Edge::with_weight("n1", "n2", 3.3),
Edge::with_weight("n1", "n3", 4.4),
]);
let new_graph = graph.to_single_edges().unwrap();
assert!(!new_graph.specs.multi_edges);
assert_eq!(new_graph.get_all_edges().len(), 2);
assert_eq!(new_graph.get_edge("n1", "n2").unwrap().weight, 6.6);
assert_eq!(new_graph.get_edge("n1", "n3").unwrap().weight, 4.4);
```
*/
pub fn to_single_edges(&self) -> Result<Graph<T, A>, Error> {
if !self.specs.multi_edges {
return Err(Error {
kind: ErrorKind::WrongMethod,
message: "The `to_single_edges` method is not applicable to graph where `specs.multi_edges` is `false`.".to_string(),
});
}
let new_nodes = self.nodes_vec.clone();
let new_edges = self.edges.iter().map(collapse_edges).collect();
Graph::new_from_nodes_and_edges(
new_nodes,
new_edges,
GraphSpecs {
multi_edges: false,
..self.specs.clone()
},
)
}
/**
Converts a directed graph to an undirected graph.
# Examples
```
use graphrs::{generators};
let graph = generators::random::fast_gnp_random_graph(25, 0.25, true, Some(1)).unwrap();
let new_graph = graph.to_undirected(None).unwrap();
assert_eq!(new_graph.number_of_nodes(), 25);
assert_eq!(new_graph.number_of_edges(), 132);
```
*/
pub fn to_undirected(
&self,
collapse_edge_weights_strategy: Option<ToUndirectedCollapseEdgeWeightsStrategy>,
) -> Result<Graph<T, A>, Error>
where
T: Hash + Eq + Clone + Ord,
A: Clone,
{
if !self.specs.directed {
return Err(Error {
kind: ErrorKind::WrongMethod,
message: "The `to_undirected` method is not applicable to undirected graphs."
.to_string(),
});
}
let new_nodes = self.get_all_nodes().into_iter().cloned().collect();
let default_weight = match collapse_edge_weights_strategy {
Some(ToUndirectedCollapseEdgeWeightsStrategy::Max) => f64::MIN,
Some(ToUndirectedCollapseEdgeWeightsStrategy::Min) => f64::MAX,
Some(ToUndirectedCollapseEdgeWeightsStrategy::Sum) => 0.0,
None => f64::NAN,
};
let mut edge_map: HashMap<T, HashMap<T, f64>> = HashMap::new();
for edge in self.get_all_edges() {
let ordered = edge.ordered();
let existing_weight = edge_map
.get(&ordered.u)
.and_then(|m| m.get(&ordered.v))
.unwrap_or(&default_weight);
let new_weight = match collapse_edge_weights_strategy {
Some(ToUndirectedCollapseEdgeWeightsStrategy::Max) => {
edge.weight.max(*existing_weight)
}
Some(ToUndirectedCollapseEdgeWeightsStrategy::Min) => {
edge.weight.min(*existing_weight)
}
Some(ToUndirectedCollapseEdgeWeightsStrategy::Sum) => edge.weight + existing_weight,
None => f64::NAN,
};
edge_map
.entry(ordered.u)
.or_insert_with(HashMap::new)
.insert(ordered.v, new_weight);
}
let new_edges = edge_map
.into_iter()
.flat_map(|(u, m)| {
m.into_iter()
.map(move |(v, w)| Edge::with_weight(u.clone(), v, w))
})
.collect();
Graph::new_from_nodes_and_edges(
new_nodes,
new_edges,
GraphSpecs {
directed: false,
..self.specs
},
)
}
}
fn collapse_edges<T, A>(tuple: (&(T, T), &Vec<Arc<Edge<T, A>>>)) -> Arc<Edge<T, A>>
where
T: Eq + Clone + PartialOrd + Ord + Hash + Send + Sync + Display,
A: Clone,
{
let (k, v) = tuple;
let sum_weight = v.iter().map(|e| e.weight).sum();
Edge::with_weight(k.0.clone(), k.1.clone(), sum_weight)
}