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 5 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
18 changes: 18 additions & 0 deletions rustworkx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,24 @@ def complement(graph):
raise TypeError("Invalid Input Type %s for graph" % type(graph))


@_rustworkx_dispatch
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
def local_complement(graph, node):
"""Local complementation of a node applied to a graph.

:param graph: The graph to be used, can be either a
:class:`~rustworkx.PyGraph` or :class:`~rustworkx.PyDiGraph`.
:param int node: A node index.

:returns: The locally complemented graph.
:rtype: :class:`~rustworkx.PyGraph` or :class:`~rustworkx.PyDiGraph`

.. note::
Parallel edges and self-loops are never created,
even if the ``multigraph`` is set to ``True``
"""
raise TypeError("Invalid Input Type %s for graph" % type(graph))


@_rustworkx_dispatch
def random_layout(graph, center=None, seed=None):
"""Generate a random layout
Expand Down
80 changes: 80 additions & 0 deletions src/connectivity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,86 @@ 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 graph_local_complement(
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
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: HashSet<NodeIndex> = graph.graph.neighbors(node).collect();
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
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_head, nodes_tail) = node_neighbors_vec.split_at(i + 1);
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
for neighbor_j in nodes_tail.iter() {
if complement_graph.has_edge(neighbor_i.index(), neighbor_j.index()) {
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
let _ = complement_graph.remove_edge(neighbor_i.index(), neighbor_j.index());
} else {
complement_graph
.graph
.add_edge(**neighbor_i, **neighbor_j, py.None());
}
}
}

Ok(complement_graph)
}

/// Local complementation is not defined on a directed graph.
/// This functions just returns an error.
///
/// :param PyDiGraph graph: The graph to be used.
/// :param int node: A node in the graph.
///
/// :returns: The locally complemented graph.
/// :rtype: PyDiGraph
///
/// .. note::
///
/// This function just returns an error.
#[pyfunction]
#[pyo3(text_signature = "(graph, node, /)")]
pub fn digraph_local_complement(
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
_py: Python,
_graph: &digraph::PyDiGraph,
_node: usize,
) -> PyResult<digraph::PyDiGraph> {
Err(PyValueError::new_err(
"Local complementation not defined for directed graphs!",
))
}

/// Return all simple paths between 2 nodes in a PyGraph object
///
/// A simple path is a path with no repeated nodes.
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,8 @@ 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!(graph_local_complement))?;
m.add_wrapped(wrap_pyfunction!(digraph_local_complement))?;
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
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
71 changes: 71 additions & 0 deletions tests/graph/test_local_complement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# 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_clique(self):
N = 5
graph = rustworkx.PyGraph(multigraph=False)
graph.extend_from_edge_list([(i, j) for i in range(N) for j in range(N) if i < j])
S-Erik marked this conversation as resolved.
Show resolved Hide resolved

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.PyGraph(multigraph=False)
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
graph.add_nodes_from([i for i in range(N)])

expected_graph = rustworkx.PyGraph(multigraph=False)
S-Erik marked this conversation as resolved.
Show resolved Hide resolved
expected_graph.add_nodes_from([i for i in range(N)])

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