[英]Networkx Average shortest path with labels
我想計算標簽圖中具有相同標簽的節點的平均最短路徑。 例如,紅色標記為A,黑色標記為B。
G = nx.DiGraph()
G.add_node('A', label = 'A')
G.add_node('B', label = 'B')
G.add_node('C', label = 'A')
G.add_node('D', label = 'B')
G.add_edges_from([('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'A')])
H = G.to_undirected()
現在我只想基於此計算A的平均最短路徑
V_m是具有相同標簽的頂點。 n_ {i,j}是最短路徑的數量,d_ {i,j}是測地距離。
我想使用Networkx來實現。 開始使用節點屬性進行標記。
我可以用它們的標簽讀出節點
graph_labels = (nx.get_node_attributes(G, 'label'))
現在,我只想將鍵/值對保留在標簽為“ A”的位置。 因此,我可以專注於具有相同標簽的節點。 我希望它不是抽象的,但是您有什么想法嗎?
提前致謝。
def select_nodes_by_label(G, lab):
return [node[0] for node in G.nodes(data='label') if node[1] == lab ]
這將返回一個節點列表,我們可以用來獲取所有組合的最短路徑。
from itertools import combinations
def avg_shortest_path_labeled_node(G, lab):
sel_nodes = select_nodes_by_label(G,lab)
V_m = len(sel_nodes)
# collect all lengths of shortest paths from combinations of labeled nodes
sp_len = [len(nx.shortest_path(G,c[0], c[1])) for c in combinations(sel_nodes,2)]
n = len(sp_len)
return sum(sp_len)/(n) * 1/(V_m * (V_m - 1))
avg_shortest_path_labeled_node(G,'A')
[出]:
1.5
是您期望的結果嗎? 在更復雜的圖形上測試此功能可能很有趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.