import networkx as nx
import matplotlib.pyplot as plt
from pylab import *
import random
mpl.rcParams['font.sans-serif'] = ['SimHei']
def star(n): #生成n个节点的星形网络
G = nx.Graph()
for i in range(1,n):
G.add_edge(i,n)
return G
def all_connect(n): #生成n个节点的全连接网络
G = nx.Graph()
for i in range(1, n):
for j in range(i+1,n+1):
G.add_edge(i, j)
return G
def circle(n): #生成n个节点的环状网络
G = nx.Graph()
for i in range(1, n+1):
if(i!=n):
G.add_edge(i, i+1)
else:
G.add_edge(i,1)
return G
def attack(G):#生成按照某规则依次去除点后的最大联通子图点数量
s = G.copy()
p = G.copy()
list1 = sorted(nx.degree_centrality(G).items(),key=lambda x:x[1],reverse=True)
list_one = [] #按度大小去除点
list_two = [] #随机去除点
list_three = [] #按特征向量去除点
for i in range(len(list1)-1):
data = list1[i]
node = data[0]
G.remove_node(node)
H = list(G.subgraph(c) for c in nx.connected_components(G))
GCC=sorted(H,key=lambda x:nx.number_of_nodes(x))[-1]
list_one.append(nx.number_of_nodes(GCC))
list2 = list(nx.degree(s))
for i in range(len(list2)-1):
data = random.choice(list2)
node = data[0]
s.remove_node(node)
list2.remove(data)
H = list(s.subgraph(c) for c in nx.connected_components(s))
GCC = sorted(H, key=lambda x: nx.number_of_nodes(x))[-1]
list_two.append(nx.number_of_nodes(GCC))
list3 = sorted(nx.eigenvector_centrality(p,max_iter=10000).items(),key=lambda x:x[1],reverse=True)
for i in range(len(list3)-1):
data = list3[i]
node = data[0]
p.remove_node(node)
H = list(p.subgraph(c) for c in nx.connected_components(p))
GCC=sorted(H,key=lambda x:nx.number_of_nodes(x))[-1]
list_three.append(nx.number_of_nodes(GCC))
return [list_one,list_two,list_three]
fun_list = [star,all_connect,circle]
name_list = ["星型网络","全连接网络","环状网络"]
method_list = ["按度中心性去除","随机去除","按特征向量中心性去除"]
n = 100 #设置网络节点数量
for i in range(len(fun_list)):
fun = fun_list[i]
G = fun(n)
list_all = attack(G)
name = name_list[i]
for j in range(len(list_all)):
method = method_list[j]
ax = plt.subplot(3,3,3*i+j+1)
list_target = list_all[j]
plt.plot(range(1,n),list_target)
ax.set_title(name+":"+method)
ax.set_xlabel("去除点数量")
ax.set_ylabel("最大连通子图点数")
plt.tight_layout()
plt.suptitle("网络攻击模拟")
plt.show()
上述代码实现以下功能:对于星型网络、全连接网络、环状网络分别模拟网络攻击,攻击方式如下:按度中心性攻击、随机攻击、按特征向量中心性攻击。最后绘制结果。