use petgraph::data::{Build, Create};
use petgraph::visit::{Data, NodeIndexable};
use super::utils::get_num_nodes;
use super::InvalidInputError;
pub fn path_graph<G, T, F, H, M>(
num_nodes: Option<usize>,
weights: Option<Vec<T>>,
mut default_node_weight: F,
mut default_edge_weight: H,
bidirectional: bool,
) -> Result<G, InvalidInputError>
where
G: Build + Create + Data<NodeWeight = T, EdgeWeight = M> + NodeIndexable,
F: FnMut() -> T,
H: FnMut() -> M,
{
if weights.is_none() && num_nodes.is_none() {
return Err(InvalidInputError {});
}
let node_len = get_num_nodes(&num_nodes, &weights);
let num_edges = if bidirectional {
2 * node_len
} else {
node_len
};
let mut graph = G::with_capacity(node_len, num_edges);
if node_len == 0 {
return Ok(graph);
}
match weights {
Some(weights) => {
for weight in weights {
graph.add_node(weight);
}
}
None => {
for _ in 0..node_len {
graph.add_node(default_node_weight());
}
}
};
for a in 0..node_len - 1 {
let node_a = graph.from_index(a);
let node_b = graph.from_index(a + 1);
graph.add_edge(node_a, node_b, default_edge_weight());
if bidirectional {
graph.add_edge(node_b, node_a, default_edge_weight());
}
}
Ok(graph)
}
#[cfg(test)]
mod tests {
use crate::generators::path_graph;
use crate::generators::InvalidInputError;
use crate::petgraph;
use crate::petgraph::visit::EdgeRef;
#[test]
fn test_with_weights() {
let g: petgraph::graph::UnGraph<usize, ()> =
path_graph(None, Some(vec![0, 1, 2, 3]), || 4, || (), false).unwrap();
assert_eq!(
vec![(0, 1), (1, 2), (2, 3)],
g.edge_references()
.map(|edge| (edge.source().index(), edge.target().index()))
.collect::<Vec<(usize, usize)>>(),
);
assert_eq!(
vec![0, 1, 2, 3],
g.node_weights().copied().collect::<Vec<usize>>(),
);
}
#[test]
fn test_bidirectional() {
let g: petgraph::graph::DiGraph<(), ()> =
path_graph(Some(4), None, || (), || (), true).unwrap();
assert_eq!(
vec![(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2),],
g.edge_references()
.map(|edge| (edge.source().index(), edge.target().index()))
.collect::<Vec<(usize, usize)>>(),
);
}
#[test]
fn test_error() {
match path_graph::<petgraph::graph::DiGraph<(), ()>, (), _, _, ()>(
None,
None,
|| (),
|| (),
false,
) {
Ok(_) => panic!("Returned a non-error"),
Err(e) => assert_eq!(e, InvalidInputError),
};
}
}