NetworkX_python之Tutorial

NetworkX是一個用於創建、操作和研究複雜網絡的結構、動態和功能的Python包。
NetworkX provides:

  • 研究社會、生物和基礎設施網絡的結構和動態的工具;
  • 適用於許多應用程序的標準編程接口和圖形實現
  • 快速的發展環境
  • 能夠輕鬆地處理大型非標準數據集

使用NetworkX,您可以以標準和非標準數據格式加載和存儲網絡,生成許多類型的隨機和經典網絡,分析網絡結構,構建網絡模型,設計新的網絡算法,繪製網絡等等。

install

官方文檔

conda install networkx 或 pip install networkx

networkx basics

在該框架中,關係圖被分爲四類。Graph,DiGraph,MultiDiGraph

Graph,實現無向圖,規定兩點間只有一條邊,同時允許自己到自己的邊存在
DiGraph,是Graph的子類,是有向圖。
MultiGraph,允許兩點之間有多邊存在的無向圖。
MultiDiGraph,允許兩點之間有多邊存在的有向圖。

圖創建

一切操作之前需要先創建圖,在NX中,圖的創建有三種方式
1.在線創建圖

G = nx.Graph()
G.add_edge(1, 2) # default edge data=1
elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
G.add_edges_from(elist)
elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
G.add_weighted_edges_from(elist)

2.讀文件取圖

G=nx.path_graph(4)
nx.write_adjlist(G, "test.adjlist")
G=nx.read_adjlist("test.adjlist")

文件格式爲adjlist,內容如下

0 1
1 2
2 3
3

3.添加邊點
例子如“在線創建圖”中所示。

圖中邊點的增刪

在這裏插入圖片描述

添加圖屬性、節點屬性、邊屬性

  1. 圖屬性
G = nx.Graph(day="Friday")
G.graph
{'day': 'Friday'}

or

G.graph['day'] = "Monday"
G.graph
{'day': 'Monday'}
  1. 節點屬性
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')
G.nodes[1]
{'time': '5pm'}
G.nodes[1]['room'] = 714
G.nodes.data()
NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})
  1. 邊屬性
G.add_edge(1, 2, weight=4.7 )
G.add_edges_from([(3, 4), (4, 5)], color='red')
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
G[1][2]['weight'] = 4.7
G.edges[3, 4]['weight'] = 4.2

有向圖

DiGraph類爲有向圖。它爲邊提供了特殊的屬性。DiGraph.out_edges(), DiGraph.in_degree(), DiGraph.predecessors(), DiGraph.successors()。在DiGraph類中,degree是in_degree和out_degree的總和,neighbors等價於successors。

>>> DG = nx.DiGraph()
>>> DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
>>> DG.out_degree(1, weight='weight')
0.5
>>> DG.degree(1, weight='weight')
1.25
>>> list(DG.successors(1))
[2]
>>> list(DG.neighbors(1))
[2]

千萬不要將有向圖與無向圖混爲一談,兩者有很多方法是不一樣的。以下方法可將有向圖轉爲無向圖。也可使用Graph.to_undirected()

>>> H = nx.Graph(G)  # convert G to undirected graph

多圖

NX 提供了多圖類,允許兩個節點之間存在多邊。MultiGraphMultiDiGraph允許在兩個節點之間添加兩條方向相同的邊。但是後面最好還是要將圖標準化。

>>> MG = nx.MultiGraph()
>>> MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
>>> dict(MG.degree(weight='weight'))#節點各自權重之和,
{1: 1.25, 2: 1.75, 3: 0.5}
# 將圖中,兩節點之間方向相同的邊合併爲一條,取權重最小的邊爲標準邊,其他捨棄。
>>> GG = nx.Graph()
>>> for n, nbrs in MG.adjacency():#n,節點名稱;nbrs,節點鄰節點及邊信息.n: 1;nbrs {2: {0: {'weight': 0.5}, 1: {'weight': 0.75}}}
...    for nbr, edict in nbrs.items():
...        minvalue = min([d['weight'] for d in edict.values()])
...        GG.add_edge(n, nbr, weight = minvalue)
...
>>> nx.shortest_path(GG, 1, 3)#計算最短路徑
[1, 2, 3]

圖形生成器和圖形操作

除了逐點生成或逐邊生成以外,也可以通過以下方式來進行圖的生成。

  1. 應用經典圖操作,例如
  • subgraph(G, nbunch) - induced subgraph view of G on nodes in nbunch
  • union(G1,G2) - graph union
  • disjoint_union(G1,G2) - graph union assuming all nodes are different
  • cartesian_product(G1,G2) - return Cartesian product graph
  • compose(G1,G2) - combine graphs identifying nodes common to both
  • complement(G) - graph complement
  • create_empty_copy(G) - return an empty copy of the same graph class
  • to_undirected(G) - return an undirected representation of G
  • to_directed(G) - return a directed representation of G
  1. 小圖調用
>>> petersen = nx.petersen_graph()
>>> tutte = nx.tutte_graph()
>>> maze = nx.sedgewick_maze_graph()
>>> tet = nx.tetrahedral_graph()
  1. 幾個經典圖生成器的使用
>>> K_5 = nx.complete_graph(5)
>>> K_3_5 = nx.complete_bipartite_graph(3, 5)
>>> barbell = nx.barbell_graph(10, 10)
>>> lollipop = nx.lollipop_graph(10, 20)
  1. 隨機圖生成器的使用
>>> er = nx.erdos_renyi_graph(100, 0.15)
>>> ws = nx.watts_strogatz_graph(30, 3, 0.1)
>>> ba = nx.barabasi_albert_graph(100, 5)
>>> red = nx.random_lobster(100, 0.9, 0.9)
  1. 讀取常見的圖格式( edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others)
>>> nx.write_gml(red, "path.to.file")
>>> mygraph = nx.read_gml("path.to.file")

詳細細節參閱地址 Reading and writing graphsGraph generators

圖分析

NX支持提供各種各樣的圖理論函數進行圖分析。

>>> G = nx.Graph()
>>> G.add_edges_from([(1, 2), (1, 3)])
>>> G.add_node("spam")       # adds node "spam"
>>> list(nx.connected_components(G)) #分析連通區域
[{1, 2, 3}, {'spam'}]
>>> sorted(d for n, d in G.degree())
[0, 1, 1, 2]
>>> nx.clustering(G)
{1: 0, 2: 0, 3: 0, 'spam': 0}

有關圖分析算法的詳細信息及其他函數請參與 Algorithms

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章