这个问题需要一些特殊性,但这里尝试用节点的元组构造一些虚拟数据,提取任意路径,并转储为 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)
结果
另请参阅其他 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}