Пример #1
0
def get_run_time(nlist, mlist, graphfun):
    '''
    calculate time spend
    '''
    time_spend = []
    for node_num in nlist:
        for step in mlist:
            ugraph = graphfun(node_num, step)
            to_start = time.time()
            targeted_order(ugraph)
            to_end = time.time()
            to_time_spend = to_end - to_start
            time_spend.append({
                'n': node_num, 'm': step, 'type': 'targeted order',
                'time spend': to_time_spend
                })
            fto_start = time.time()
            fast_targeted_order(ugraph)
            fto_end = time.time()
            fto_time_spend = fto_end - fto_start
            time_spend.append({
                'n': node_num, 'm': step, 'type': 'fast targeted order',
                'time spend': fto_time_spend
                })
    return time_spend
Пример #2
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()
def compare_two_order_function():

	m = 5

	fast_order_time = list()
	order_time = list()

	for n in range(10, 1000, 10):
		upa = UPA(n, m)

		start_time = time.time()
		fast_targeted_order(upa)
		end_time = time.time()
		fast_order_time.append(end_time - start_time)

		start_time = time.time()
		provided.targeted_order(upa)
		end_time = time.time()
		order_time.append(end_time - start_time)

	plt.title('Regular vs. fast computation of targeted order')
	plt.xlabel('Size of UPA graph, m = 5')
	plt.ylabel('Running time in seconds')
	line1, = plt.plot(range(10, 1000, 10), fast_order_time,'g') 
	line2, = plt.plot(range(10, 1000, 10), order_time,'b') 
	plt.legend((line1, line2), ('fast_targeted_order', 'targeted_order'))
	
	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])})
Пример #5
0
def Question3():
	wynik = list()
	for step in range(10, 1000, 10):
		start = time.clock()
		UPA_graph = UPA_generator(5,step)
		UPA_fast_order = alg_application2_provided.fast_targeted_order(UPA_graph)
		stop = time.clock()
		wynik.append(stop-start)
	xvals = range(10, 1000, 10)
	yvals1 = wynik
	wynik = list()
	for step in range(10, 1000, 10):
		start = time.clock()
		UPA_graph = UPA_generator(5,step)
		UPA_fast_order = alg_application2_provided.targeted_order(UPA_graph)
		stop = time.clock()
		wynik.append(stop-start)
	xvals = range(10, 1000, 10)
	yvals2 = wynik
	#yvals = [1000*item for item in wynik]
	plt.plot(xvals, yvals1, '-b', label='fast_targeted_order')
	plt.plot(xvals, yvals2, '-r', label='targeted_order')
	plt.legend(loc='upper right')
	plt.title('desktop Python time plotting')  
	plt.xlabel('number of nodes')  
	plt.ylabel('time')  
	plt.show()
Пример #6
0
def Question3():
    wynik = list()
    for step in range(10, 1000, 10):
        start = time.clock()
        UPA_graph = UPA_generator(5, step)
        UPA_fast_order = alg_application2_provided.fast_targeted_order(
            UPA_graph)
        stop = time.clock()
        wynik.append(stop - start)
    xvals = range(10, 1000, 10)
    yvals1 = wynik
    wynik = list()
    for step in range(10, 1000, 10):
        start = time.clock()
        UPA_graph = UPA_generator(5, step)
        UPA_fast_order = alg_application2_provided.targeted_order(UPA_graph)
        stop = time.clock()
        wynik.append(stop - start)
    xvals = range(10, 1000, 10)
    yvals2 = wynik
    #yvals = [1000*item for item in wynik]
    plt.plot(xvals, yvals1, '-b', label='fast_targeted_order')
    plt.plot(xvals, yvals2, '-r', label='targeted_order')
    plt.legend(loc='upper right')
    plt.title('desktop Python time plotting')
    plt.xlabel('number of nodes')
    plt.ylabel('time')
    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 running_time_best():
    '''
    Helper function for Question 3
    '''

    running_times_norm = []
    running_times_fast = []
    for n in range(10, 1000, 10):
        upa_graph = upa(n, 5)
        start = time.clock()
        provided.targeted_order(upa_graph)
        stop = time.clock()
        elapsed_time = stop - start
        running_times_norm.append(elapsed_time)
        start = time.clock()
        fast_targeted_order(upa_graph)
        stop = time.clock()
        elapsed_time = stop - start
        running_times_fast.append(elapsed_time)

    return running_times_norm, running_times_fast
Пример #9
0
def ques3_plot():
    """
    Plot an example with two curves with legends
    """
    target_order = []
    fast_target_order = []

    m = 5
    for n in range(10,1000,10):
        UPAGraph = UPAalgo(n,m)
        start_time = time.time()
        alg_application2_provided.targeted_order(UPAGraph)
        end_time = time.time()
                
        target_order.append(end_time - start_time)

        start_time2 = time.time()
        fast_targeted_order(UPAGraph)
        end_time2 = time.time()
                
        fast_target_order.append(end_time2 - start_time2)

    #print target_order
    #print fast_target_order

    xvals = range(10,1000,10)

    yvals1 = target_order 
    yvals2 = fast_target_order
        
    plt.ylabel("Running times")
    plt.xlabel("No. of Nodes")
    plt.title("Running time vs No. of nodes for UPA graph(Desktop Python)")
    plt.plot(xvals, yvals1, 'b.-', label='Target Order')
    plt.plot(xvals, yvals2, 'r.-', label='Fast Target Order')
    
    plt.legend(loc='upper left')
    plt.show()
Пример #10
0
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):
        upa_graph = mod_upa.create_UPA_graph(size, 5)
        
        # Calculating the running time of targeted_attack for this iteration
        start_clock = time.clock()
        graph_provided.targeted_order(upa_graph)
        end_clock = time.clock() - start_clock
        targeted_times.append(end_clock * 1000)
        
        # Calculating the running time of fast_targeted_attack for this iteration
        start_clock = time.clock()
        fast_targeted_order(upa_graph)
        end_clock = time.clock() - start_clock
        fast_targeted_times.append(end_clock * 1000)
        
    # Plotting the outcome 
    plt.plot(xvals, targeted_times, '-c', 
             label='targeted_order times (O(n**2))')
    plt.plot(xvals, fast_targeted_times, '-y', 
             label='fast_targeted_order times (O(n))')
    plt.legend(loc='upper left')
    plt.title('Processing times to calculate attacks (desktop Python)')
    plt.ylabel('Running time (milliseconds)')
    plt.xlabel('Graph size')
    plt.show()
Пример #11
0
def question3():
    running_time = []
    fast_running_time = []
    rng = range(10, 1000, 10)
    for n in rng:
        upa_graph = upa_makegraph(n, 5)
        time1 = time.time()
        tmp = app2.targeted_order(upa_graph)
        running_time.append(time.time() - time1)
        fast_time1 = time.time()
        tmp2 = fast_targeted_order(upa_graph)
        fast_running_time.append(time.time() - fast_time1)
    plt.plot(rng, running_time, '-r', label='Targeted Order')
    plt.plot(rng, fast_running_time, '-b', label='Fast Targeted Order')
    plt.title('Targeted Order Function Performance (desktop Python)')
    plt.ylabel('Execution Time (msec)')
    plt.xlabel('Number of Nodes (m = 5)')
    plt.legend()
    plt.show()
Пример #12
0
def question3():
    running_time = []
    fast_running_time = []
    rng = range(10, 1000, 10)
    for n in rng:
        upa_graph = upa_makegraph(n, 5)
        time1 = time.time()
        tmp = app2.targeted_order(upa_graph)
        running_time.append(time.time() - time1)
        fast_time1 = time.time()
        tmp2 = fast_targeted_order(upa_graph)
        fast_running_time.append(time.time() - fast_time1)
    plt.plot(rng, running_time, '-r', label = 'Targeted Order')
    plt.plot(rng, fast_running_time, '-b', label = 'Fast Targeted Order')
    plt.title('Targeted Order Function Performance (desktop Python)')
    plt.ylabel('Execution Time (msec)')
    plt.xlabel('Number of Nodes (m = 5)')
    plt.legend()
    plt.show()
def attack(graph, attack_type):
    new_graph = provided.copy_graph(graph)
    if attack_type == 'normal':
        order = provided.targeted_order(new_graph)
    elif attack_type == 'fast':
        order = fastTargetedOrder(new_graph)
    resilience = pa2.compute_resilience(new_graph, order)
    return resilience
    
#t0 = time.time()
#normal_resilience = attack(upa, 'normal') 
#normal_time = time.time() - t0
#
#t0 = time.time()
#fast_resilience = attack(upa, 'fast')
#fast_time = time.time() - t0   
##
#print 'Normal attack time: ', normal_time
#print 'Fast attack time: ', fast_time
    
#print fastTargetedOrder(create_UPA(25,3))
import pickle

create_upas = []
normal_time = []
fast_time = []

for n in range(10, 1000, 10):
    print n
    t0 = time.time()
    upa = app2.create_UPA(n, 5)
    create_upas.append(time.time() - t0)
    #print upa
    use_graph = provided.copy_graph(upa)

    t0 = time.time()
    order = provided.targeted_order(use_graph)
    #normal_resilience = pa2.compute_resilience(use_graph, order)
    #normal_resilience = app2.attack(upa, 'normal')
    normal_time.append(time.time() - t0)

    use_graph = provided.copy_graph(upa)

    t0 = time.time()
    order = app2.fastTargetedOrder(use_graph)
    #fast_resilience = pa2.compute_resilience(use_graph, order)
    #fast_resilience = app2.attack(upa, 'fast')
    fast_time.append(time.time() - t0)

for i in range(len(normal_time)):
    print 'Time for upa creation :', create_upas[i]
    print 'Normal attack time: ', normal_time[i]
def question_three():
    '''
    Question 3 (3 pts)
    In the next three problems, we will consider attack orders in which the nodes being removed are chosen based on the structure of the graph.
    A simple rule for these targeted attacks is to always remove a node of maximum (highest) degree from the graph.
    The function targeted_order(ugraph) in the provided code takes an undirected graph ugraph and iteratively does the following:

    Computes a node of the maximum degree in ugraph.
    If multiple nodes have the maximum degree, it chooses any of them (arbitrarily).
    Removes that node (and its incident edges) from ugraph.

    Observe that targeted_order continuously updates ugraph and always computes a node of maximum degree with respect to this updated graph.
    The output of targeted_order is a sequence of nodes that can be used as input to compute_resilience.

    As you examine the code for targeted_order, you feel that the provided implementation of targeted_order is not as efficient as possible.
    In particular, much work is being repeated during the location of nodes with the maximum degree.
    In this question, we will consider an alternative method (which we will refer to as fast_targeted_order) for computing the same targeted attack order.
    Here is a pseudo-code description of the method:

    In Python, this method creates a list degree_sets whose kth element is the set of nodes of degree k.
    The method then iterates through the list degree_sets in order of decreasing degree. When it encounter a non-empty set, the nodes in this set must be of maximum degree.
    The method then repeatedly chooses a node from this set, deletes that node from the graph, and updates degree_sets appropriately.

    For this question, your task is to implement fast_targeted_order and then analyze the running time of these two methods on UPA graphs of size n with m=5.
    Your analysis should be both mathematical and empirical and include the following:

    Determine big-O bounds of the worst-case running times of targeted_order and fast_targeted_order as a function of the number of nodes n in the UPA graph.
    Compute a plot comparing the running times of these methods on UPA graphs of increasing size.

    Since the number of edges in these UPA graphs is always less than 5n (due to the choice of m=5), your big-O bounds for both functions should be expressions in n.
    You should also assume that the all of the set operations used in fast_targeted_order are O(1).

    Next, run these two functions on a sequence of UPA graphs with n in range(10, 1000, 10) and m=5 and use the time module (or your favorite Python timing utility)
    to compute the running times of these functions.
    Then, plot these running times (vertical axis) as a function of the number of nodes n (horizontal axis) using a standard plot (not log/log).
    Your plot should consist of two curves showing the results of your timings.
    Remember to format your plot appropriately and include a legend.
    The title of your plot should indicate the implementation of Python (desktop Python vs. CodeSkulptor) used to generate the timing results.

    Your answer to this question will be assessed according to the following three items:

    What are tight upper bounds on the worst-case running times of targeted_order and fast_targeted_order? Use big-O notation to express your answers (which should be very simple).
    Does the plot follow the formatting guidelines for plots? Does the plot include a legend? Does the title include the implementation of Python used to compute the timings?
    Are the shapes of the timing curves in the plot correct?
    '''

    # see FastTargetedOrderFig.png for pseudo-code
    # see alg_application2_provided for provided targeted_order code
    # and my implementation of fast_targeted_order

    # see question3.png for graph results

    '''
    Answer to upper bounds on the worst-case running times:
    Fast_targeted_order : O(n)
    Targeted_order: O(n^2)
    '''

    m = 5 # given by question

    # produce timing for Fast_targeted_order
    x_values = []
    y_values = []

    for n in xrange(10, 1000, 10):
        graph = create_UPA_graph(n, m)
        start_time = time.clock()
        app2_prov.fast_targeted_order(graph)
        finish_time = time.clock()
        run_time = (finish_time - start_time) * 1000 # convert to ms
        x_values.append(n)
        y_values.append(run_time)

    plt.plot(x_values, y_values, lw=2, label='fast_targeted_order (UPA)')

    # produce timing for targeted_order
    x_values = []
    y_values = []

    for n in xrange(10, 1000, 10):
        graph = create_UPA_graph(n, m)
        start_time = time.clock()
        app2_prov.targeted_order(graph)
        finish_time = time.clock()
        run_time = (finish_time - start_time) * 1000 # convert to ms
        x_values.append(n)
        y_values.append(run_time)

    plt.plot(x_values, y_values, lw=2, label='targeted_order (UPA)')

    plt.legend(loc='upper left')
    plt.title('Execution time (ms) for different UPA graph sizes (m = 5) (Desktop Python implementation)')
    plt.xlabel('Number of nodes')
    plt.ylabel('Running time (ms)')

    plt.show()

    pass
Пример #16
0
#upa_graph = get_upa_graph(1239, 5)
#print edges_in_undirected_graph(upa_graph)

#different attack
#start_time = time.time()
#print start_time
#attack_order_v1 = aa2p.targeted_order(upa_graph)
#print time.time() - start_time
#attack_order_v2 = aa2p.fast_targeted_order(upa_graph)

#running time
running_time_v1 = []
for num_nodes in range(10, 1000, 10):
    upa_graph = get_upa_graph(num_nodes, 5)
    start_time = time.time()
    attack_order_v1 = aa2p.targeted_order(upa_graph)
    running_time_v1.append(time.time() - start_time)

running_time_v2 = []
for num_nodes in range(10, 1000, 10):
    upa_graph = get_upa_graph(num_nodes, 5)
    start_time = time.time()
    attack_order_v2 = aa2p.fast_targeted_order(upa_graph)
    running_time_v2.append(time.time() - start_time)
    
#making comparison plots
fig, ax = plt.subplots()
x_vals = [idx for idx in range(10, 1000, 10)]
#print len(x_vals)

ax.plot(x_vals, running_time_v1, '-b', label = 'targeted order')