Ejemplo n.º 1
0
def question_4():
    example_network = load_graph(NETWORK_URL)
    er_undirected = er_und.random_undirected_graph(1239, 0.002)
    upa_graph = upa.upa_generator(1239, 3)
    
    er_attack = fast_targeted_order(er_undirected)
    upa_attack = fast_targeted_order(upa_graph)
    network_attack = fast_targeted_order(example_network)
    
    er_resilience = bfs.compute_resilience(er_undirected, er_attack)
    upa_resilience = bfs.compute_resilience(upa_graph, upa_attack)
    network_resilience = bfs.compute_resilience(example_network, network_attack)
    # Create a new figure of size 8x6 points, using 100 dots per inch
    plt.figure(figsize=(8,6), dpi=80)

    # Create a new subplot from a grid of 1x1
    plt.subplot(1,1,1) #parameters: row, column, location index

    plt.xlabel("Number of removed nodes")
    plt.ylabel("Size of the Largest Component")
    plt.title("The Resilience of Different Types of Networks - using Targeted Order")
    # Generate points
    X = [n for n in range(len(er_resilience))]
    # Plot cosine using blue color with a continuous line of width 1 (pixels)
    plt.plot(X, er_resilience, color="blue", linewidth=2.0, linestyle="-", label="ER Graph")

    # Plot sine using green color with a continuous line of width 1 (pixels)
    plt.plot(X, upa_resilience, color="green", linewidth=2.0, linestyle="-", label="UPA Graph")

    plt.plot(X, network_resilience, color="red", linewidth=2.0, linestyle="-", label="Example Network")
    # Add Legends
    plt.legend(loc='upper right', frameon=False)
    # Show result on screen
    plt.show()
Ejemplo n.º 2
0
def question_1():
    # THE CORRECT probability factor p for er_undirected should be 0.002
    # also, I SHOULD HAVE LISTED the values of p and m
    example_network = load_graph(NETWORK_URL)
    er_undirected = er_und.random_undirected_graph(1239, 0.002)
    upa = upa.upa_generator(1239, 3)

    er_attack = random_order(er_undirected)
    upa_attack = random_order(upa)
    network_attack = random_order(example_network)

    er_resilience = bfs.compute_resilience(er_undirected, er_attack)
    upa_resilience = bfs.compute_resilience(upa, upa_attack)
    network_resilience = bfs.compute_resilience(example_network,
                                                network_attack)
    # Create a new figure of size 8x6 points, using 100 dots per inch
    plt.figure(figsize=(10, 6), dpi=80)

    # Create a new subplot from a grid of 1x1
    plt.subplot(1, 1, 1)  #parameters: row, column, location index

    plt.xlabel("Number of removed nodes")
    plt.ylabel("Size of the Largest Component")
    plt.title("The Resilience of Different Types of Networks")
    # Generate points
    X = [n for n in range(len(er_resilience))]
    # Plot cosine using blue color with a continuous line of width 1 (pixels)
    plt.plot(X,
             er_resilience,
             color="blue",
             linewidth=2.0,
             linestyle="-",
             label="ER Graph")

    # Plot sine using green color with a continuous line of width 1 (pixels)
    plt.plot(X,
             upa_resilience,
             color="green",
             linewidth=2.0,
             linestyle="-",
             label="UPA Graph")

    plt.plot(X,
             network_resilience,
             color="red",
             linewidth=2.0,
             linestyle="-",
             label="Example Network")
    # Add Legends
    plt.legend(loc='upper right', frameon=False)
    # Show result on screen
    plt.show()
  def test_compute_resilience(self):
    my_graph = {}
    my_graph[0] = set([1])
    my_graph[1] = set([0, 2])
    my_graph[2] = set([1])
    my_graph[3] = set([4])
    my_graph[4] = set([3])

    self.assertEqual(bfs.compute_resilience(my_graph, [2]), [3, 2])

    my_graph = {}
    my_graph[0] = set([1])
    my_graph[1] = set([0, 2])
    my_graph[2] = set([1])
    my_graph[3] = set([4])
    my_graph[4] = set([3])
    my_graph[5] = set([0, 1, 3, 4])

    self.assertEqual(bfs.compute_resilience(my_graph, [5, 2]), [6, 3, 2])
Ejemplo n.º 4
0
def prepare_plot(graph):
    """
    Takes a graph and function to load graph, calls random_order on graph and then 
    calls compute_resilience and returns the list of largest connected components
    """
    #list_of_nodes = random_order(graph)
    list_of_nodes = fast_targeted_order(graph)
    connected_comps = compute_resilience(graph, list_of_nodes)
    plot = []
    #start_range = len(list_of_nodes)
    for no_of_nodes_removed in range(0, len(list_of_nodes)):
        plot.append([no_of_nodes_removed, connected_comps[no_of_nodes_removed]])
    return plot
def question_1(x_axis_value, is_attack_targeted=False):
    """
    Determine the probability "p" such that the ER graph computed using this
    probability has approximately the same number of edges as the computer
    network ("p" should be consistent with considering each edge in the
    undirected graph exactly once, not twice).

    Likewise, compute an integer "m" such that the number of edges
    in the UPA graph is close to the number of edges in the computer network.

    For each graph, compute a random attack order and use this attack order
    to compute the resilience of the graph. Plot the results  as three curves
    in a single standard plot. Use a line plot for each curve. The x-axis
    is the number of nodes removed while the y-axis is the size of the largest
    connected component.
    """
    network_graph = load_graph_data.load_graph(load_graph_data.NETWORK_URL)
    node_count = len(network_graph)
    edge_count = utility_graph.count_edges(network_graph, False)
    print('The network graph has ' + str(node_count) + ' nodes and ' +
          str(edge_count) + ' edges.')

    probability_connected = 0.004
    er_graph = utility_algorithm.er_algorithm(node_count,
                                              probability_connected, False)
    er_edge_count = utility_graph.count_edges(er_graph, False)
    print('With the probability two nodes are connected equal to ' +
          str(probability_connected) +
          ', this run of the ER graph algorithm resulted in ' +
          str(len(er_graph)) + ' nodes and ' + str(er_edge_count) + ' edges.')

    # Divide average_out_degree by two since this is an undirected graph.
    avg_out_degree = int(
        round(utility_graph.average_out_degree(network_graph) / 2))
    print('Number of existing nodes to which a new node in the UPA graph ' +
          'will be connected is ' + str(avg_out_degree) + '.')

    upa_graph = utility_algorithm.dpa_algorithm(node_count, avg_out_degree,
                                                False)
    print('This run of the UPA algorithm resulted in a graph with ' +
          str(len(upa_graph)) + ' nodes and ' +
          str(utility_graph.count_edges(upa_graph, False)) + ' edges.')

    if (is_attack_targeted):
        network_attack_order = utility_algorithm.fast_targeted_order(
            utility_graph.copy_graph(network_graph))
        er_attack_order = utility_algorithm.fast_targeted_order(
            utility_graph.copy_graph(er_graph))
        upa_attack_order = utility_algorithm.fast_targeted_order(
            utility_graph.copy_graph(upa_graph))
    else:
        network_attack_order = utility_graph.random_order(network_graph)
        er_attack_order = utility_graph.random_order(er_graph)
        upa_attack_order = utility_graph.random_order(upa_graph)

    network_resilience = bfs.compute_resilience(network_graph,
                                                network_attack_order)
    er_resilience = bfs.compute_resilience(er_graph, er_attack_order)
    upa_resilience = bfs.compute_resilience(upa_graph, upa_attack_order)

    if x_axis_value == X_Axis_Value.Nodes_Removed:
        plt.xlabel('Nodes Removed')
        x_axis_values = [idx for idx in xrange(node_count + 1)]
    elif x_axis_value == X_Axis_Value.Nodes_Remaining:
        plt.xlabel('Nodes Remaining')

        # Invert x-axis so it counts down as nodes are removed.
        plt.gca().invert_xaxis()

        x_axis_values = [idx for idx in xrange(node_count + 1, 0, -1)]
    else:
        raise ValueError('X-axis value ', str(x_axis_value),
                         ' does not exist.')

    plt.title('Attack Resiliency')
    plt.ylabel('Largest Connected Component')
    plt.plot(x_axis_values, network_resilience, '-b', label='Network')
    plt.plot(x_axis_values, er_resilience, '-r', label='ER')
    plt.plot(x_axis_values, upa_resilience, '-g', label='UPA')
    plt.legend(loc='upper right')
    plt.show()
Ejemplo n.º 6
0
    for a text representation of the graph
    
    Returns a dictionary that models a graph
    """
    graph_file = urlopen(graph_url)
    graph_text = graph_file.read().decode("utf-8")
    graph_lines = graph_text.split('\n')
    graph_lines = graph_lines[:-1]

    print("Loaded graph with", len(graph_lines), "nodes")

    answer_graph = {}
    for line in graph_lines:
        neighbors = line.split(' ')
        node = int(neighbors[0])
        answer_graph[node] = set([])
        for neighbor in neighbors[1:-1]:
            answer_graph[node].add(int(neighbor))

    return answer_graph


network_graph = load_graph(NETWORK_URL)
#print (func.num_edges(network_graph))

attack_order = func.fast_targeted_order(network_graph)
network_y = bfs.compute_resilience(network_graph, attack_order)
#print(network_y)

#print(bfs.compute_resilience(network_graph, [1346, 1129, 52]))
Ejemplo n.º 7
0
# ER graph where prob of edge is num_edges in provided divided by poss
# prob = 0.003972926209447663
prob = num_edges / nCr(num_nodes, 2)
er_graph = er_algo(num_nodes, prob)
# er_edges = sum(len(value) for value in er_graph.values()) / 2

# UPA graph
upa_graph = algo_upa_graph(1239, 3)  # m = 3 --> ~3,700 edges
# upa_edges = sum(len(value) for value in upa_graph.values()) / 2

# Calculate resilience
attack_order_provided = random_order(provided_graph)
attack_order_er = random_order(er_graph)
attack_order_upa = random_order(upa_graph)

provided_resilience = bfs.compute_resilience(provided_graph,
                                             attack_order_provided)
er_graph_resilience = bfs.compute_resilience(er_graph, attack_order_er)
upa_graph_resilience = bfs.compute_resilience(upa_graph, attack_order_upa)

# Plots
fig = plt.figure('Network Resilience - Random Attack Order (Desktop)')
plt.title('Network Resilience - Random Attack Order (Desktop)')
plt.xlabel('Number of Nodes Removed')
plt.ylabel('Largest Connected Component')

x1 = range(len(provided_resilience))
y1 = provided_resilience

x2 = range(len(er_graph_resilience))
y2 = er_graph_resilience
Ejemplo n.º 8
0
    """
    er_graph = {}
    for num in range(num_nodes):
        er_graph[num] = set()

    # check out itertools to get methods for creating combinations & permutations
    combo_list = list(iter.combinations(range(num_nodes), 2))
    for combo in combo_list:
        # random.random() generates a number between 0 & 1
        rand = random.random()
        if rand < prob:
            er_graph[combo[0]].add(combo[1])
            er_graph[combo[1]].add(combo[0])
    return er_graph


er_graph = er(1239, 0.00397)

# 1239 nodes and need approx 3047 edges for comp network sim. What prob provides this expected val?
#Expected val when probability doesn't change:
#  .5(k-1)(k) * p = expected val
# .5 * 1238 * 1239 * p = exp
# exp / 766941 = p
# exp = num edges
# print( 3047 / 766941 )
# will use .00397 as prob

attack_order = func.fast_targeted_order(er_graph)
er_y = bfs.compute_resilience(er_graph, attack_order)
#print(er_y)
        # make graph undirected
        for neighbor in new_node_neighbors:
            upa_graph[neighbor].add(num)

    return upa_graph

#1239 nodes and approx 3047 edges for comp network sim


# 3047 / 1239 = approx 2.459 edges per node

upa_graph = upa(1239, 3)
#print (func.num_edges(upa_graph))
attack_order = func.fast_targeted_order(upa_graph)

upa_y = bfs.compute_resilience(upa_graph, attack_order)
#print(upa_y)


def run_time_efficiency(num_new_nodes):
    x = []
    fast_y = []
    slow_y = []
    gc.disable()

    for num_nodes in range(10, 1000, 10):
        x.append(num_nodes)
        graph = upa(num_nodes, num_new_nodes)

        start = timeit.default_timer()
        func.fast_targeted_order(graph)