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

Implementing iterative removal of non_terminal_leaves in Steiner Tree approximation #7422

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 12 additions & 3 deletions networkx/algorithms/approximation/steinertree.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,18 @@ def _kou_steiner_tree(G, terminal_nodes, weight):

def _remove_nonterminal_leaves(G, terminals):
terminals_set = set(terminals)
for n in list(G.nodes):
if n not in terminals_set and G.degree(n) == 1:
G.remove_node(n)
degree_one_nodes = {n for n in G if G.degree(n) == 1}
nonterminal_leaves = degree_one_nodes - terminals_set
while nonterminal_leaves:
possible_nonterminal_leaves = set()
for n in nonterminal_leaves:
possible_nonterminal_leaves = possible_nonterminal_leaves | set(
G.neighbors(n)
)
G.remove_nodes_from(nonterminal_leaves)
nonterminal_leaves = {
leaf for leaf in possible_nonterminal_leaves if G.degree(leaf) == 1
} - terminals_set


ALGORITHMS = {
Expand Down
11 changes: 11 additions & 0 deletions networkx/algorithms/approximation/tests/test_steinertree.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,17 @@ def test_multigraph_steiner_tree(self):
S = steiner_tree(G, terminal_nodes, method=method)
assert edges_equal(S.edges(data=True, keys=True), expected_edges)

def test_remove_nonterminal_leaves(self):
from networkx.algorithms.approximation.steinertree import (
_remove_nonterminal_leaves,
)

G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 5)], weight=1)
_remove_nonterminal_leaves(G, [2, 3])

assert list(G.nodes) == [2, 3] # only the terminal nodes are left
OrionSehn marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.parametrize("method", ("kou", "mehlhorn"))
def test_steiner_tree_weight_attribute(method):
Expand Down