Saad Memon
Saad Memon

Reputation: 1

How to simulate the random and targeted attacks in Complex network and Python

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

How can I simulate the removal of nodes as random and targeted attacks? I can calculate the total steps until the network break downs but i want to plot it.

Upvotes: 0

Views: 2951

Answers (1)

Vikram
Vikram

Reputation: 1775

Create a folder 'sim' in the directory where the main code. Add this function 'save_graph' and update the 'attack' function. For better visualization I have tried NETWORK_SIZE = 500. The results are in the attached gif animation http://www.pictureshack.us/images/6613_myimage.gif

    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

Upvotes: 0

Related Questions