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

Add Local Complementation #1366

Merged
merged 8 commits into from
Jan 28, 2025
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
1 change: 1 addition & 0 deletions docs/source/api/pygraph_api_functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ typed API based on the data type.
rustworkx.graph_transitivity
rustworkx.graph_core_number
rustworkx.graph_complement
rustworkx.local_complement
rustworkx.graph_union
rustworkx.graph_tensor_product
rustworkx.graph_token_swapper
Expand Down
18 changes: 18 additions & 0 deletions releasenotes/notes/add-local-complementation-f79b3b05769814cc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
features:
- |
Added a new function, :func:`~rustworkx.local_complement` which
performs the local complementation of a node applied to a graph
For example:

.. jupyter-execute::

import rustworkx

# Example taken from Figure 1 a) in https://arxiv.org/abs/1910.03969
graph = rustworkx.PyGraph(multigraph=False)
graph.extend_from_edge_list(
[(0, 1), (0, 3), (0, 5), (1, 2), (2, 3), (2, 4), (3, 4), (3, 5)]
)

complement_graph = rustworkx.local_complement(graph, 0)
1 change: 1 addition & 0 deletions rustworkx/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ from .rustworkx import chain_decomposition as chain_decomposition
from .rustworkx import digraph_find_cycle as digraph_find_cycle
from .rustworkx import digraph_complement as digraph_complement
from .rustworkx import graph_complement as graph_complement
from .rustworkx import local_complement as local_complement
from .rustworkx import digraph_all_simple_paths as digraph_all_simple_paths
from .rustworkx import graph_all_simple_paths as graph_all_simple_paths
from .rustworkx import digraph_all_pairs_all_simple_paths as digraph_all_pairs_all_simple_paths
Expand Down
5 changes: 5 additions & 0 deletions rustworkx/rustworkx.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ def graph_complement(
graph: PyGraph[_S, _T],
/,
) -> PyGraph[_S, _T | None]: ...
def local_complement(
graph: PyGraph[_S, _T],
node: int,
/,
) -> PyGraph[_S, _T | None]: ...
def digraph_all_simple_paths(
graph: PyDiGraph,
origin: int,
Expand Down
59 changes: 59 additions & 0 deletions src/connectivity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use super::{
};

use hashbrown::{HashMap, HashSet};
use indexmap::IndexSet;
use petgraph::algo;
use petgraph::algo::condensation;
use petgraph::graph::DiGraph;
Expand Down Expand Up @@ -561,6 +562,64 @@ pub fn digraph_complement(py: Python, graph: &digraph::PyDiGraph) -> PyResult<di
Ok(complement_graph)
}

/// Local complementation of a node applied to an undirected graph.
///
/// :param PyGraph graph: The graph to be used.
/// :param int node: A node in the graph.
///
/// :returns: The locally complemented graph.
/// :rtype: PyGraph
///
/// .. note::
///
/// This function assumes that there are no self loops
/// in the provided graph.
/// Returns an error if the :attr:`~rustworkx.PyGraph.multigraph`
/// attribute is set to ``True``.
#[pyfunction]
#[pyo3(text_signature = "(graph, node, /)")]
pub fn local_complement(
py: Python,
graph: &graph::PyGraph,
node: usize,
) -> PyResult<graph::PyGraph> {
if graph.multigraph {
return Err(PyValueError::new_err(
"Local complementation not defined for multigraphs!",
));
}

let mut complement_graph = graph.clone(); // keep same node indices

let node = NodeIndex::new(node);
if !graph.graph.contains_node(node) {
return Err(InvalidNode::new_err(
"The input index for 'node' is not a valid node index",
));
}

// Local complementation
let node_neighbors: IndexSet<NodeIndex> = graph.graph.neighbors(node).collect();
let node_neighbors_vec: Vec<&NodeIndex> = node_neighbors.iter().collect();
for (i, neighbor_i) in node_neighbors_vec.iter().enumerate() {
// Ensure checking pairs of neighbors is only done once
let (_, nodes_tail) = node_neighbors_vec.split_at(i + 1);
for neighbor_j in nodes_tail.iter() {
let res = complement_graph.remove_edge(neighbor_i.index(), neighbor_j.index());
match res {
Ok(_) => (),
Err(_) => {
let _ = complement_graph
.graph
.add_edge(**neighbor_i, **neighbor_j, py.None());
}
}
}
}

Ok(complement_graph)
}

/// Return all simple paths between 2 nodes in a PyGraph object
///
/// A simple path is a path with no repeated nodes.
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ fn rustworkx(py: Python<'_>, m: &Bound<PyModule>) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(digraph_core_number))?;
m.add_wrapped(wrap_pyfunction!(graph_complement))?;
m.add_wrapped(wrap_pyfunction!(digraph_complement))?;
m.add_wrapped(wrap_pyfunction!(local_complement))?;
m.add_wrapped(wrap_pyfunction!(graph_random_layout))?;
m.add_wrapped(wrap_pyfunction!(digraph_random_layout))?;
m.add_wrapped(wrap_pyfunction!(graph_bipartite_layout))?;
Expand Down
80 changes: 80 additions & 0 deletions tests/graph/test_local_complement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# 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.

import unittest

import rustworkx


class TestLocalComplement(unittest.TestCase):
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
def test_multigraph(self):
graph = rustworkx.PyGraph(multigraph=True)
node = graph.add_node("")
with self.assertRaises(ValueError):
rustworkx.local_complement(graph, node)

def test_invalid_node(self):
graph = rustworkx.PyGraph(multigraph=False)
node = graph.add_node("")
with self.assertRaises(rustworkx.InvalidNode):
rustworkx.local_complement(graph, node + 1)

def test_clique(self):
N = 5
graph = rustworkx.generators.complete_graph(N, multigraph=False)

for node in range(0, N):
expected_graph = rustworkx.PyGraph(multigraph=False)
expected_graph.extend_from_edge_list([(i, node) for i in range(0, N) if i != node])

complement_graph = rustworkx.local_complement(graph, node)

self.assertTrue(
rustworkx.is_isomorphic(
expected_graph,
complement_graph,
)
)

def test_empty(self):
N = 5
graph = rustworkx.generators.empty_graph(N, multigraph=False)

expected_graph = rustworkx.generators.empty_graph(N, multigraph=False)

complement_graph = rustworkx.local_complement(graph, 0)
self.assertTrue(
rustworkx.is_isomorphic(
expected_graph,
complement_graph,
)
)

def test_local_complement(self):
# Example took from https://arxiv.org/abs/1910.03969, figure 1
graph = rustworkx.PyGraph(multigraph=False)
graph.extend_from_edge_list(
[(0, 1), (0, 3), (0, 5), (1, 2), (2, 3), (2, 4), (3, 4), (3, 5)]
)

expected_graph = rustworkx.PyGraph(multigraph=False)
expected_graph.extend_from_edge_list(
[(0, 1), (0, 3), (0, 5), (1, 2), (1, 3), (1, 5), (2, 3), (2, 4), (3, 4)]
)

complement_graph = rustworkx.local_complement(graph, 0)
self.assertTrue(
rustworkx.is_isomorphic(
expected_graph,
complement_graph,
)
)
Loading