首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何模拟复杂网络中的随机攻击和定向攻击

如何模拟复杂网络中的随机攻击和定向攻击
EN

Stack Overflow用户
提问于 2013-06-27 16:20:57
回答 1查看 2.2K关注 0票数 0
代码语言:javascript
复制
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import networkx as nx
from ComplexNetworkSim import NetworkSimulation, AnimationCreator, PlotCreator


def attack(graph, centrality_metric):
    graph = graph.copy()
    steps = 0
    ranks = centrality_metric(graph)
    nodes = sorted(graph.nodes(), key=lambda n: ranks[n])
    while nx.is_connected(graph):
        graph.remove_node(nodes.pop())
        steps += 1
    else:
        return steps

def random_attack(graph):
    graph = graph.copy()
    steps = 0

    while nx.is_connected(graph):
        node = random.choice(graph.nodes())
        graph.remove_node(node)
        steps += 1
    else:
        return steps

NETWORK_SIZE = 1000
print 'Creating powerlaw cluster with %d Nodes.' % NETWORK_SIZE
K = 4
P = 0.1
HK = nx.powerlaw_cluster_graph(NETWORK_SIZE, K, 0.1)


print 'Starting attacks...'

print 'Network with  Scale-free Model broke after %s steps with random attack.' % (random_attack(HK))
print 'Network with Scale-free Model broke after %s steps with Targeted Attacks.' % (attack(HK, nx.betweenness_centrality))

如何将节点移除模拟为随机攻击和定向攻击?我可以计算网络崩溃之前的总步数,但我想绘制它。

EN

回答 1

Stack Overflow用户

发布于 2013-06-28 17:06:47

在主代码所在的目录中创建一个'sim‘文件夹。添加此函数'save_graph‘并更新'attack’函数。为了获得更好的可视化效果,我尝试了NETWORK_SIZE = 500。结果在所附的gif动画http://www.pictureshack.us/images/6613_myimage.gif

代码语言:javascript
复制
    def save_graph(graph,pos,file_name):
        #initialze Figure
        plt.figure(num=None, figsize=(20, 20), dpi=80)
        plt.axis('off')
        fig = plt.figure(1)
        nx.draw_networkx_nodes(graph,pos)
        nx.draw_networkx_edges(graph,pos)
        nx.draw_networkx_labels(graph,pos)

        cut = 1.00
        xmax = cut * max(xx for xx, yy in pos.values())
        ymax = cut * max(yy for xx, yy in pos.values())
        plt.xlim(0, xmax)
        plt.ylim(0, ymax)

        plt.savefig(file_name,bbox_inches="tight")
        pylab.close()
        del fig

   def attack(graph, centrality_metric):
        graph = graph.copy()
        steps = 0
        ranks = centrality_metric(graph)
        nodes = sorted(graph.nodes(), key=lambda n: ranks[n])

        #Generate spring layout
        pos = nx.spring_layout(graph)

        while nx.is_connected(graph):
             graph.remove_node(nodes.pop())
             file_name = './sim/'+str(steps)+'.png'
             save_graph(graph,pos,file_name)
             steps += 1
       else:
             return steps
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17338146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档