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 generalized Petersen graphs generator #497

Merged
merged 15 commits into from
Nov 30, 2021
1 change: 1 addition & 0 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ Generators
retworkx.generators.heavy_hex_graph
retworkx.generators.directed_heavy_hex_graph
retworkx.generators.lollipop_graph
retworkx.generators.generalized_petersen_graph

Random Circuit Functions
========================
Expand Down
14 changes: 14 additions & 0 deletions releasenotes/notes/petersen-graph-7ebe5d3b4cc0c946.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
features:
- |
Added a new function, :func:`~retworkx.generators.generalized_petersen_graph` that
adds support for generating generalized Petersen graphs. For example:

.. jupyter-execute::

import retworkx.generators
from retworkx.visualization import mpl_draw

graph = retworkx.generators.generalized_petersen_graph(5, 2)
layout = retworkx.shell_layout(graph, nlist=[[0, 1, 2, 3, 4], [6, 7, 8, 9, 5]])
mpl_draw(graph, pos=layout)
92 changes: 92 additions & 0 deletions src/generators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2213,6 +2213,97 @@ pub fn lollipop_graph(
Ok(graph)
}

/// Generate a generalized Petersen graph :math:`G(n, k)` with :math:`2n`
/// nodes and :math:`3n` edges. See Watkins [1]_ for more details.
///
/// .. note::
///
/// The Petersen graph itself is denoted :math:`G(5, 2)`
///
/// :param int n: number of nodes in the internal star and external regular polygon.
/// :param int k: shift that changes the internal star graph.
/// :param bool multigraph: When set to False the output
/// :class:`~retworkx.PyGraph` object will not be not be a multigraph and
/// won't allow parallel edges to be added. Instead
/// calls which would create a parallel edge will update the existing edge.
///
/// :returns: The generated generalized Petersen graph.
///
/// :rtype: PyGraph
/// :raises IndexError: If either ``n`` or ``k`` are
/// not valid
/// :raises TypeError: If either ``n`` or ``k`` are
/// not non-negative integers
///
/// .. jupyter-execute::
///
/// import retworkx.generators
/// from retworkx.visualization import mpl_draw
///
/// # Petersen Graph is G(5, 2)
/// graph = retworkx.generators.generalized_petersen_graph(5, 2)
/// layout = retworkx.shell_layout(graph, nlist=[[0, 1, 2, 3, 4],[6, 7, 8, 9, 5]])
/// mpl_draw(graph, pos=layout)
///
/// .. jupyter-execute::
///
/// # Möbius–Kantor Graph is G(8, 3)
/// graph = retworkx.generators.generalized_petersen_graph(8, 3)
/// layout = retworkx.shell_layout(
/// graph, nlist=[[0, 1, 2, 3, 4, 5, 6, 7], [10, 11, 12, 13, 14, 15, 8, 9]]
/// )
/// mpl_draw(graph, pos=layout)
///
/// .. [1] Watkins, Mark E.
/// "A theorem on tait colorings with an application to the generalized Petersen graphs"
/// Journal of Combinatorial Theory 6 (2), 152–164 (1969).
/// https://doi.org/10.1016/S0021-9800(69)80116-X
///
#[pyfunction(multigraph = true)]
#[pyo3(text_signature = "(n, k, /, multigraph=True)")]
pub fn generalized_petersen_graph(
py: Python,
n: usize,
k: usize,
multigraph: bool,
) -> PyResult<graph::PyGraph> {
if n < 3 {
return Err(PyIndexError::new_err("n must be at least 3"));
georgios-ts marked this conversation as resolved.
Show resolved Hide resolved
}

if k == 0 || 2 * k >= n {
return Err(PyIndexError::new_err(
"k is invalid: it must be positive and less than n/2",
));
}

let mut graph = StablePyGraph::<Undirected>::with_capacity(2 * n, 3 * n);

let star_nodes: Vec<NodeIndex> =
(0..n).map(|_| graph.add_node(py.None())).collect();

let polygon_nodes: Vec<NodeIndex> =
(0..n).map(|_| graph.add_node(py.None())).collect();

for i in 0..n {
graph.add_edge(star_nodes[i], star_nodes[(i + k) % n], py.None());
}

for i in 0..n {
graph.add_edge(polygon_nodes[i], polygon_nodes[(i + 1) % n], py.None());
}

for i in 0..n {
graph.add_edge(polygon_nodes[i], star_nodes[i], py.None());
}

Ok(graph::PyGraph {
graph,
node_removed: false,
multigraph,
})
}

#[pymodule]
pub fn generators(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(cycle_graph))?;
Expand All @@ -2234,5 +2325,6 @@ pub fn generators(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(hexagonal_lattice_graph))?;
m.add_wrapped(wrap_pyfunction!(directed_hexagonal_lattice_graph))?;
m.add_wrapped(wrap_pyfunction!(lollipop_graph))?;
m.add_wrapped(wrap_pyfunction!(generalized_petersen_graph))?;
Ok(())
}
56 changes: 56 additions & 0 deletions tests/generators/test_petersen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# 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 retworkx


class TestPetersenGraph(unittest.TestCase):
def test_petersen_graph_count(self):
n = 99
k = 23
graph = retworkx.generators.generalized_petersen_graph(n, k)
self.assertEqual(len(graph), 2 * n)
self.assertEqual(len(graph.edges()), 3 * n)

def test_petersen_graph_edge(self):
graph = retworkx.generators.generalized_petersen_graph(5, 2)
edge_list = graph.edge_list()
expected_edge_list = [
(0, 2),
(1, 3),
(2, 4),
(3, 0),
(4, 1),
(5, 6),
(6, 7),
(7, 8),
(8, 9),
(9, 5),
(5, 0),
(6, 1),
(7, 2),
(8, 3),
(9, 4),
]
self.assertEqual(edge_list, expected_edge_list)

def test_petersen_invalid_n_k(self):
with self.assertRaises(IndexError):
retworkx.generators.generalized_petersen_graph(2, 1)

with self.assertRaises(IndexError):
retworkx.generators.generalized_petersen_graph(5, 0)

with self.assertRaises(IndexError):
retworkx.generators.generalized_petersen_graph(5, 4)
28 changes: 28 additions & 0 deletions tests/graph/test_isomorphic.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,34 @@ def test_graph_isomorphic_self_loop(self):
graph.add_edges_from_no_data([(0, 0), (0, 1)])
self.assertTrue(retworkx.is_isomorphic(graph, graph))

def test_graph_isomorphic_petersen(self):
"""Based on 'The isomorphism classes of the generalized Petersen graphs'
by Steimle and Staton: https://doi.org/10.1016/j.disc.2007.12.074

For 2 <= k <= n- 2 with gcd(n, k) = 1,
G(n, k) is isomorphic to G(n, l) if and only if:
k ≡ -l (mod n) or kl ≡ ±1 (mod n)
"""
n = 23
upper_bound_k = (n - 1) // 2
for k in range(1, upper_bound_k + 1):
for t in range(k, upper_bound_k + 1):
with self.subTest(k=k, t=t):
self.assertEqual(
retworkx.is_isomorphic(
retworkx.generators.generalized_petersen_graph(
n, k
),
retworkx.generators.generalized_petersen_graph(
n, t
),
),
(k == t)
or (k == n - t)
or (k * t % n == 1)
or (k * t % n == n - 1),
)

def test_isomorphic_parallel_edges(self):
first = retworkx.PyGraph()
first.extend_from_edge_list([(0, 1), (0, 1), (1, 2), (2, 3)])
Expand Down