import networkx as nx
import matplotlib.pyplot as plt
建立图
G1=nx.Graph() # 无向图
G2=nx.DiGraph()# 有向图
G3=nx.MultiGraph() # 多图
G4=nx.MultiDiGraph()
图建立之后,进行加边
G1=nx.Graph()
G1.add_nodes_from([5,6,7])
G1.add_edges_from([(5,6),(6,7),(5,7)])
nx.draw_networkx(G1)
plt.show()
G2=nx.Graph()
G2.add_nodes_from([5,6,7])
G2.add_weighted_edges_from([(5,6,5.0),(6,7,2.0),(5,7,3.0)])
nx.draw_networkx(G1)
plt.show()
G2=nx.Graph()
nodes=[1,2,3]
G2.add_nodes_from(nodes)
labels=[(1,2,3.0),(1,3,4),(2,3,5)]
G2.add_weighted_edges_from(labels)
nx.draw_networkx(G2)
plt.show()
删除点和边
G.remove_node()
G.remove_nodes_from()
G.remove_edge()
G.remove_edges_from()
G.clear()
遍历点和边
G2.nodes()
NodeView((1, 2, 3))
G2.edges()
EdgeView([(1, 2), (1, 3), (2, 3)])
for i in G2.edges():
print(i)
(1, 2)
(1, 3)
(2, 3)
特殊图,完全图,完全二分图
k_5=nx.complete_graph(6)
nx.draw_networkx(k_5)
plt.show()
k_33=nx.complete_bipartite_graph(10,2)
nx.draw_networkx(k_33)
plt.show()
最短路径
G=nx.complete_graph(6)
nx.draw_networkx(G)
plt.show()
path=nx.single_source_shortest_path(k_33,2)
print(path)
{2: [2], 10: [2, 10], 11: [2, 11], 0: [2, 10, 0], 1: [2, 10, 1], 3: [2, 10, 3], 4: [2, 10, 4], 5: [2, 10, 5], 6: [2, 10, 6], 7: [2, 10, 7], 8: [2, 10, 8], 9: [2, 10, 9]}
length=nx.single_source_shortest_path_length(k_33,2)
print(length)
{2: 0, 10: 1, 11: 1, 0: 2, 1: 2, 3: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2}
读写图与属性
G=nx.grid_2d_graph(5,5)
nx.draw(G)
G.edges()
EdgeView([((0, 0), (1, 0)), ((0, 0), (0, 1)), ((0, 1), (1, 1)), ((0, 1), (0, 2)), ((0, 2), (1, 2)), ((0, 2), (0, 3)), ((0, 3), (1, 3)), ((0, 3), (0, 4)), ((0, 4), (1, 4)), ((1, 0), (2, 0)), ((1, 0), (1, 1)), ((1, 1), (2, 1)), ((1, 1), (1, 2)), ((1, 2), (2, 2)), ((1, 2), (1, 3)), ((1, 3), (2, 3)), ((1, 3), (1, 4)), ((1, 4), (2, 4)), ((2, 0), (3, 0)), ((2, 0), (2, 1)), ((2, 1), (3, 1)), ((2, 1), (2, 2)), ((2, 2), (3, 2)), ((2, 2), (2, 3)), ((2, 3), (3, 3)), ((2, 3), (2, 4)), ((2, 4), (3, 4)), ((3, 0), (4, 0)), ((3, 0), (3, 1)), ((3, 1), (4, 1)), ((3, 1), (3, 2)), ((3, 2), (4, 2)), ((3, 2), (3, 3)), ((3, 3), (4, 3)), ((3, 3), (3, 4)), ((3, 4), (4, 4)), ((4, 0), (4, 1)), ((4, 1), (4, 2)), ((4, 2), (4, 3)), ((4, 3), (4, 4))])
[i for i in nx.generate_adjlist(G)]
['(0, 0) (1, 0) (0, 1)',
'(0, 1) (1, 1) (0, 2)',
'(0, 2) (1, 2) (0, 3)',
'(0, 3) (1, 3) (0, 4)',
'(0, 4) (1, 4)',
'(1, 0) (2, 0) (1, 1)',
'(1, 1) (2, 1) (1, 2)',
'(1, 2) (2, 2) (1, 3)',
'(1, 3) (2, 3) (1, 4)',
'(1, 4) (2, 4)',
'(2, 0) (3, 0) (2, 1)',
'(2, 1) (3, 1) (2, 2)',
'(2, 2) (3, 2) (2, 3)',
'(2, 3) (3, 3) (2, 4)',
'(2, 4) (3, 4)',
'(3, 0) (4, 0) (3, 1)',
'(3, 1) (4, 1) (3, 2)',
'(3, 2) (4, 2) (3, 3)',
'(3, 3) (4, 3) (3, 4)',
'(3, 4) (4, 4)',
'(4, 0) (4, 1)',
'(4, 1) (4, 2)',
'(4, 2) (4, 3)',
'(4, 3) (4, 4)',
'(4, 4)']
# 写数据
#nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
# read edgelist from grid.edgelist
# 读数据
#H = nx.read_edgelist(path="grid.edgelist", delimiter=":")
G = nx.lollipop_graph(4, 6)
nx.draw(G,with_labels=True)
plt.show()
pathlength=[]
G.nodes()
NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
for v in G.nodes():
spl=dict(nx.single_target_shortest_path_length(G,v))
print("{} {}".format(v,spl))
for p in spl:
pathlength.append(spl[p])
0 {0: 0, 1: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7}
1 {1: 0, 0: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7}
2 {2: 0, 0: 1, 1: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7}
3 {3: 0, 0: 1, 1: 1, 2: 1, 4: 1, 5: 2, 6: 3, 7: 4, 8: 5, 9: 6}
4 {4: 0, 3: 1, 5: 1, 0: 2, 1: 2, 2: 2, 6: 2, 7: 3, 8: 4, 9: 5}
5 {5: 0, 4: 1, 6: 1, 3: 2, 7: 2, 0: 3, 1: 3, 2: 3, 8: 3, 9: 4}
6 {6: 0, 5: 1, 7: 1, 8: 2, 4: 2, 9: 3, 3: 3, 0: 4, 1: 4, 2: 4}
7 {7: 0, 8: 1, 6: 1, 9: 2, 5: 2, 4: 3, 3: 4, 0: 5, 1: 5, 2: 5}
8 {8: 0, 9: 1, 7: 1, 6: 2, 5: 3, 4: 4, 3: 5, 0: 6, 1: 6, 2: 6}
9 {9: 0, 8: 1, 7: 2, 6: 3, 5: 4, 4: 5, 3: 6, 0: 7, 1: 7, 2: 7}
pathlength
[0,
1,
1,
1,
2,
3,
4,
5,
6,
7,
0,
1,
1,
1,
2,
3,
4,
5,
6,
7,
0,
1,
1,
1,
2,
3,
4,
5,
6,
7,
0,
1,
1,
1,
1,
2,
3,
4,
5,
6,
0,
1,
1,
2,
2,
2,
2,
3,
4,
5,
0,
1,
1,
2,
2,
3,
3,
3,
3,
4,
0,
1,
1,
2,
2,
3,
3,
4,
4,
4,
0,
1,
1,
2,
2,
3,
4,
5,
5,
5,
0,
1,
1,
2,
3,
4,
5,
6,
6,
6,
0,
1,
2,
3,
4,
5,
6,
7,
7,
7]
print(f"平均长度为{sum(pathlength)/len(pathlength)}")
平均长度为2.86
dist={}
for p in pathlength:
if p in dist:
dist[p] += 1
else:
dist[p] = 1
dist
{0: 10, 1: 24, 2: 16, 3: 14, 4: 12, 5: 10, 6: 8, 7: 6}
dist.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7])
for d in sorted(dist.keys()):
print(f"{d} {dist[d]}")
0 10
1 24
2 16
3 14
4 12
5 10
6 8
7 6
绘图
- 简单路径Simple Path
- 节点颜色Node Colormap
- 边的颜色 Edge Colormap
- 带颜色的房子 House With Colors
- 环形树Circular Tree
- 等级排列Degree Rank
- 谱嵌入Spectral Embedding
- 四宫格Four Grids
- 自我中心网络Ego Graph
- 度直方图Degree histogram
- 随机几何图形Random Geometric Graph
- 加权图Weighted Graph
- 有向图Directed Graph
- 标签和颜色Labels And Colors
- 最大连通分支Giant Component
- 地图集Atlas
G=nx.path_graph(24)
nx.draw(G)
# 标节点颜色
G=nx.path_graph(24)
pos=nx.spring_layout(G,iterations=100)
# cmap=plt.cm.Reds 控制颜色选择范围
# node_size=100 节点大小
nx.draw(G,pos,node_color=range(24),node_size=100, cmap=plt.cm.Reds)
plt.show()
# 标边的颜色
G=nx.star_graph(24)
pos=nx.spring_layout(G)
colors = range(24)
colors2 = range(25)
nx.draw(G, pos, node_color=colors2, edge_color=colors,
width=4, edge_cmap=plt.cm.Blues, with_labels=True)
plt.show()
# 节点颜色
G = nx.house_graph()
# explicitly set positions
pos2=nx.spring_layout(G,iterations=100)
pos = {0: (0, 0),
1: (1, 0),
2: (0, 1),
3: (1, 1),
4: (0.5, 2.0)}
# 点的颜色
# nx.draw(G,pos,node_color=range(5),node_size=100,
# edge_color=range(6),width=3,
# cmap=plt.cm.Reds)
nx.draw_networkx_nodes(G, pos, node_size=80, nodelist=[4])
nx.draw_networkx_nodes(G, pos, node_size=30, nodelist=[0, 1, 2, 3], node_color='b')
nx.draw_networkx_edges(G,pos, edge_color=range(6),width=3,alpha=1)
nx.draw(G,pos,with_labels=True)
plt.show()
G = nx.Graph()
labels=[("a","b",0.6),("a","c",0.4),("b","c",0.2)]
nodes=["a","b","c"]
G2.add_nodes_from(nodes)
G.add_edges_from(labels)
nx.draw(G)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-145-34fa279f4449> in <module>
3 nodes=["a","b","c"]
4 G2.add_nodes_from(nodes)
----> 5 G.add_edges_from(labels)
6 nx.draw(G)
G:\anaconda\ana2\lib\site-packages\networkx\classes\graph.py in add_edges_from(self, ebunch_to_add, **attr)
937 datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
938 datadict.update(attr)
--> 939 datadict.update(dd)
940 self._adj[u][v] = datadict
941 self._adj[v][u] = datadict
TypeError: 'float' object is not iterable
pos
{'a': array([ 0.51804335, -0.0643564 ]),
'b': array([ 1. , -0.25656045]),
'c': array([-0.40023676, -0.02447434]),
'd': array([0.35081305, 0.46342116]),
'e': array([-0.80520955, 0.26219699]),
'f': array([-0.66341009, -0.38022696])}
G2=nx.Graph()
nodes=["a","b","c","d","e","f"]
G2.add_nodes_from(nodes)
labels=[("a","b",0.6),("a","c",0.2),("c","d",0.1),("c","e",0.7),("c","f",0.9),("a","d",0.3)]
G2.add_weighted_edges_from(labels)
pos=nx.spring_layout(G2)
nx.draw_networkx_edges(G2, pos, edgelist=large,width=6)
nx.draw_networkx_edges(G, pos, edgelist=smail,width=6, alpha=0.5, edge_color='b', style='dashed')
# nx.draw_networkx_labels(G, pos, font_size=0, font_family='sans-serif')
nx.draw(G,pos,with_labels=True,node_color="Red")
# 设置颜色
# nx.draw_networkx_edges(G2, edge_color=range(6),width=3,alpha=1)
# nx.draw_networkx(G2)
plt.show()
G2.edges(data=True)
EdgeDataView([('a', 'b', {'weight': 0.6}), ('a', 'c', {'weight': 0.2}), ('a', 'd', {'weight': 0.3}), ('c', 'd', {'weight': 0.1}), ('c', 'e', {'weight': 0.7}), ('c', 'f', {'weight': 0.9})])
large=[]
for (u,v,d) in G2.edges(data=True):
if d['weight'] > 0.5:
print(u,v)
large.append((u,v))
smail=[]
for (u,v,d) in G2.edges(data=True):
if d['weight'] <= 0.5:
print(u,v)
smail.append((u,v))
a b
c e
c f
a c
a d
c d
pos=nx.spring_layout(G2)
# 找出权重大于0.5的边
large=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] > 0.5]
large=[]
for (u,v,d) in G2.edges(data=True):
if d['weight'] > 0.5:
print(u,v)
large.append((u,v))
a b
c e
c f
large
[('a', 'b'), ('c', 'e'), ('c', 'f')]
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
elarge
[]
# 拿破仑俄国战役
data1 = """\
24.0,54.9,340000,A,1
24.5,55.0,340000,A,1
25.5,54.5,340000,A,1
26.0,54.7,320000,A,1
27.0,54.8,300000,A,1
28.0,54.9,280000,A,1
28.5,55.0,240000,A,1
29.0,55.1,210000,A,1
30.0,55.2,180000,A,1
30.3,55.3,175000,A,1
32.0,54.8,145000,A,1
33.2,54.9,140000,A,1
34.4,55.5,127100,A,1
35.5,55.4,100000,A,1
36.0,55.5,100000,A,1
37.6,55.8,100000,A,1
37.7,55.7,100000,R,1
37.5,55.7,98000,R,1
37.0,55.0,97000,R,1
36.8,55.0,96000,R,1
35.4,55.3,87000,R,1
34.3,55.2,55000,R,1
33.3,54.8,37000,R,1
32.0,54.6,24000,R,1
30.4,54.4,20000,R,1
29.2,54.3,20000,R,1
28.5,54.2,20000,R,1
28.3,54.3,20000,R,1
27.5,54.5,20000,R,1
26.8,54.3,12000,R,1
26.4,54.4,14000,R,1
25.0,54.4,8000,R,1
24.4,54.4,4000,R,1
24.2,54.4,4000,R,1
24.1,54.4,4000,R,1"""
data2 = """\
24.0,55.1,60000,A,2
24.5,55.2,60000,A,2
25.5,54.7,60000,A,2
26.6,55.7,40000,A,2
27.4,55.6,33000,A,2
28.7,55.5,33000,R,2
29.2,54.2,30000,R,2
28.5,54.1,30000,R,2
28.3,54.2,28000,R,2"""
data3 = """\
24.0,55.2,22000,A,3
24.5,55.3,22000,A,3
24.6,55.8,6000,A,3
24.6,55.8,6000,R,3
24.2,54.4,6000,R,3
24.1,54.4,6000,R,3"""
cities = """\
24.0,55.0,Kowno
25.3,54.7,Wilna
26.4,54.4,Smorgoni
26.8,54.3,Moiodexno
27.7,55.2,Gloubokoe
27.6,53.9,Minsk
28.5,54.3,Studienska
28.7,55.5,Polotzk
29.2,54.4,Bobr
30.2,55.3,Witebsk
30.4,54.5,Orscha
30.4,53.9,Mohilow
32.0,54.8,Smolensk
33.2,54.9,Dorogobouge
34.3,55.2,Wixma
34.4,55.5,Chjat
36.0,55.5,Mojaisk
37.6,55.8,Moscou
36.6,55.3,Tarantino
36.5,55.0,Malo-Jarosewii"""
c={}
for line in cities.split('\n'):
x,y,name=line.split(",")
c[name]=(float(x),float(y))
c
{'Kowno': (24.0, 55.0),
'Wilna': (25.3, 54.7),
'Smorgoni': (26.4, 54.4),
'Moiodexno': (26.8, 54.3),
'Gloubokoe': (27.7, 55.2),
'Minsk': (27.6, 53.9),
'Studienska': (28.5, 54.3),
'Polotzk': (28.7, 55.5),
'Bobr': (29.2, 54.4),
'Witebsk': (30.2, 55.3),
'Orscha': (30.4, 54.5),
'Mohilow': (30.4, 53.9),
'Smolensk': (32.0, 54.8),
'Dorogobouge': (33.2, 54.9),
'Wixma': (34.3, 55.2),
'Chjat': (34.4, 55.5),
'Mojaisk': (36.0, 55.5),
'Moscou': (37.6, 55.8),
'Tarantino': (36.6, 55.3),
'Malo-Jarosewii': (36.5, 55.0)}
G=nx.Graph()
g=[]
# 24.2,54.4,6000,R,3
for data in [data1,data2,data2]:
# G=nx.graph()
i=0
G.pos={}
G.pop={}
last=None
for line in data.split("\n"):
x,y,p,r,n=line.split(",")
G.pos[i]=(float(x),float(y))
G.pop[i]=int(p)
if last is None:
last = i
else:
G.add_edge(i, last, **{r: int(n)})
last = i
i = i + 1
g.append(G)
city=c
plt.figure(1, figsize=(11, 5))
plt.clf()
colors = ["b", "g", "r"]
for G in g:
c = colors.pop(0)
node_size = [int(G.pop[n] / 300.0) for n in G]
nx.draw_networkx_edges(G, G.pos, edge_color=c, width=4, alpha=0.5)
nx.draw_networkx_nodes(G, G.pos, node_size=node_size, node_color=c, alpha=0.5)
nx.draw_networkx_nodes(G, G.pos, node_size=5, node_color="k")
for c in city:
x, y = city[c]
plt.text(x, y + 0.1, c)
plt.show()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-224-26383fe76ce3> in <module>
4 for G in g:
5 c = colors.pop(0)
----> 6 node_size = [int(G.pop[n] / 300.0) for n in G]
7 nx.draw_networkx_edges(G, G.pos, edge_color=c, width=4, alpha=0.5)
8 nx.draw_networkx_nodes(G, G.pos, node_size=node_size, node_color=c, alpha=0.5)
<ipython-input-224-26383fe76ce3> in <listcomp>(.0)
4 for G in g:
5 c = colors.pop(0)
----> 6 node_size = [int(G.pop[n] / 300.0) for n in G]
7 nx.draw_networkx_edges(G, G.pos, edge_color=c, width=4, alpha=0.5)
8 nx.draw_networkx_nodes(G, G.pos, node_size=node_size, node_color=c, alpha=0.5)
KeyError: 8
<Figure size 792x360 with 0 Axes>
import matplotlib.pyplot as plt
import networkx as nx
def minard_graph():
data1 = """\
24.0,54.9,340000,A,1
24.5,55.0,340000,A,1
25.5,54.5,340000,A,1
26.0,54.7,320000,A,1
27.0,54.8,300000,A,1
28.0,54.9,280000,A,1
28.5,55.0,240000,A,1
29.0,55.1,210000,A,1
30.0,55.2,180000,A,1
30.3,55.3,175000,A,1
32.0,54.8,145000,A,1
33.2,54.9,140000,A,1
34.4,55.5,127100,A,1
35.5,55.4,100000,A,1
36.0,55.5,100000,A,1
37.6,55.8,100000,A,1
37.7,55.7,100000,R,1
37.5,55.7,98000,R,1
37.0,55.0,97000,R,1
36.8,55.0,96000,R,1
35.4,55.3,87000,R,1
34.3,55.2,55000,R,1
33.3,54.8,37000,R,1
32.0,54.6,24000,R,1
30.4,54.4,20000,R,1
29.2,54.3,20000,R,1
28.5,54.2,20000,R,1
28.3,54.3,20000,R,1
27.5,54.5,20000,R,1
26.8,54.3,12000,R,1
26.4,54.4,14000,R,1
25.0,54.4,8000,R,1
24.4,54.4,4000,R,1
24.2,54.4,4000,R,1
24.1,54.4,4000,R,1"""
data2 = """\
24.0,55.1,60000,A,2
24.5,55.2,60000,A,2
25.5,54.7,60000,A,2
26.6,55.7,40000,A,2
27.4,55.6,33000,A,2
28.7,55.5,33000,R,2
29.2,54.2,30000,R,2
28.5,54.1,30000,R,2
28.3,54.2,28000,R,2"""
data3 = """\
24.0,55.2,22000,A,3
24.5,55.3,22000,A,3
24.6,55.8,6000,A,3
24.6,55.8,6000,R,3
24.2,54.4,6000,R,3
24.1,54.4,6000,R,3"""
cities = """\
24.0,55.0,Kowno
25.3,54.7,Wilna
26.4,54.4,Smorgoni
26.8,54.3,Moiodexno
27.7,55.2,Gloubokoe
27.6,53.9,Minsk
28.5,54.3,Studienska
28.7,55.5,Polotzk
29.2,54.4,Bobr
30.2,55.3,Witebsk
30.4,54.5,Orscha
30.4,53.9,Mohilow
32.0,54.8,Smolensk
33.2,54.9,Dorogobouge
34.3,55.2,Wixma
34.4,55.5,Chjat
36.0,55.5,Mojaisk
37.6,55.8,Moscou
36.6,55.3,Tarantino
36.5,55.0,Malo-Jarosewii"""
c = {}
for line in cities.split("\n"):
x, y, name = line.split(",")
c[name] = (float(x), float(y))
g = []
for data in [data1, data2, data3]:
G = nx.Graph()
i = 0
G.pos = {} # location
G.pop = {} # size
last = None
for line in data.split("\n"):
x, y, p, r, n = line.split(",")
G.pos[i] = (float(x), float(y))
G.pop[i] = int(p)
if last is None:
last = i
else:
G.add_edge(i, last, **{r: int(n)})
last = i
i = i + 1
g.append(G)
return g, c
(g, city) = minard_graph()
plt.figure(1, figsize=(11, 5))
plt.clf()
colors = ["b", "g", "r"]
for G in g:
c = colors.pop(0)
node_size = [int(G.pop[n] / 300.0) for n in G]
nx.draw_networkx_edges(G, G.pos, edge_color=c, width=4, alpha=0.5)
nx.draw_networkx_nodes(G, G.pos, node_size=node_size, node_color=c, alpha=0.5)
nx.draw_networkx_nodes(G, G.pos, node_size=5, node_color="k")
for c in city:
x, y = city[c]
plt.text(x, y + 0.1, c)
plt.show()
import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy as np
#来生成一个有N个节点,连接概率为p的随机网络
N = 150
p = 0.04
er=nx.erdos_renyi_graph(N,p)
for i in range(N):
er.nodes[i]['state'] = 'S'
gama = 0.5
beta = 0.1
ps=nx.spring_layout(er)#布置框架
colors={"R":'b',"I":'r',"S":'g'}
states= nx.get_node_attributes(er, 'state')############ 获得节点的isCore属性
color=[colors[states[i]] for i in range(N)]
nx.draw(er,ps,node_color =color ,with_labels=False,node_size=20)
plt.show()
def centrality(G):
#计算度中心性,降序
dc = nx.algorithms.centrality.degree_centrality(G)
return sorted(dc.items(), key=lambda x: x[1],reverse = True)
def betweenness(G):
#计算介数中心性,降序
dc = nx.betweenness_centrality(G)
return sorted(dc.items(), key=lambda x: x[1],reverse = True)
def closeness(G):
#计算接近中心性,降序
dc = nx.closeness_centrality(G)
return sorted(dc.items(), key=lambda x: x[1],reverse = True)
data_cent=centrality(G)
data_betw=betweenness(G)
data_clo=closeness(G)
# N(t)=s(t)+i(t)+r(t)
def spread(G,beta,initial,func,gamma=0):
colors={"R":'b',"I":'r',"S":'g'}
y=[]
n = len(G.nodes) #总人数
for i in range(n):
G.nodes[i]["state"]="S"
s=n-initial # 易感染人数
desc=func(G)
i_nodes=[]
#选择前inttial个度中心性最高的节点设为感染源
for i in range(initial):
G.nodes[desc[0][0]['state']]="I"
i_nodes.append(desc[0][0])
desc_dc.remove(desc_dc[0])
y.append( ( (s, (len(i_nodes)),0 ) ))
t_nodes=nx.Graph()
while len(i_nodes) !=0:
print(s)
i_temp=[]
for i in i_nodes:
if random.random() < gamma:
r_nodes.add_node(i)
i_nodes.remove(i)
G.nodes[i]['state'] = 'R'
i_nodes_temp = nx.Graph()
i_nodes_temp.add_nodes_from(i_nodes)
for i in i_nodes_temp.nodes:
#按beta概率传染I节点的邻居节点
for node in G.neighbors(i):
r= random.random()
if r < beta and G.nodes[node]['state'] == 'S':
G.nodes[node]['state'] = 'I'
i_temp.append(node)
for t in i_temp :
if t not in i_nodes:
i_nodes.append(t)
s = n - len(i_nodes) -len(r_nodes.nodes)
i = len(i_nodes)
r = len(r_nodes.nodes)
y.append((s,i,r))
states= nx.get_node_attributes(G, 'state')############ 获得节点的属性
color=[colors[states[i]] for i in range(n)]
nx.draw(G,ps,node_color =color ,with_labels=True,node_size=300)
plt.show()
return np.array(y)
#选择度中心性最高的5个点作为感染源
result = spread(er,0.3,5,centrality,0.1)
print(result)
plt.plot(result[:,0], 'g', label='Susceptibles')
plt.plot(result[:,1], 'r', label='Infectious')
plt.plot(result[:,2], 'b', label='Recovereds')
plt.legend(loc='right')
plt.xlabel('time')
plt.ylabel('number of people')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-244-992b55a89be6> in <module>
1 #选择度中心性最高的5个点作为感染源
----> 2 result = spread(er,0.3,5,centrality,0.1)
3 print(result)
4 plt.plot(result[:,0], 'g', label='Susceptibles')
5 plt.plot(result[:,1], 'r', label='Infectious')
<ipython-input-243-ee7c39402c8b> in spread(G, beta, initial, func, gamma)
11 #选择前inttial个度中心性最高的节点设为感染源
12 for i in range(initial):
---> 13 G.nodes[desc[0][0]['state']]="I"
14 i_nodes.append(desc[0][0])
15 desc_dc.remove(desc_dc[0])
TypeError: 'int' object is not subscriptable
# S表示易感者,I表示感染者,R表示移出者。
gama = 0.7
beta = 0.05
desc1=centrality(G)
desc1
[(1, 0.4), (2, 0.4), (3, 0.4), (4, 0.4), (0, 0.2), (5, 0.2)]
def spread(G,beta,initial,func,gamma = 0 ):
colors={"R":'b',"I":'r',"S":'g'}
y = []
n = len(G.nodes)#总人数
for i in range(n):#所有人默认为易感染
G.nodes[i]['state'] = 'S'
s = n - initial #易感染人数
desc_dc = func(G)
i_nodes = []
#选择前inttial个度中心性最高的节点设为感染源
for i in range(initial):
G.nodes[desc_dc[0][0]]['state'] = 'I'
i_nodes.append(desc_dc[0][0])
desc_dc.remove(desc_dc[0])
y.append( ( (s, (len(i_nodes)),0 ) ))
#开始传播,直到所有人被传染
# y代表SIR各个人数[易感染人数,感染人数,痊愈人数]
# S表示易感者,I表示感染者,R表示移出者。
r_nodes = nx.Graph()
while len(i_nodes) != 0:
print(s)
#当前轮被传染的人数
i_temp = []
#当前恢复人数 gamma 概率,感染人痊愈的概率
for i in i_nodes:
if random.random() < gamma:
r_nodes.add_node(i)
i_nodes.remove(i)
G.nodes[i]['state'] = 'R'
i_nodes_temp = nx.Graph()
i_nodes_temp.add_nodes_from(i_nodes)
for i in i_nodes_temp.nodes:
#感染人 按beta概率传染I节点的邻居节点
for node in G.neighbors(i):
r= random.random()
if r < beta and G.nodes[node]['state'] == 'S':
G.nodes[node]['state'] = 'I'
i_temp.append(node)
for t in i_temp :
if t not in i_nodes:
i_nodes.append(t)
s = n - len(i_nodes) -len(r_nodes.nodes)
i = len(i_nodes)
r = len(r_nodes.nodes)
y.append((s,i,r))
states= nx.get_node_attributes(G, 'state')############ 获得节点的属性
color=[colors[states[i]] for i in range(n)]
nx.draw(G,ps,node_color =color ,with_labels=True,node_size=40)
plt.show()
return np.array(y)
#选择度中心性最高的5个点作为感染源
result = spread(er,0.2,5,centrality,0.3)
print(result)
plt.plot(result[:,0], 'g', label='Susceptibles')
plt.plot(result[:,1], 'r', label='Infectious')
plt.plot(result[:,2], 'b', label='Recovereds')
plt.legend(loc='right')
plt.xlabel('time')
plt.ylabel('number of people')
145
140
129
120
108
92
80
65
60
49
43
39
38
35
33
33
32
30
28
28
27
27
27
27
27
[[145 5 0]
[140 9 1]
[129 19 2]
[120 26 4]
[108 33 9]
[ 92 42 16]
[ 80 46 24]
[ 65 50 35]
[ 60 43 47]
[ 49 44 57]
[ 43 39 68]
[ 39 32 79]
[ 38 27 85]
[ 35 25 90]
[ 33 22 95]
[ 33 14 103]
[ 32 13 105]
[ 30 13 107]
[ 28 14 108]
[ 28 10 112]
[ 27 6 117]
[ 27 4 119]
[ 27 3 120]
[ 27 2 121]
[ 27 1 122]
[ 27 0 123]]
Text(0, 0.5, 'number of people')