Skip to content

Commit

Permalink
Add from_graph function for graphmap
Browse files Browse the repository at this point in the history
  • Loading branch information
Indeximal committed Jun 8, 2022
1 parent 3e1a0c4 commit b58d7ca
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/graphmap.rs
Expand Up @@ -477,6 +477,37 @@ where
}
gr
}

/// Creates a `GraphMap` that corresponds to the given `Graph`.
///
/// **Warning**: Nodes with the same weight are merged and only the last parallel edge
/// is kept. Node and edge indices of the `Graph` are lost. Only use this function
/// if the node weights are distinct and there are no parallel edges.
///
/// Computes in **O(|V| + |E|)** time (average).
pub fn from_graph<Ix>(graph: Graph<N, E, Ty, Ix>) -> Self
where
Ix: crate::graph::IndexType,
E: Clone,
{
let mut new_graph: GraphMap<N, E, Ty> =
GraphMap::with_capacity(graph.node_count(), graph.edge_count());

for node in graph.raw_nodes() {
new_graph.add_node(node.weight);
}

for edge in graph.edge_indices() {
let (a, b) = graph.edge_endpoints(edge).unwrap();
new_graph.add_edge(
*graph.node_weight(a).unwrap(),
*graph.node_weight(b).unwrap(),
graph.edge_weight(edge).unwrap().clone(),
);
}

new_graph
}
}

/// Create a new `GraphMap` from an iterable of edges.
Expand Down
20 changes: 20 additions & 0 deletions tests/graphmap.rs
Expand Up @@ -325,6 +325,26 @@ fn test_into_graph() {
}
}

#[test]
fn test_from_graph() {
let mut gr: Graph<u32, u32, Directed> = Graph::new();
let node_a = gr.add_node(12);
let node_b = gr.add_node(13);
let node_c = gr.add_node(14);
gr.add_edge(node_a, node_b, 1000);
gr.add_edge(node_b, node_c, 999);
gr.add_edge(node_c, node_a, 1111);
gr.add_node(42);
let gr = gr;

let graph: GraphMap<u32, u32, Directed> = GraphMap::from_graph(gr.clone());
println!("{}", Dot::new(&gr));
println!("{}", Dot::new(&graph));

assert!(petgraph::algo::is_isomorphic(&gr, &graph));
assert_eq!(graph[(12, 13)], 1000);
}

#[test]
fn test_all_edges_mut() {
// graph with edge weights equal to in+out
Expand Down

0 comments on commit b58d7ca

Please sign in to comment.