[英]Reducing a weighted directed graph into a DAG with networkx
Suppose there is a weighted directed graph, possibly with cycles假设有一个加权有向图,可能带有循环
import neteorkx as nx
G = nx.DiGraph()
G.add_weighted_edges_from(
[
("a", "b", 10),
("b", "c", 10),
("c", "d", 10),
("d", "e", 5),
("d", "a", 3),
]
)
What is the proper way to reduce that graph such that all cycles are removed and the weights are adjusted accordingly?什么是减少该图的正确方法,以便删除所有循环并相应地调整权重?
eg in this example since the D -(3)-> A
edge is removed, we drop all weights in the path by 3, giving a reduced form of A -(7)-> B -(7)-> C -(7)-> D -(5)-> E
例如,在这个例子中,由于
D -(3)-> A
边缘被删除,我们将路径中的所有权重降低 3,给出A -(7)-> B -(7)-> C -(7)-> D -(5)-> E
Does networkx provide a standardized algorithm for this, or do I need to implement this myself? networkx 是否为此提供了标准化算法,还是我需要自己实现?
Since I haven't found any immediate solutions, I turned to writing my own custom code for this, and right now it doesn't look that bad.由于我还没有找到任何直接的解决方案,因此我转而为此编写自己的自定义代码,现在看起来还不错。
It currently looks something like this:它目前看起来像这样:
try:
while cycle := nx.find_cycle(G, orientation="original"):
edges = [(u, v) for u, v, _ in list(cycle)]
u, v = edges.pop()
weight = G[u][v]["weight"]
G.remove_edge(u, v)
for u, v in edges:
G[u][v]["weight"] -= weight
except nx.exception.NetworkXNoCycle:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.