Skip to content
Merged
Changes from 13 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
87 changes: 87 additions & 0 deletions src/sage/graphs/generic_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -15746,6 +15746,93 @@ def distance_all_pairs(self, by_weight=False, algorithm=None,
weight_function=weight_function,
check_weight=check_weight)[0]

def power(self, k):
r"""
Compute the kth power graph of an unweighted graph based on shortest
distances between nodes using BFS.

INPUT:

- ``k`` -- integer; the maximum path length for considering edges in the power graph.

OUTPUT:

- The kth power graph based on shortest distances between nodes.

EXAMPLES:

Testing on undirected graphs::

sage: G = Graph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = 2
sage: PG = G.power(k)
sage: PG.edges(sort=True, labels=False)
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (2, 5), (3, 4), (4, 5)]

Testing on directed graphs::

sage: G = DiGraph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = 3
sage: PG = G.power(k)
sage: PG.edges(sort=True, labels=False)
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (1, 5), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (3, 0), (3, 1), (3, 2), (4, 5)]

TESTS:

Testing when k < 0::

sage: G = Graph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = -2
sage: PG = G.power(k)
Traceback (most recent call last)
...
ValueError: distance must be a non-negative integer, not -2

Testing when k = 0::

sage: G = Graph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = 0
sage: PG = G.power(k)
sage: PG.edges(sort=True, labels=False)
[]

Testing when k = 1::

sage: G = Graph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = 1
sage: PG = G.power(k)
sage: PG.edges(sort=True, labels=False)
[(0, 1), (0, 3), (1, 2), (2, 3), (2, 4), (4, 5)]

Testing when k = Infinity::

sage: G = Graph([(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = Infinity
sage: PG = G.power(k)
Traceback (most recent call last)
...
ValueError: distance must be a non-negative integer, not +Infinity

Testing on graph with multiple edges::

sage: G = DiGraph([(0, 1), (0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5)])
sage: k = 3
sage: PG = G.power(k)
sage: PG.edges(sort=True, labels=False)
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (1, 5), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (3, 0), (3, 1), (3, 2), (4, 5)]
"""
from sage.graphs.digraph import DiGraph
from sage.graphs.graph import Graph

power_of_graph = DiGraph() if self.is_directed() else Graph()

for u in self:
for v in self.breadth_first_search(u, distance=k):
if u != v:
power_of_graph.add_edge(u, v)

return power_of_graph

def girth(self, certificate=False):
"""
Return the girth of the graph.
Expand Down