def main():
    """if len(sys.argv) < 2:
        print('Usage: application2.py <graph.txt>')
        return"""

    network_graph = alg_application2_provided.load_graph(sys.argv[1])
    print('network_grap has %d edges', num_of_edges(network_graph))

    N = len(network_graph)
    p = 0.00171
    # trials = 10
    # print('avg # of edges %d' % avg([num_of_edges(algorithm_er(N, p)) for _ in range(trials)]))
    er_graph = algorithm_er(N, p)
    print('# of edges in er_graph %d' % num_of_edges(er_graph))

    m = 2
    upa_graph = algorithm_upa(N, m)
    print('# of edges in upa_graph %d' % num_of_edges(upa_graph))

    question1(network_graph, er_graph, upa_graph, random_order,
              'random order attack', 'resilience-random.png')

    plt.cla()
    question3('performance.png')

    plt.cla()
    question1(network_graph, er_graph, upa_graph, fast_targeted_order,
              'targeted order attack', 'resilience-targeted.png')
    plt.show()
def load_network_graph():
    '''
    Helper function to load the provided undirected network graph
    '''
    network_graph = provided.load_graph(provided.NETWORK_URL)

    return network_graph
def main():
    if len(sys.argv) < 2:
        print('Usage: application2.py <graph.txt>')
        return

    network_graph = alg_application2_provided.load_graph(sys.argv[1])
    print('network_grap has %d edges', num_of_edges(network_graph))

    N = len(network_graph)
    p = 0.00171
    # trials = 10
    # print('avg # of edges %d' % avg([num_of_edges(algorithm_er(N, p)) for _ in range(trials)]))
    er_graph = algorithm_er(N, p)
    print('# of edges in er_graph %d' % num_of_edges(er_graph))

    m = 2
    upa_graph = algorithm_upa(N, m)
    print('# of edges in upa_graph %d' % num_of_edges(upa_graph))

    question1(network_graph, er_graph, upa_graph, random_order,
              'random order attack', 'pic/1-resilience-random.png')

    plt.cla()
    question3('pic/3-performance.png')

    plt.cla()
    question1(network_graph, er_graph, upa_graph, fast_targeted_order,
              'targeted order attack', 'pic/4-resilience-targeted.png')
    plt.show()
Beispiel #4
0
def ques4_plot():
    """
    Plot an example with two curves with legends
    """
    
    ERGraph = uERAlgo(1239,0.004)
    UPAGraph = UPAalgo(1239,3)
    computer_nw = alg_application2_provided.load_graph(alg_application2_provided.NETWORK_URL)    

    xvals = range(0,1240)

    yvals1 = module2.compute_resilience(ERGraph,alg_application2_provided.targeted_order(ERGraph))
    yvals2 = module2.compute_resilience(UPAGraph,alg_application2_provided.targeted_order(UPAGraph))
    yvals3 = module2.compute_resilience(computer_nw,alg_application2_provided.targeted_order(computer_nw))

    #yvals1 = module2.compute_resilience(ERGraph,fast_targeted_order(ERGraph))
    #yvals2 = module2.compute_resilience(UPAGraph,fast_targeted_order(UPAGraph))
    #yvals3 = module2.compute_resilience(computer_nw,fast_targeted_order(computer_nw))

    
    plt.xlabel("Number of Nodes Removed")
    plt.ylabel("Size of Largest Connected Component")
    plt.title("Size of Largest Connected Component vs Nodes Removed (using Targeted Order)")
    plt.plot(xvals, yvals1, '-g', label='ERGraph n = 1239,p = 0.004')
    plt.plot(xvals, yvals2, '-r', label='UPAGraph n = 1239, m = 3')
    plt.plot(xvals, yvals3, '-b', label='computer network')
    plt.legend(loc='upper right')
    plt.show()

#ques4_plot()
Beispiel #5
0
def question4():
    NETWORK_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_rf7.txt"
    network_graph = app2.load_graph(NETWORK_URL)
    network_idd = prj1.in_degree_distribution(network_graph)
    network_nodes = sum(network_idd.values())
    network_edges = sum([x * y for (x, y) in network_idd.iteritems()]) / 2
    network_prob = float(network_edges) / network_nodes / (network_nodes - 1)
    print "Network_nodes", network_nodes
    print "Network_edges", network_edges
    print "Network_prob", network_prob
    print "Network_m", network_edges / float(network_nodes)

    er_graph = er_makegraph(1347, 0.00172)
    er_idd = prj1.in_degree_distribution(er_graph)
    er_nodes = sum(er_idd.values())
    er_edges = sum([x * y for (x, y) in er_idd.iteritems()]) / 2
    print "ER_nodes", er_nodes
    print "ER_edges", er_edges

    upa_graph = upa_makegraph(1347, 2)
    upa_idd = prj1.in_degree_distribution(upa_graph)
    upa_nodes = sum(upa_idd.values())
    upa_edges = sum([x * y for (x, y) in upa_idd.iteritems()]) / 2
    print "UPA_nodes", upa_nodes
    print "UPA_edges", upa_edges

    network_resilience = prj2.compute_resilience(
        network_graph, fast_targeted_order(network_graph))
    er_resilience = prj2.compute_resilience(er_graph,
                                            fast_targeted_order(er_graph))
    upa_resilience = prj2.compute_resilience(upa_graph,
                                             fast_targeted_order(upa_graph))

    plt.plot(range(len(network_resilience)),
             network_resilience,
             '-r',
             label='Network graph')
    plt.plot(range(len(er_resilience)),
             er_resilience,
             '-b',
             label='ER-generated (p = 0.00172)')
    plt.plot(range(len(upa_resilience)),
             upa_resilience,
             '-g',
             label='UPA-generated (m = 2)')
    plt.title('Comparison of Networks Resilience')
    plt.ylabel('Size of the largest connected component')
    plt.xlabel('Number of nodes removed')
    plt.legend()
    plt.show()


#question4()
def question4_plot():
    """
    Loads the three graphs in the problem, calculates a sequence of targeted
    attacks using fast_targeted_attack and calculates the resilience of each 
    graph based on this attack. Plots the results.
    """

    # Loading the provided computer network example
    example_graph = graph_provided.load_graph(NETWORK_URL)

    # Creating a random ER graph with 1239 nodes and p = .004
    er_graph = make_random_ugraph(1239, .004)

    # Creating an UPA graph, m=12
    upa_graph = mod_upa.create_UPA_graph(1239, 2)

    # Calculating attack sequences with the provided targeted_order
    #example_attack = graph_provided.targeted_order(example_graph)
    #er_attack = graph_provided.targeted_order(er_graph)
    #upa_attack = graph_provided.targeted_order(upa_graph)

    # Calculating attack sequences with fast_targeted_order
    example_attack = fast_targeted_order(example_graph)
    er_attack = fast_targeted_order(er_graph)
    upa_attack = fast_targeted_order(upa_graph)

    # Calculating resilience
    example_resilience = mod_resilience.compute_resilience(example_graph, 
                                                           example_attack)
    er_resilience = mod_resilience.compute_resilience(er_graph, 
                                                      er_attack)
    upa_resilience = mod_resilience.compute_resilience(upa_graph, 
                                                       upa_attack)

    # Plotting the outcome 
    xvals = range(1240)

    plt.plot(xvals, example_resilience, '-c', 
             label='computer network example (provided)')
    plt.plot(xvals, er_resilience, '-y', 
             label='generated ER graph (p = .004)')
    plt.plot(xvals, upa_resilience, '-m', 
             label='generated UPA graph (m = 2)')
    plt.legend(loc='upper right')
    plt.title('Graphs resilience to targeted attack')
    plt.xlabel('Nodes removed')
    plt.ylabel('Biggest connected element size')
    plt.show()
Beispiel #7
0
def legend_example():
    """
    Plot an example with two curves with legends
    """
    
    ERGraph = uERAlgo(1239,0.004)
    UPAGraph = UPAalgo(1239,3)
    computer_nw = alg_application2_provided.load_graph(alg_application2_provided.NETWORK_URL)

    print countedges(ERGraph)
    print countedges(UPAGraph)
    print countedges(computer_nw)

    #deg_dict = compute_degrees(computer_nw)
    #total_deg = (sum(x for x in deg_dict.values()))/1239
    #print total_deg
    xvals = range(0,1240)

    yvals1 = module2.compute_resilience(ERGraph,random_order(ERGraph))
    yvals2 = module2.compute_resilience(UPAGraph,random_order(UPAGraph))
    yvals3 = module2.compute_resilience(computer_nw,random_order(computer_nw))

    #yvals1 = module2.compute_resilience(ERGraph,alg_application2_provided.targeted_order(ERGraph))
    #yvals2 = module2.compute_resilience(UPAGraph,alg_application2_provided.targeted_order(UPAGraph))
    #yvals3 = module2.compute_resilience(computer_nw,alg_application2_provided.targeted_order(computer_nw))

    #yvals1 = module2.compute_resilience(ERGraph,fast_targeted_order(ERGraph))
    #yvals2 = module2.compute_resilience(UPAGraph,fast_targeted_order(UPAGraph))
    #yvals3 = module2.compute_resilience(computer_nw,fast_targeted_order(computer_nw))

    print len(yvals1)
    print len(yvals2)
    print len(yvals3)

       
    plt.xlabel("Number of Nodes Removed")
    plt.ylabel("Size of Largest Connected Component")
    plt.title("Size of Largest Connected Component vs Nodes Removed")
    plt.plot(xvals, yvals1, '-g', label='ERGraph n = 1239,p = 0.004')
    plt.plot(xvals, yvals2, '-r', label='UPAGraph n = 1239, m = 3')
    plt.plot(xvals, yvals3, '-b', label='computer network')
    plt.legend(loc='upper right')
    plt.show()
Beispiel #8
0
def question4():
    NETWORK_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_rf7.txt"
    network_graph = app2.load_graph(NETWORK_URL)
    network_idd = prj1.in_degree_distribution(network_graph)
    network_nodes = sum(network_idd.values())
    network_edges = sum([x * y for (x, y) in network_idd.iteritems()]) / 2
    network_prob = float(network_edges) / network_nodes / (network_nodes - 1)
    print "Network_nodes", network_nodes
    print "Network_edges", network_edges
    print "Network_prob", network_prob
    print "Network_m", network_edges  /float(network_nodes)

    er_graph = er_makegraph(1347, 0.00172)
    er_idd = prj1.in_degree_distribution(er_graph)
    er_nodes = sum(er_idd.values())
    er_edges = sum([x * y for (x, y) in er_idd.iteritems()]) / 2
    print "ER_nodes", er_nodes
    print "ER_edges", er_edges

    upa_graph = upa_makegraph(1347, 2)
    upa_idd = prj1.in_degree_distribution(upa_graph)
    upa_nodes = sum(upa_idd.values())
    upa_edges = sum([x * y for (x, y) in upa_idd.iteritems()]) / 2
    print "UPA_nodes", upa_nodes
    print "UPA_edges", upa_edges

    network_resilience = prj2.compute_resilience(network_graph, fast_targeted_order(network_graph))
    er_resilience = prj2.compute_resilience(er_graph, fast_targeted_order(er_graph))
    upa_resilience = prj2.compute_resilience(upa_graph, fast_targeted_order(upa_graph))

    plt.plot(range(len(network_resilience)), network_resilience, '-r', label='Network graph')
    plt.plot(range(len(er_resilience)), er_resilience, '-b', label='ER-generated (p = 0.00172)')
    plt.plot(range(len(upa_resilience)), upa_resilience, '-g', label='UPA-generated (m = 2)')
    plt.title('Comparison of Networks Resilience')
    plt.ylabel('Size of the largest connected component')
    plt.xlabel('Number of nodes removed')
    plt.legend()
    plt.show()

#question4()
def Question4():
	n = 1239
	xvals = range(n+1)
	UPA_graph = UPA_generator(2,n)
	ER_graph = make_ER_graph_2(n,.0034)
	CN_graph = alg_application2_provided.load_graph(NETWORK_URL)
	UPA_fast_order = alg_application2_provided.fast_targeted_order(UPA_graph)
	ER_fast_order = alg_application2_provided.fast_targeted_order(ER_graph)
	CN_fast_order = alg_application2_provided.fast_targeted_order(CN_graph)
	UPA_resilience = module2_project.compute_resilience(UPA_graph, UPA_fast_order)
	ER_resilience = module2_project.compute_resilience(ER_graph, ER_fast_order)
	CN_resilience = module2_project.compute_resilience(CN_graph, CN_fast_order)
	yvals1 = UPA_resilience
	yvals2 = ER_resilience
	yvals3 = CN_resilience
	plt.plot(xvals, yvals1, '-b', label='UPA_resilience m = 2')
	plt.plot(xvals, yvals2, '-r', label='ER_resilience, p = .0034')
	plt.plot(xvals, yvals3, '-g', label='ComputerNetworkGraph_resilience')
	plt.legend(loc='upper right')
	plt.title('plot of resilience of three graphs ')  
	plt.xlabel('number of removed nodes')  
	plt.ylabel('size of the largest connected component')  
	plt.show()
def Question4():
    n = 1239
    xvals = range(n + 1)
    UPA_graph = UPA_generator(2, n)
    ER_graph = make_ER_graph_2(n, .0034)
    CN_graph = alg_application2_provided.load_graph(NETWORK_URL)
    UPA_fast_order = alg_application2_provided.fast_targeted_order(UPA_graph)
    ER_fast_order = alg_application2_provided.fast_targeted_order(ER_graph)
    CN_fast_order = alg_application2_provided.fast_targeted_order(CN_graph)
    UPA_resilience = module2_project.compute_resilience(
        UPA_graph, UPA_fast_order)
    ER_resilience = module2_project.compute_resilience(ER_graph, ER_fast_order)
    CN_resilience = module2_project.compute_resilience(CN_graph, CN_fast_order)
    yvals1 = UPA_resilience
    yvals2 = ER_resilience
    yvals3 = CN_resilience
    plt.plot(xvals, yvals1, '-b', label='UPA_resilience m = 2')
    plt.plot(xvals, yvals2, '-r', label='ER_resilience, p = .0034')
    plt.plot(xvals, yvals3, '-g', label='ComputerNetworkGraph_resilience')
    plt.legend(loc='upper right')
    plt.title('plot of resilience of three graphs ')
    plt.xlabel('number of removed nodes')
    plt.ylabel('size of the largest connected component')
    plt.show()
    return output_graph

def random_order(ugraph):
    """
    :param ugraph: input an undisrected graph
    :return: a list of nodes in the graph in some random order
    """
    random_nodes_list = []
    for node in ugraph.keys():
        random_nodes_list.append(node)
    random.shuffle(random_nodes_list)

    return random_nodes_list

#graph of computer network
cn_graph = aa2p.load_graph(aa2p.NETWORK_URL)
print edges_in_undirected_graph(cn_graph)

#graph of ER
er_graph = er_algorithm(len(cn_graph.keys()), 0.002)
#print er_graph
print edges_in_undirected_graph(er_graph)

#graph of UPA
upa_graph = get_upa_graph(len(cn_graph.keys()), 2)
print edges_in_undirected_graph(upa_graph)

#random attack
cn_attack_order = random_order(cn_graph)
er_attack_order = random_order(er_graph)
upa_attack_order = random_order(upa_graph)
def load_network_graph():
    graph_url = '/home/novneet/PycharmProjects/AlgoThinking1/week2/application/res/alg_rf7.txt'
    network_graph = alg2.load_graph(graph_url)
    return network_graph
Beispiel #13
0
def load_network_graph():
    graph_url = '/home/novneet/PycharmProjects/AlgoThinking1/week2/application/res/alg_rf7.txt'
    network_graph = alg2.load_graph(graph_url)
    return network_graph
'''

Algorithmic Thinking (part1), programming application  2, question 5
Connected components and graph resilience,
https://class.coursera.org/algorithmicthink1-003/human_grading/view/courses/975649/assessments/32/submissions
Author: Sakari Hakala

'''

import alg_application2_provided as provided
import matplotlib.pyplot as plt
import algo_pa2 as pa2
import algo_app2_1 as app2

cn = provided.load_graph(provided.NETWORK_URL)
upa = app2.create_UPA(1239, 2)
uer = app2.undirected_ER(1239, 0.004)

order_cn = app2.fastTargetedOrder(cn)
order_upa = app2.fastTargetedOrder(upa)
order_uer = app2.fastTargetedOrder(uer)

resillience_cn = pa2.compute_resilience(cn, order_cn)
resillience_upa = pa2.compute_resilience(upa, order_upa)
resillience_uer = pa2.compute_resilience(uer, order_uer)

plt.plot(resillience_cn, '-b', label='Provided computer network')
plt.plot(resillience_upa, '-r', label='UPA graph, m = 2')
plt.plot(resillience_uer, '-g', label='uER graph, p = 0.004')
plt.title('Graph resillience under targeted attack')
plt.xlabel('Number of nodes attacked')
#n=10
#m=2
#print [graph_size(UPA_generator(m,n), n) for _ in np.arange(20)]

NETWORK_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_rf7.txt"

import matplotlib.pyplot as plt

t0 = time.clock()

n = 1239
xvals = range(n+1)
UPA_graph = UPA_generator(2,n)
ER_graph = make_ER_graph_2(n,.0034)
CN_graph = alg_application2_provided.load_graph(NETWORK_URL)
UPA_resilience = module2_project.compute_resilience(UPA_graph, random_order(UPA_graph))
ER_resilience = module2_project.compute_resilience(ER_graph, random_order(ER_graph))
CN_resilience = module2_project.compute_resilience(CN_graph, random_order(CN_graph))
yvals1 = UPA_resilience
yvals2 = ER_resilience
yvals3 = CN_resilience
plt.plot(xvals, yvals1, '-b', label='UPA_resilience m = 2')
plt.plot(xvals, yvals2, '-r', label='ER_resilience, p = .0034')
plt.plot(xvals, yvals3, '-g', label='ComputerNetworkGraph_resilience')
plt.legend(loc='upper right')
plt.title('plot of resilience of three graphs ')  
plt.xlabel('number of removed nodes')  
plt.ylabel('size of the largest connected component')  
plt.show()
plt.savefig('q2_1.png')
            attack_list.append(u_node)
            degree_sets[k_degree].remove(u_node)
            for v_neighbor in ugraph[u_node]:
                v_degree = len(ugraph[v_neighbor])
                degree_sets[v_degree].remove(v_neighbor)
                degree_sets[v_degree - 1].add(v_neighbor)
            graph_provided.delete_node(graph, u_node)
            index += 1
    
    return attack_list

# Tests for fast_targeted_order
#my_graph = mod_upa.create_UPA_graph(10, 3)
#print 'my graph = ' + str(my_graph)
#print 'provided attack order = ' + str(graph_provided.targeted_order(my_graph)) 
my_graph = graph_provided.load_graph(NETWORK_URL)
attack = fast_targeted_order(my_graph)
resilience = mod_resilience.compute_resilience(my_graph, attack)

def question3_plot():
    """
    Calculates a series of targeted attacks using both functions (provided and
    the fast targeted implemented one), computes the running time of these 
    processes and plots the outcome
    """
    # Initializing the data series
    xvals = range(10 , 1000, 10)
    targeted_times = []
    fast_targeted_times = []
    
    for size in range(10, 1000, 10):