NetworkX 使用(三)


%pylab inline
import networkx as nx
Populating the interactive namespace from numpy and matplotlib
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3])
G.add_edge(1,2)
e = (2,3)
G.add_edge(*e)  # Unpacking tuple
G.add_edges_from([(1,2),(1,3)])
nx.draw(G)

output_3_0.png-10.8kB

print(G.number_of_nodes())
print(G.number_of_edges())
3
3
G[1]
AtlasView({2: {}, 3: {}})
G[1][2]['weight'] = 10
G[1]
AtlasView({2: {'weight': 10}, 3: {}})
FG = nx.Graph()
FG.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
for n,nbrs in FG.adjacency():
    for nbr,eattr in nbrs.items():
        data=eattr['weight']
        if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))
(1, 2, 0.125)
(2, 1, 0.125)
(3, 4, 0.375)
(4, 3, 0.375)
print(list(FG.adjacency()))
type(FG.adjacency())
[(1, {2: {'weight': 0.125}, 3: {'weight': 0.75}}), (2, {1: {'weight': 0.125}, 4: {'weight': 1.2}}), (3, {1: {'weight': 0.75}, 4: {'weight': 0.375}}), (4, {2: {'weight': 1.2}, 3: {'weight': 0.375}})]





dict_itemiterator
# Convenient access to all edges is achieved with the edges method.
for (u,v,d) in FG.edges(data='weight'):
     if d<0.5: print('(%d, %d, %.3f)'%(n,nbr,d))
(4, 3, 0.125)
(4, 3, 0.375)

添加 graphs, nodes, 和 edges 的屬性

屬性 (Attributes) 有 weights, labels, colors, 或者你喜歡的如何 Python 對象均可添加到 graphs, nodes, 或者 edges 中.

Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but attributes can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named G.graph, G.node and G.edge for a graph G.

Graph 屬性

在創建新圖的時候分配圖屬性.

G = nx.Graph(day="Friday")
G.graph
{'day': 'Friday'}

或者,你可以在之后修改:

G.graph['day']='Monday'
G.graph
{'day': 'Monday'}

Node 屬性

使用 add_node(), add_nodes_from() 或者 G.node 添加節點屬性.

G.add_node(1, time = '5pm')
G.node[1]
{'time': '5pm'}
G.add_nodes_from([3], time='2pm')
G.node[3]
{'time': '2pm'}
G.node[1]['room'] = 714
G.node[1]
{'time': '5pm', 'room': 714}
G.nodes(data=True)
NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})

Note that adding a node to G.node does not add it to the graph, use G.add_node() to add new nodes.

Edge 屬性

使用 add_edge(), add_edges_from(), subscript notation(下標注釋), 或者 G.edge 添加邊屬性.

G.add_edge(1, 2, weight=4.7 )
G[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(data=True)
EdgeDataView([(1, 2, {'weight': 4.7, 'color': 'blue'}), (3, 4, {'color': 'red'}), (3, 2, {'weight': 8}), (4, 5, {'color': 'red'})])

轉換圖為鄰接矩陣

你可以使用 nx.to_numpy_matrix(G)G 轉換為 numpy 矩陣. 如果是加權圖,則矩陣的元素是權重值. 如果邊不存在,其值則設置為 \(0\) 而不是 Infinity(無窮大). You have to manually modify those values to Infinity (float('inf'))

nx.to_numpy_matrix(G)
matrix([[0. , 0. , 4.7, 0. , 0. ],
        [0. , 0. , 8. , 1. , 0. ],
        [4.7, 8. , 0. , 0. , 0. ],
        [0. , 1. , 0. , 0. , 1. ],
        [0. , 0. , 0. , 1. , 0. ]])
nx.to_numpy_matrix(FG)
matrix([[0.   , 0.125, 0.75 , 0.   ],
        [0.125, 0.   , 0.   , 1.2  ],
        [0.75 , 0.   , 0.   , 0.375],
        [0.   , 1.2  , 0.375, 0.   ]])

有向圖

DiGraph 類提供了許多有向圖中的額外算法,比如 DiGraph.out_edges(), DiGraph.in_degree(), DiGraph.predecessors(), DiGraph.successors()等。為了讓算法可以在兩類圖中都可以工作,無向圖中的 neighbors()degree() 分別等價於有向圖中的 successors()和有向圖中的 in_degree()out_degree() 的和.

DG = nx.DiGraph()
DG.add_weighted_edges_from([(1, 2, 0.5), (1, 3, 1.1), (4, 1, 2.3)])
DG.out_degree(1)  # 節點 1 的出度
2
DG.out_degree(1, weight='weight')  # 節點 1 的所有出度的權值之和
1.6
list(DG.successors(1)) # 節點 1 的繼承者
[2, 3]
list(DG.neighbors(1)) # 節點 1 的鄰居(不包括指向節點 1 的節點)
[2, 3]

有向圖與無向圖的轉換

H = DG.to_undirected()
# 或者
H = nx.Graph(DG)

多圖(Multigraphs)

NetworkX 提供了一個類,它可以允許任何一對節點之間有多條邊。類 MultiGraph 和類 MultiDiGraph 允許添加相同的邊兩次,這兩條邊可能附帶不同的權值。對於有些應用程序這是非常有用的類,但是許多算法不能夠很好的在這樣的圖中定義,比如最短路徑算法,但是像 MultiGraph.degree 這種算法又可以很好的被定義。否則你應該為了很好的定義測量,而將圖轉化為標准的圖。

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'))

GG = nx.Graph()
for n, nbrs in MG.adjacency():
    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]

圖的生成器和圖的操作

除了通過節點和邊生成圖,也可以通過以下方法產生:

使用典型的圖形操作:

  • subgraph(G, nbunch) - 產生 nbunch 節點的子圖
  • union(G1,G2) - 結合圖
  • disjoint_union(G1,G2) - 假設所有節點都不同,然后結合圖
  • cartesian_product(G1,G2) - 返回笛卡爾乘積圖
  • compose(G1,G2) - 結合兩個圖並表示兩者共同的節點
  • complement(G) - 圖 G 的補圖
  • create_empty_copy(G) - 返回同一類圖的無邊副本
  • convert_to_undirected(G) - 返回 G 的無向圖
  • convert_to_directed(G) - 返回G的有向圖

調用經典的小圖

petersen = nx.petersen_graph()

tutte = nx.tutte_graph()

maze = nx.sedgewick_maze_graph()

tet = nx.tetrahedral_graph()

使用一些圖形生成器

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)

使用隨機圖發生器

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)

通過讀取存儲在文件中的一些標准圖形格式,例如邊表,鄰接表,GML,GraphML,pickle,LEAD或者其他的一些格式:

nx.write_gml(red,"path.to.file")

mygraph=nx.read_gml("path.to.file")

分析圖

圖 G 的結構可以通過各種圖論的函數來分析,例如:

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}

返回節點屬性的函數是通過返回一個以節點為鍵的字典來實現的:

nx.degree(G)
DegreeView({1: 2, 2: 1, 3: 1, 'spam': 0})

圖算法:Algorithms


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM