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 custom weight attribute for Mehlhorn #6681

Merged
merged 5 commits into from
Mar 10, 2024
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
2 changes: 1 addition & 1 deletion networkx/algorithms/approximation/steinertree.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _mehlhorn_steiner_tree(G, terminal_nodes, weight):
if not G_1_prime.has_edge(su, sv):
G_1_prime.add_edge(su, sv, weight=weight_here)
else:
new_weight = min(weight_here, G_1_prime[su][sv][weight])
new_weight = min(weight_here, G_1_prime[su][sv]["weight"])
G_1_prime.add_edge(su, sv, weight=new_weight)

G_2 = nx.minimum_spanning_edges(G_1_prime, data=True)
Expand Down
19 changes: 19 additions & 0 deletions networkx/algorithms/approximation/tests/test_steinertree.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,22 @@ def test_multigraph_steiner_tree(self):
for method in self.methods:
S = steiner_tree(G, terminal_nodes, method=method)
assert edges_equal(S.edges(data=True, keys=True), expected_edges)


@pytest.mark.parametrize("method", ("kou", "mehlhorn"))
def test_steiner_tree_weight_attribute(method):
G = nx.star_graph(4)
# Add an edge attribute that is named something other than "weight"
nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
H = nx.approximation.steiner_tree(G, [1, 3], method=method, weight="distance")
assert nx.utils.edges_equal(H.edges, [(0, 1), (0, 3)])


@pytest.mark.parametrize("method", ("kou", "mehlhorn"))
def test_steiner_tree_multigraph_weight_attribute(method):
G = nx.cycle_graph(3, create_using=nx.MultiGraph)
nx.set_edge_attributes(G, {e: 10 for e in G.edges}, name="distance")
G.add_edge(2, 0, distance=5)
H = nx.approximation.steiner_tree(G, list(G), method=method, weight="distance")
assert len(H.edges) == 2 and H.has_edge(2, 0, key=1)
assert sum(dist for *_, dist in H.edges(data="distance")) == 15