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

Fix random_spanning_tree() for single node and empty graphs #7211

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 9 additions & 4 deletions networkx/algorithms/tree/mst.py
Original file line number Diff line number Diff line change
Expand Up @@ -897,14 +897,15 @@ def spanning_tree_total_weight(G, weight):
# itself.
if G.number_of_edges() == 1:
return G.edges(data=weight).__iter__().__next__()[2]
# 2. There are more than two edges in the graph. Then, we can find the
# 2. There are no edges or two or more edges in the graph. Then, we find the
# total weight of the spanning trees using the formula in the
# reference paper: take the weight of that edge and multiple it by
# the number of spanning trees which have to include that edge. This
# reference paper: take the weight of each edge and multiply it by
# the number of spanning trees which include that edge. This
# can be accomplished by contracting the edge and finding the
# multiplicative total spanning tree weight if the weight of each edge
# is assumed to be 1, which is conveniently built into networkx already,
# by calling total_spanning_tree_weight with weight=None
# by calling total_spanning_tree_weight with weight=None.
# Note that with no edges the returned value is just zero.
else:
total = 0
for u, v, w in G.edges(data=weight):
Expand All @@ -913,6 +914,10 @@ def spanning_tree_total_weight(G, weight):
)
return total

if G.number_of_nodes() < 2:
# no edges in the spanning tree
return nx.empty_graph(G.nodes)

U = set()
st_cached_value = 0
V = set(G.edges())
Expand Down
24 changes: 24 additions & 0 deletions networkx/algorithms/tree/tests/test_mst.py
Original file line number Diff line number Diff line change
Expand Up @@ -706,3 +706,27 @@ def test_random_spanning_tree_additive_large():
# Assert that p is greater than the significance level so that we do not
# reject the null hypothesis
assert not p < 0.05


def test_random_spanning_tree_empty_graph():
G = nx.Graph()
rst = nx.tree.random_spanning_tree(G)
assert len(rst.nodes) == 0
assert len(rst.edges) == 0


def test_random_spanning_tree_single_node_graph():
G = nx.Graph()
G.add_node(0)
rst = nx.tree.random_spanning_tree(G)
assert len(rst.nodes) == 1
assert len(rst.edges) == 0


def test_random_spanning_tree_single_node_loop():
G = nx.Graph()
G.add_node(0)
G.add_edge(0, 0)
rst = nx.tree.random_spanning_tree(G)
assert len(rst.nodes) == 1
assert len(rst.edges) == 0