我有一个水管网络,其中每个节点都是一栋房子,每条边都是连接房屋的管道。边具有水量属性。
我想计算到达节点 13 的总流量。
总结如下5+2+1+6+0+3+14+4+12+5+8+10+6+9=85
我尝试过类似的东西,但它会重复已经遍历过的路径。例如,我不想多次将节点 1 到 2(权重 5)的值相加:
import networkx as nx
from itertools import combinations
G = nx.DiGraph()
edges = [(1,2,5), (2,5,0), (3,2,2), (3,4,1), (4,5,6), (5,6,3), (7,8,14), (8,6,4), (6,9,12), (9,11,8), (10,9,5),(10,12,10), (11,12,6),(12,13,9)]
for edge in edges:
n1, n2, weight = edge
G.add_edge(n1, n2, volume=weight)
for n1, n2 in combinations(G.nodes,2):
paths = list(nx.all_simple_paths(G=G, source=n1, target=n2))
for path in paths:
total_weight = nx.path_weight(G=G, path=path, weight="volume")
print(f"From node {n1} to {n2}, there's the path {'-'.join([str(x) for x in path])} \n with the total volume: {total_weight}")
# From node 1 to 2, there's the path 1-2
# with the total volume: 5
# From node 1 to 5, there's the path 1-2-5
# with the total volume: 5
# From node 1 to 6, there's the path 1-2-5-6
# ...
IIUC,只需获取
subgraph
所有ancestors
13(包括 13)的 a ,然后计算加权size
(=所有边权重的总和):输出:
85