Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import networkx as nx
import numpy as np
import random
import matplotlib.pyplot as plt
def targeted_node_attack(graph, fr):
if fr > 1 or fr < 0:
raise Exception("Fraction of nodes to remove has to be between 0 and 1.")
graph = graph.copy()
size = graph.number_of_nodes()
n = size * fr
nodes = sorted(graph.degree, key=lambda x: x[1], reverse=False)
for i in range(int(n)):
node_to_remove = nodes.pop()
graph.remove_node(node_to_remove[0])
return graph
def random_node_attack(graph, fr):
if fr > 1 or fr < 0:
raise Exception("Fraction of nodes to remove has to be between 0 and 1.")
graph = graph.copy()
size = graph.number_of_nodes()
n = size * fr
for i in range(int(n)):
graph.remove_node(list(graph.nodes)[np.random.randint(0, size)])
size = graph.number_of_nodes()
return graph
def targeted_edge_attack(graph, fr):
"""
Remove edges that connect the nodes with the highest degree and it's neighbour, that has a highest degree
:param graph: netwokx graph
:param fr: fraction of edges to be removed
:return: netwokx graph
"""
if fr > 1 or fr < 0:
raise Exception("Fraction of edges to remove has to be between 0 and 1.")
graph = graph.copy()
size = graph.size()
n = size * fr
for i in range(int(n)):
nodes = sorted(graph.degree, key=lambda x: x[1], reverse=True)
neighbours = list(graph.neighbors(nodes[0][0]))
intersection = [node for node in nodes if node[0] in neighbours and node[0] != nodes[0][0]]
if intersection:
graph.remove_edge(nodes[0][0], intersection[0][0])
return graph
def remove_random_edge(graph):
edges = list(graph.edges)
chosen_edge = random.choice(edges)
graph.remove_edge(chosen_edge[0], chosen_edge[1])
return graph
def random_edge_attack(graph, fr):
"""
Remove random edges
:param graph: netwokx graph
:param fr: fraction of edges to be removed
:return: netwokx graph
"""
if fr > 1 or fr < 0:
raise Exception("Fraction of edges to remove has to be between 0 and 1.")
graph = graph.copy()
size = graph.size()
n = size * fr
graph = remove_random_edge(graph)
# chosen_edge = random.choice(edges)
# edges.remove(chosen_edge)
# graph.remove_edge(chosen_edge[0], chosen_edge[1])
return graph
def targeted_disconned_node(graph, fr):
if fr > 1 or fr < 0:
raise Exception("Fraction of nodes to remove has to be between 0 and 1.")
graph = graph.copy()
size = graph.number_of_nodes()
n = size * fr
nodes = sorted(graph.degree, key=lambda x: x[1], reverse=False)
for i in range(int(n)):
node_to_remove = nodes.pop()
graph = disconnect_node(graph, node_to_remove[0])
return graph
def disconnect_node(graph, node):
neighbors = list(graph.neighbors(node))
while neighbors:
edges = [(node, n) for n in neighbors]
graph.remove_edges_from(edges)
neighbors = list(graph.neighbors(node))
return graph