Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move cycle_basis to rustworkx-core #792

Merged
merged 5 commits into from
Jan 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
features:
- |
Two new functions, ``find_cycle`` and ``cycle_basis``, have been added
to the ``rustworkx-core`` crate in the ``connectivity`` module. These
functions can be used to find a cycle in a petgraph graph or to find
the cycle basis of a graph.
191 changes: 191 additions & 0 deletions rustworkx-core/src/connectivity/cycle_basis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

use hashbrown::{HashMap, HashSet};
use petgraph::visit::{IntoNeighbors, IntoNodeIdentifiers, NodeCount};
use std::hash::Hash;

/// Return a list of cycles which form a basis for cycles of a given graph.
///
/// A basis for cycles of a graph is a minimal collection of
/// cycles such that any cycle in the graph can be written
/// as a sum of cycles in the basis. Here summation of cycles
/// is defined as the exclusive-or of the edges.
///
/// This is adapted from
/// Paton, K. An algorithm for finding a fundamental set of
/// cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518.
///
/// The function implicitly assumes that there are no parallel edges.
/// It may produce incorrect/unexpected results if the input graph has
/// parallel edges.
///
///
/// Arguments:
///
/// * `graph` - The graph in which to find the basis.
/// * `root` - Optional node index for starting the basis search. If not
/// specified, an arbitrary node is chosen.
///
/// # Example
/// ```rust
/// use petgraph::prelude::*;
/// use rustworkx_core::connectivity::cycle_basis;
///
/// let edge_list = [(0, 1), (0, 3), (0, 5), (1, 2), (2, 3), (3, 4), (4, 5)];
/// let graph = UnGraph::<i32, i32>::from_edges(&edge_list);
/// let mut res: Vec<Vec<NodeIndex>> = cycle_basis(&graph, Some(NodeIndex::new(0)));
/// ```
pub fn cycle_basis<G>(graph: G, root: Option<G::NodeId>) -> Vec<Vec<G::NodeId>>
where
G: NodeCount,
G: IntoNeighbors,
G: IntoNodeIdentifiers,
G::NodeId: Eq + Hash,
{
let mut root_node = root;
let mut graph_nodes: HashSet<G::NodeId> = graph.node_identifiers().collect();
let mut cycles: Vec<Vec<G::NodeId>> = Vec::new();
while !graph_nodes.is_empty() {
let temp_value: G::NodeId;
// If root_node is not set get an arbitrary node from the set of graph
// nodes we've not "examined"
let root_index = match root_node {
Some(root_node) => root_node,
None => {
temp_value = *graph_nodes.iter().next().unwrap();
graph_nodes.remove(&temp_value);
temp_value
}
};
// Stack (ie "pushdown list") of vertices already in the spanning tree
let mut stack: Vec<G::NodeId> = vec![root_index];
// Map of node index to predecessor node index
let mut pred: HashMap<G::NodeId, G::NodeId> = HashMap::new();
pred.insert(root_index, root_index);
// Set of examined nodes during this iteration
let mut used: HashMap<G::NodeId, HashSet<G::NodeId>> = HashMap::new();
used.insert(root_index, HashSet::new());
// Walk the spanning tree
while !stack.is_empty() {
// Use the last element added so that cycles are easier to find
let z = stack.pop().unwrap();
for neighbor in graph.neighbors(z) {
// A new node was encountered:
if !used.contains_key(&neighbor) {
pred.insert(neighbor, z);
stack.push(neighbor);
let mut temp_set: HashSet<G::NodeId> = HashSet::new();
temp_set.insert(z);
used.insert(neighbor, temp_set);
// A self loop:
} else if z == neighbor {
let cycle: Vec<G::NodeId> = vec![z];
cycles.push(cycle);
// A cycle was found:
} else if !used.get(&z).unwrap().contains(&neighbor) {
let pn = used.get(&neighbor).unwrap();
let mut cycle: Vec<G::NodeId> = vec![neighbor, z];
let mut p = pred.get(&z).unwrap();
while !pn.contains(p) {
cycle.push(*p);
p = pred.get(p).unwrap();
}
cycle.push(*p);
cycles.push(cycle);
let neighbor_set = used.get_mut(&neighbor).unwrap();
neighbor_set.insert(z);
}
}
}
let mut temp_hashset: HashSet<G::NodeId> = HashSet::new();
for key in pred.keys() {
temp_hashset.insert(*key);
}
graph_nodes = graph_nodes.difference(&temp_hashset).copied().collect();
root_node = None;
}
cycles
}

#[cfg(test)]
mod tests {
use crate::connectivity::cycle_basis;
use petgraph::prelude::*;

fn sorted_cycle(cycles: Vec<Vec<NodeIndex>>) -> Vec<Vec<usize>> {
let mut sorted_cycles: Vec<Vec<usize>> = vec![];
for cycle in cycles {
let mut cycle: Vec<usize> = cycle.iter().map(|x| x.index()).collect();
cycle.sort();
sorted_cycles.push(cycle);
}
sorted_cycles.sort();
sorted_cycles
}

#[test]
fn test_cycle_basis_source() {
let edge_list = vec![
(0, 1),
(0, 3),
(0, 5),
(0, 8),
(1, 2),
(1, 6),
(2, 3),
(3, 4),
(4, 5),
(6, 7),
(7, 8),
(8, 9),
];
let graph = UnGraph::<i32, i32>::from_edges(&edge_list);
let expected = vec![vec![0, 1, 2, 3], vec![0, 1, 6, 7, 8], vec![0, 3, 4, 5]];
let res_0 = cycle_basis(&graph, Some(NodeIndex::new(0)));
assert_eq!(sorted_cycle(res_0), expected);
let res_1 = cycle_basis(&graph, Some(NodeIndex::new(1)));
assert_eq!(sorted_cycle(res_1), expected);
let res_9 = cycle_basis(&graph, Some(NodeIndex::new(9)));
assert_eq!(sorted_cycle(res_9), expected);
}

#[test]
fn test_self_loop() {
let edge_list = vec![
(0, 1),
(0, 3),
(0, 5),
(0, 8),
(1, 2),
(1, 6),
(2, 3),
(3, 4),
(4, 5),
(6, 7),
(7, 8),
(8, 9),
];
let mut graph = UnGraph::<i32, i32>::from_edges(&edge_list);
graph.add_edge(NodeIndex::new(1), NodeIndex::new(1), 0);
let res_0 = cycle_basis(&graph, Some(NodeIndex::new(0)));
assert_eq!(
sorted_cycle(res_0),
vec![
vec![0, 1, 2, 3],
vec![0, 1, 6, 7, 8],
vec![0, 3, 4, 5],
vec![1]
]
);
}
}
2 changes: 2 additions & 0 deletions rustworkx-core/src/connectivity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod all_simple_paths;
mod biconnected;
mod chain;
mod conn_components;
mod cycle_basis;
mod find_cycle;
mod min_cut;

Expand All @@ -25,5 +26,6 @@ pub use chain::chain_decomposition;
pub use conn_components::bfs_undirected;
pub use conn_components::connected_components;
pub use conn_components::number_connected_components;
pub use cycle_basis::cycle_basis;
pub use find_cycle::find_cycle;
pub use min_cut::stoer_wagner_min_cut;
67 changes: 4 additions & 63 deletions src/connectivity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,69 +65,10 @@ use rustworkx_core::connectivity;
#[pyfunction]
#[pyo3(text_signature = "(graph, /, root=None)")]
pub fn cycle_basis(graph: &graph::PyGraph, root: Option<usize>) -> Vec<Vec<usize>> {
let mut root_node = root;
let mut graph_nodes: HashSet<NodeIndex> = graph.graph.node_indices().collect();
let mut cycles: Vec<Vec<usize>> = Vec::new();
while !graph_nodes.is_empty() {
let temp_value: NodeIndex;
// If root_node is not set get an arbitrary node from the set of graph
// nodes we've not "examined"
let root_index = match root_node {
Some(root_value) => NodeIndex::new(root_value),
None => {
temp_value = *graph_nodes.iter().next().unwrap();
graph_nodes.remove(&temp_value);
temp_value
}
};
// Stack (ie "pushdown list") of vertices already in the spanning tree
let mut stack: Vec<NodeIndex> = vec![root_index];
// Map of node index to predecessor node index
let mut pred: HashMap<NodeIndex, NodeIndex> = HashMap::new();
pred.insert(root_index, root_index);
// Set of examined nodes during this iteration
let mut used: HashMap<NodeIndex, HashSet<NodeIndex>> = HashMap::new();
used.insert(root_index, HashSet::new());
// Walk the spanning tree
while !stack.is_empty() {
// Use the last element added so that cycles are easier to find
let z = stack.pop().unwrap();
for neighbor in graph.graph.neighbors(z) {
// A new node was encountered:
if !used.contains_key(&neighbor) {
pred.insert(neighbor, z);
stack.push(neighbor);
let mut temp_set: HashSet<NodeIndex> = HashSet::new();
temp_set.insert(z);
used.insert(neighbor, temp_set);
// A self loop:
} else if z == neighbor {
let cycle: Vec<usize> = vec![z.index()];
cycles.push(cycle);
// A cycle was found:
} else if !used.get(&z).unwrap().contains(&neighbor) {
let pn = used.get(&neighbor).unwrap();
let mut cycle: Vec<NodeIndex> = vec![neighbor, z];
let mut p = pred.get(&z).unwrap();
while !pn.contains(p) {
cycle.push(*p);
p = pred.get(p).unwrap();
}
cycle.push(*p);
cycles.push(cycle.iter().map(|x| x.index()).collect());
let neighbor_set = used.get_mut(&neighbor).unwrap();
neighbor_set.insert(z);
}
}
}
let mut temp_hashset: HashSet<NodeIndex> = HashSet::new();
for key in pred.keys() {
temp_hashset.insert(*key);
}
graph_nodes = graph_nodes.difference(&temp_hashset).copied().collect();
root_node = None;
}
cycles
connectivity::cycle_basis(&graph.graph, root.map(NodeIndex::new))
.into_iter()
.map(|res_map| res_map.into_iter().map(|x| x.index()).collect())
.collect()
}

/// Find all simple cycles of a :class:`~.PyDiGraph`
Expand Down