对于经验丰富的程序员来说,这可能很容易解决,但我还是找不到解决方案。
我有一个networkx DiGraph(在Python w / flask中),它包含作为节点的元组和带权重的边。
我想从开始节点到结束节点提取所有路径的树及其权重。这基本上是all_simple_paths(),但是有权重,并将它们作为树导出为JSON,一个根(起始节点)和所有(简单)路径直到结束节点。
我看到的解决方案(以及其他):
任何有关如何执行此操作的提示都将受到高度赞赏。 :)
答案 0 :(得分:1)
这个问题需要一些特殊性,但这里是努力用节点的元组构造一些虚拟数据,提取任意路径,并转储为JSON格式。
from random import seed, random, shuffle
seed(11405)
u = [('a','b','c'), ('d','e','f'), ('g','h','i'),
('j','k','l'), ('m','n','o'), ('p','q','r'),
('s','t','u'), ('v','w','x'), ('y','z','a')]
shuffle(u)
v = [('a','b','c'), ('d','e','f'), ('g','h','i'),
('j','k','l'), ('m','n','o'), ('p','q','r'),
('s','t','u'), ('v','w','x'), ('y','z','a')]
shuffle(v)
edges = [ (s,t, {'weight': random()}) for s,t in zip(u,v) if s != t]
import networkx as nx
from networkx.readwrite import json_graph
G = nx.DiGraph()
G.add_edges_from(edges)
# Extract a Path between Two Arbitrary Nodes
u = ('m', 'n', 'o')
v = ('a', 'b', 'c')
paths = list(nx.all_simple_paths(G, u,v))
path = paths[0]
# Extract the Subgraph of G using the Selected Nodes
H = G.subgraph(path)
# Output to JSON in Node-Link Format
print json_graph.node_link_data(H)
另请参阅the docs了解其他JSON导出格式。
{'directed': True,
'graph': [],
'nodes': [{'id': ('g', 'h', 'i')},
{'id': ('p', 'q', 'r')},
{'id': ('a', 'b', 'c')},
{'id': ('m', 'n', 'o')},
{'id': ('v', 'w', 'x')}],
'links': [{'source': 0, 'target': 1, 'weight': 0.5156976823289995},
{'source': 1, 'target': 4, 'weight': 0.7392883299553644},
{'source': 3, 'target': 0, 'weight': 0.2109456825712841},
{'source': 4, 'target': 2, 'weight': 0.8368736026881095}],
'multigraph': False}