簡體   English   中英

使用networkx計算加權無向圖中連接到一個節點的每個子圖中的節點和邊數

[英]Count the number of nodes and edges in each subgraph connected to one node in a weighted undirected graph with networkx

讓我們考慮一個加權無向圖 G。Networkx 是否有一種優化的方法來獲得連接到一個焦點節點的每個子圖的節點數和邊數?

import networkx as nx
import matplotlib.pyplot as plt

listcolor = ['darkblue', 'blue', 'darkred', 'red', 'darkgreen', 'lime', 'gold', 'yellow', 'darkslateblue', 'darkorchid', 'darkorange', 'orange']

G = nx.Graph()

G.add_edge('A', 'B', weight= 1)
G.add_edge('A', 'J', weight= 2)
G.add_edge('K', 'L', weight= 4)
G.add_edge('E', 'F', weight= 7)
G.add_edge('I', 'J', weight= 8)
G.add_edge('B', 'K', weight= 9)
G.add_edge('B', 'E', weight= 17)
G.add_edge('A', 'C', weight= 19)
G.add_edge('H', 'K', weight= 19)
G.add_edge('G', 'H', weight= 20)
G.add_edge('D', 'H', weight= 22)

pos = nx.spring_layout(G, seed=2)
nx.draw(G,node_color = listcolor, with_labels = True)
plt.tight_layout()
plt.axis("off")
plt.show()

例如,我們考慮節點 B:它有三個連接的子圖,一個有 5 個節點(包括 K,L,D,H,G),一個有 4 個節點(包括 C,A,J,I)和一個有 2 個節點節點(包括 F,E)。 現在,假設我需要獲得相同的子圖列表以及每個節點的數量,無論考慮的節點是什么(另一個示例為 K)。 如何從 G 中有效地獲取此子圖列表及其節點和邊數? 在此處輸入圖像描述

感謝Paul Brodersen通過他的快速評論向我展示了解決方案的方法:

import networkx as nx
import matplotlib.pyplot as plt
import copy

def GetSubGAtt(g,fn):   # get subgraphs attributes : g: a graph, fn: focal node
      wg = copy.deepcopy(g)  # working graph
      wg.remove_node(fn)
      LSubG = list(nx.connected_components(wg)) # get the subgraphs
      dictr = {}   # a dict of results {neighbor node:number of nodes in its subgraph}
      neig = list(g.adj[fn])   # get the neighbors
      for i,j in enumerate(LSubG):
            l=len(j)
            k=set(neig) & set(j)
            dictr[list(k)[0]]=len(j)
      return dictr


listcolor = ['darkblue', 'blue', 'darkred', 'red', 'darkgreen', 'lime', 'gold', 'yellow', 'darkslateblue', 'darkorchid', 'darkorange', 'orange']

G = nx.Graph()

G.add_edge('A', 'B', weight= 1)
G.add_edge('A', 'J', weight= 2)
G.add_edge('K', 'L', weight= 4)
G.add_edge('E', 'F', weight= 7)
G.add_edge('I', 'J', weight= 8)
G.add_edge('B', 'K', weight= 9)
G.add_edge('B', 'E', weight= 17)
G.add_edge('A', 'C', weight= 19)
G.add_edge('H', 'K', weight= 19)
G.add_edge('G', 'H', weight= 20)
G.add_edge('D', 'H', weight= 22)

result = GetSubGAtt(G,'B')

print(result)

GetSubGAtt() 返回連接到一個焦點節點的子圖的字典以及這些子圖中的節點數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM