def question2(file_to_save = None):
    '''

    :param INPUT_FILE:
    :return:
    '''
    nodes = 1238
    # x_coordinate = range((nodes+1)/5)
    x_coordinate = range(248)
    cgraph = load_graph_file(INPUT_FILE)
    #cgraph = load_graph_url(NETWORK_URL)
    cattack = random_order(cgraph)
    print "cattack order", cattack
    cgraph_res = project2.compute_resilience(cgraph, random_order(cgraph)[:(nodes+1)/5])
    print "cgraph_res", len(cgraph_res), cgraph_res[-1]
    dgraph = re_algorithm(nodes, 0.0039)
    dgraph_res = project2.compute_resilience(dgraph, random_order(dgraph)[:(nodes+1)/5])
    print "dgraph_res", len(dgraph_res), dgraph_res[-1]
    print "x_coordinate", len(x_coordinate)
    ugraph = upa_algorithm(nodes, 3)
    ugraph_res = project2.compute_resilience(ugraph, random_order(ugraph)[:(nodes+1)/5])
    print "ugraph_res", len(ugraph_res), ugraph_res[-1]

    plot.plot(x_coordinate, cgraph_res, '-r', label='Compute network')
    plot.plot(x_coordinate, dgraph_res, '-g', label='ER graph, p=0.0039')
    plot.plot(x_coordinate, ugraph_res, '-y', label='UPA graph, m=3')

    plot.title('Comparison of graph resilience for random attack order')
    plot.xlabel('Number of nodes removed')
    plot.ylabel('Size of largest connected component')
    plot.legend(loc='upper right')
    plot.tight_layout()
    if file_to_save:
        plot.savefig(file_to_save)
def q1():
	#network graph
	nework_graph = provided.load_graph_local('computer_network.txt')
	order_list1 = random_order(nework_graph)
	resilience1 = project2.compute_resilience(nework_graph, order_list1)
	print 'finish graph1'
	#uer graph
	uer_graph = UER(NODE_COUNT, 0.003999)
	order_list2 = random_order(uer_graph)
	resilience2 = project2.compute_resilience(uer_graph, order_list2)
	print 'finish graph2'
	#upa graph
	upa_graph = UPA(NODE_COUNT, 3)
	order_list3 = random_order(upa_graph)
	resilience3 = project2.compute_resilience(upa_graph, order_list3)
	print 'finish graph3'
	
	plt.title('Comparision of graph resilience for random attack order')
	plt.xlabel('Number of nodes removed')
 	plt.ylabel('Size of largest connected component')
 	line1, = plt.plot(resilience1,'b') 
	line2, =plt.plot(resilience2,'g') 
	line3, = plt.plot(resilience3,'r') 
 
	plt.legend((line1, line2, line3), ('Computer network', 'ER graph, p = 0.003999', 'UPA graph, m = 3'))
	plt.show()
def question_4():
    '''
    Using targeted_order (or fast_targeted_order), your task is to compute a 
    targeted attack order for each of the three graphs (computer network, ER, 
    UPA) from Question 1. Then, for each of these three graphs, compute the 
    resilience of the graph using compute_resilience. Finally, plot the 
    computed resiliences as three curves (line plots) in a single standard 
    plot. As in Question 1, please include a legend in your plot that 
    distinguishes the three plots. The text labels in this legend should 
    include the values for p and m that you used in computing the ER and UPA 
    graphs, respectively.
    '''

    # set constants to make the three graphs the same num nodes and edges
    num_nodes = 1239
    p = .004
    m = 2

    # create the three graphs
    network = load_network_graph()
    er_graph = make_er_graph(num_nodes, p)
    upa_graph = upa(num_nodes, m)

    # set the order of node attacks
    network_attack = provided.targeted_order(network)
    er_attack = provided.targeted_order(er_graph)
    upa_attack = provided.targeted_order(upa_graph)

    # compute resilience of each network
    network_resilience = project2.compute_resilience(network, network_attack)
    er_resilience = project2.compute_resilience(er_graph, er_attack)
    upa_resilience = project2.compute_resilience(upa_graph, upa_attack)

    # plot results
    plt.plot(network_resilience, 'b-', label='Computer network')
    plt.plot(er_resilience, 'g-', label='ER graph, p=0.004')
    plt.plot(upa_resilience, 'r-', label='UPA graph, m=2')
    plt.legend(loc='upper right')

    plt.title('Resilience of networks under a targeted attack')
    plt.xlabel('Number of nodes removed')
    plt.ylabel('Size of the largest connected component')
    plt.show()

    return


#question_1()
#question_3()
#question_4()

# Testing
#print make_er_graph(10, .1)
#print random_order({0: set([4]), 1: set([8, 4]), 2: set([]), 3: set([8]), 4: set([0, 1, 9]), 5: set([8]), 6: set([]), 7: set([]), 8: set([1, 3, 5]), 9: set([4])})
def question1_plot():
    """
    plot for question 1
    """
    network_graph = load_graph(NETWORK_URL)
    n = 1239
    p = 0.004
    m = 3
    er_graph = er(n, 0.004)
    upa_graph = upa(n, 3)

    graphs = [network_graph, er_graph, upa_graph]
    attack_orders = [random_order(graph) for graph in graphs]

    resiliences = [compute_resilience(graph, attack_order) for
                   graph, attack_order in zip(graphs, attack_orders)]

    removed_num = range(n + 1)
    for resil in resiliences:
        plt.plot(removed_num, resil)
    legend_text = ['Computer Network', 'ER Graph, p = %.3f' % (p),
                   'UPA Graph, m = %d' % (m)]
    plt.legend(legend_text, loc="upper right")
    plt.xlabel('the number of nodes removed')
    plt.ylabel('the size of the largest connect component')
    plt.title('Graph resiliences')
    plt.show()
def question1(network, er, upa, order_func, order_label, filename):
    N = len(network)
    order = order_func(network)
    network_res = project2.compute_resilience(network, order)
    er_res = project2.compute_resilience(er, order)
    upa_res = project2.compute_resilience(upa, order)

    xs = range(N + 1)
    plt.plot(xs, network_res, '-r', label='Network graph')
    plt.plot(xs, er_res, '-b', label='ER-generated (p = 0.00171)')
    plt.plot(xs, upa_res, '-g', label='UPA-generated (m = 2)')
    plt.title('Graph resilience (%s)' % order_label)
    plt.xlabel('Number of nodes removed')
    plt.ylabel('Size of the largest connected component')
    plt.legend(loc='upper right')
    plt.tight_layout()
    plt.savefig(filename)
    print('Saved plot to %s' % filename)
    plt.show()
def q4():
	#network graph
	nework_graph = provided.load_graph_local('computer_network.txt')
	order_list1 = provided.targeted_order(nework_graph)
	resilience1 = project2.compute_resilience(nework_graph, order_list1)
	print 'finish graph1'
	#uer graph
	uer_graph = UER(NODE_COUNT, 0.003999)
	order_list2 = provided.targeted_order(uer_graph)
	resilience2 = project2.compute_resilience(uer_graph, order_list2)
	print 'finish graph2'
	#upa graph
	upa_graph = UPA(NODE_COUNT, 3)
	order_list3 = provided.targeted_order(upa_graph)
	resilience3 = project2.compute_resilience(upa_graph, order_list3)
	print 'finish graph3'
	
	plt.xlabel('Number of nodes removed')
 	plt.ylabel('Size of largest connected component')
 	plt.title('Comparision of graph resilience for targed attack order')


	line1, = plt.plot(resilience1,'b') 
	line2, = plt.plot(resilience2,'g') 
	line3, = plt.plot(resilience3,'r') 
	plt.legend((line1, line2, line3), ('Computer network', 'ER graph, p = 0.003999', 'UPA graph, m = 3'))
	
	plt.show()


#test cases
#print UER(5, 0.5)
#print UPA(10, 5)
#determine_p() p = 0.003999
#determine_m() m = 3
#print fast_targeted_order(graphs.GRAPH10)


#questions
#q1()
#compare_two_order_function()
#q4()
def question1and2():
    global CN_GRAPH, ER_GRAPH, UPA_GRAPH
    attacked_cn  = project2.compute_resilience(CN_GRAPH, random_order(CN_GRAPH))
    attacked_er  = project2.compute_resilience(ER_GRAPH, random_order(ER_GRAPH))    
    attacked_upa = project2.compute_resilience(UPA_GRAPH, random_order(UPA_GRAPH))   

    plt.plot(attacked_cn, 'b-', label='Computer Graph')
    plt.plot(attacked_er, 'g-', label='ER graph [p=0.002]')
    plt.plot(attacked_upa, 'r-', label='UPA graph [m=2]')
    plt.legend(loc='upper right')

    plt.title('Resilience of networks under a random attack');
    plt.xlabel('# nodes removed')
    plt.ylabel('Largest connected component')
    plt.show()
    plt.close

    print test_resilient(attacked_cn)
    print test_resilient(attacked_er)
    print test_resilient(attacked_upa)
def question4(file_to_save = None, type_target_order = None):
    '''

    :param INPUT_FILE:
    :return:
    '''
    nodes = 1238
    x_coordinate = range(nodes+1)
    cgraph = load_graph_file(INPUT_FILE)
    #cgraph = load_graph_url(NETWORK_URL)
    dgraph = re_algorithm(nodes, 0.0039)
    ugraph = upa_algorithm(nodes, 3)
    if not type_target_order:
        cattack = targeted_order(cgraph)
        dattack = targeted_order(dgraph)
        uattack = targeted_order(ugraph)
    elif type_target_order:
        cattack = fast_targeted_order(cgraph)
        dattack = fast_targeted_order(dgraph)
        uattack = fast_targeted_order(ugraph)
    print "cattack order", cattack
    cgraph_res = project2.compute_resilience(cgraph, cattack)
    print "cgraph_res", len(cgraph_res)
    dgraph_res = project2.compute_resilience(dgraph, dattack)
    print "dgraph_res", len(dgraph_res)
    ugraph_res = project2.compute_resilience(ugraph, uattack)
    print "ugraph_res", len(ugraph_res)

    plot.plot(range(len(cgraph_res)), cgraph_res, '-r', label='Compute network')
    plot.plot(range(len(dgraph_res)), dgraph_res, '-g', label='ER graph, p=0.0039')
    plot.plot(range(len(ugraph_res)), ugraph_res, '-y', label='UPA graph, m=3')

    plot.title('Comparison of graph resilience for random attack order')
    plot.xlabel('Number of nodes removed')
    plot.ylabel('Size of largest connected component')
    plot.legend(loc='upper right')
    plot.tight_layout()
    if file_to_save:
        plot.savefig(file_to_save)
    plot.clf()
def question_1():
    '''
    To begin our analysis, we will examine the resilience of the computer 
    network under an attack in which servers are chosen at random. We will 
    then compare the resilience of the network to the resilience of ER and UPA 
    graphs of similar size.
    '''

    # set constants to make the three graphs the same num nodes and edges
    num_nodes = 1239
    p = .004
    m = 2

    # create the three graphs
    network = load_network_graph()
    er_graph = make_er_graph(num_nodes, p)
    upa_graph = upa(num_nodes, m)

    # set the order of node attacks
    network_attack = random_order(network)
    er_attack = random_order(er_graph)
    upa_attack = random_order(upa_graph)

    # compute resilience of each network
    network_resilience = project2.compute_resilience(network, network_attack)
    er_resilience = project2.compute_resilience(er_graph, er_attack)
    upa_resilience = project2.compute_resilience(upa_graph, upa_attack)

    # plot results
    plt.plot(network_resilience, 'b-', label='Computer network')
    plt.plot(er_resilience, 'r-', label='ER graph, p=0.004')
    plt.plot(upa_resilience, 'g-', label='UPA graph, m=2')
    plt.legend(loc='upper right')

    plt.title('Resilience of networks under a random attack')
    plt.xlabel('Number of nodes removed')
    plt.ylabel('Size of the largest connected component')
    plt.show()

    return
def print_compute_resilience(graph, order_func=random_order, style="-b", label="default"):
    print_gi(graph)
    num_nodes = len(graph)
    attack = order_func(graph)
    cr = proj.compute_resilience(graph, attack)
    cx = range(num_nodes + 1)
    print "------------"
    print label
    print "Random Nodes:", attack
    print "Y:", cr
    print "X:", cx
    plt.plot(cx, cr, style, label=label)
    # cx = range(num_nodes)
    # percent_cc_vs_rem_nodes = [(cr[i] * 1.0)/(num_nodes - i) for i in cx]
    # print percent_cc_vs_rem_nodes
    # plt.plot(cx, percent_cc_vs_rem_nodes, style, label=label)
    plt.scatter([0.2 * num_nodes], [0], 50, color="black")
# Generate Graphs
COMPUTERNETWORK = load_graph(NETWORK_URL)
# sum(map(len, COMPUTERNETWORK.values()))/2
# average(map(len, COMPUTERNETWORK.values()))
PROB = 0.00171*3
NODES_NUM = 1347
ER_UNDI_GRAPH = generate_rand_undigraph_er(NODES_NUM, PROB)
# sum(map(len, ER_UNDI_GRAPH.values()))/2
UPA_GRAPH = upa_undigraph_gen(1347, 3)
# sum(map(len, UPA_GRAPH.values()))/2

# generate random order
ORDER_CN = get_random_order(COMPUTERNETWORK)
ORDER_ER = get_random_order(ER_UNDI_GRAPH)
ORDER_UPA = get_random_order(UPA_GRAPH)

# Q1
CN_RE = compute_resilience(COMPUTERNETWORK, ORDER_CN)
ER_RE = compute_resilience(ER_UNDI_GRAPH, ORDER_ER)
UPA_RE = compute_resilience(ER_UNDI_GRAPH, ORDER_ER)

RESILIENCE_DF = pd.DataFrame(
    {'COMPUTERNETWORK': CN_RE, 'ER_GRAPH(p=0.00513)': ER_RE,
    'UPA_GRAPH(m=3)':UPA_RE, 'nodes_removed': range(1348)})
RESILIENCE_DF_R = pd.melt(RESILIENCE_DF, id_vars=['nodes_removed'], 
    value_vars=['COMPUTERNETWORK', 'ER_GRAPH(p=0.00513)', 'UPA_GRAPH(m=3)'],
    var_name='graph_type', value_name='size_of_the_largest_connect_component')

print ggplot(RESILIENCE_DF_R, aes(y='size_of_the_largest_connect_component', x='nodes_removed', color='graph_type')) + \
            geom_point() +\
            ggtitle("The resilience of three graphs")
 def test_resilience(self):
     self.assertEqual(compute_resilience(self.GRAPH1, range(10)),
                      [6, 5, 4, 3, 3, 3, 3, 2, 1, 1, 0])
     self.assertEqual(compute_resilience(self.GRAPH2, [1,4,5]),
                      [4, 2, 2, 2])