Advertisement
Guest User

CS170 Approximation Example Code

a guest
May 20th, 2016
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.30 KB | None | 0 0
  1. import networkx as nx
  2. import loader
  3. import matplotlib.pyplot as plt
  4. import IPython as ipy
  5. import numpy as np
  6. import random
  7. import itertools
  8. import sys
  9. import operator
  10.  
  11. import pprint
  12. pp = pprint.PrettyPrinter(indent=4)
  13.  
  14. BRUTE_FORCE_SIZE = 10
  15. MAG_GRASP_TIMES = 15
  16.  
  17. def MAG_GRASP(G, A, ranking=None, iterations=10000):
  18.     nodes = G.nodes()
  19.     n = len(nodes)
  20.     if ranking is None:
  21.         ranking = range(n)
  22.         random.shuffle(ranking)
  23.  
  24.     best_score = score_ranking(A, n, ranking)
  25.     for _ in range(iterations):
  26.         i, j = random.randint(0, n-1), random.randint(0, n-1)
  27.         ranking[i], ranking[j] = ranking[j], ranking[i]
  28.         s = score_ranking(A, n, ranking)
  29.         if s > best_score:
  30.             best_score = s
  31.         else:
  32.             ranking[i], ranking[j] = ranking[j], ranking[i]
  33.     c = [nodes[i]+1 for i in ranking]
  34.     return c, best_score
  35.  
  36. def brute_force(G, A):
  37.     nodes = G.nodes()
  38.     n = len(nodes)
  39.     best_ranking = range(n)
  40.     best_score = score_ranking(A, n, best_ranking)
  41.  
  42.     mapp = dict(zip(range(n), nodes))
  43.  
  44.     assert n <= 10, "Too big for brute force"
  45.  
  46.     for ranking in itertools.permutations(best_ranking):
  47.         score = score_ranking(A, n, ranking)
  48.         if score > best_score:
  49.             best_score, best_ranking = score, ranking
  50.     return [mapp[r]+1 for r in best_ranking]
  51.  
  52. def greedy_out(G,A):
  53.     nodes = G.nodes()
  54.     n = len(nodes)
  55.     norm_nodes = range(n)
  56.     mapp = dict(zip(nodes, norm_nodes))
  57.     dicty = {mapp[i]: G.out_degree(i) for i in G.nodes() }
  58.     y = sorted(dicty.items(), key=operator.itemgetter(1),reverse=True)
  59.     ranking = [x[0] for x in y]
  60.  
  61.     ranking, score = MAG_GRASP(G, A, ranking=ranking)
  62.     return ranking, score
  63.  
  64. def greedy_in(G,A):
  65.     nodes = G.nodes()
  66.     n = len(nodes)
  67.     norm_nodes = range(n)
  68.     mapp = dict(zip(nodes, norm_nodes))
  69.     dicty = {mapp[i]: G.in_degree(i) for i in G.nodes() }
  70.     y = sorted(dicty.items(), key=operator.itemgetter(1),reverse=False)
  71.     ranking = [x[0] for x in y]
  72.  
  73.     ranking, score = MAG_GRASP(G, A, ranking=ranking)
  74.     return ranking, score
  75.  
  76. def Eric(G, A):
  77.     orig = G.copy()
  78.     G = G.copy()
  79.     n = A.shape[0]
  80.     ranking = range(1, n+1)
  81.     nodes = G.nodes()
  82.     norm_nodes = range(1,n+1)
  83.     mapp = dict(zip(nodes, norm_nodes))
  84.  
  85.     l = 1; u = n
  86.     while u >= l:
  87.         n = len(G.nodes())
  88.         rand = random.randint(0, n-1)
  89.         i = G.nodes()[rand]
  90.         indeg = G.in_degree(i)
  91.         outdeg = G.out_degree(i)
  92.         G.remove_node(i)
  93.         if indeg <= outdeg:
  94.             ranking[mapp[i]-1] = l
  95.             l += 1
  96.         else:
  97.             ranking[mapp[i]-1] = u
  98.             u -= 1
  99.     ranking, score = MAG_GRASP(G, A, ranking=ranking)
  100.     return [r+1 for r in ranking], score
  101.  
  102. def circle(G, A):
  103.     base_nodes = G.nodes()[:]
  104.     G = G.copy()
  105.     n = len(G.nodes())
  106.     mappp = dict(zip(G.nodes(), range(n)))
  107.     ranking = [G.nodes()[random.randint(0, n-1)]]
  108.     for i in xrange(1,n-1):
  109.         neighbors = G.neighbors(ranking[i-1])
  110.         if len(neighbors) == 0:
  111.             return [i+1 for i in base_nodes], score_ranking(A, n, [mappp[r] for r in base_nodes])
  112.         ranking.append(G.neighbors(ranking[i-1])[0])
  113.         G.remove_node(ranking[i-1])
  114.     G.remove_node(ranking[-1])
  115.     ranking += [G.nodes()[0]]
  116.     return [r+1 for r in ranking], score_ranking(A, n, [mappp[r] for r in ranking])
  117.  
  118. def ga(G, A, population_size = 100):
  119.     n = A.shape[0]
  120.     inds = np.arange(0,n)
  121.  
  122.     # Initialization
  123.     population = []
  124.     base = range(n)
  125.     for _ in range(population_size):
  126.         random.shuffle(base)
  127.         population.append(base[:])
  128.  
  129.     # Selection
  130.     population_scores = np.array([score_ranking(A, n, r) for r in population])
  131.     p = population_scores * 1.0 / np.sum(population_scores)
  132.     new_population = [population[i] for i in np.random.choice(inds, 50, replace=True, p=p)]
  133.  
  134.     # Apply Genetic Operators
  135.     for _ in range(50):
  136.         pass
  137.  
  138. def score_ranking(A, n, ranking): #ranking = zero-indexed
  139.     assert min(ranking) == 0, "ranking needs to be zero-indexed"
  140.     b = np.zeros(n)
  141.     for i, j in enumerate(ranking):
  142.         b[j] = i
  143.     return np.sum(A * b - A * b[:, np.newaxis] > 0)
  144.  
  145. # def f_on_sccs_and_recombine(G, A, f, d):
  146. #     sccs = [g for g in nx.strongly_connected_component_subgraphs(G)]
  147. #     C = nx.condensation(G)
  148. #     ranking = []
  149. #     for i in nx.topological_sort(C):
  150. #         scc = sccs[i]
  151. #         nodes = scc.nodes()
  152. #         if len(nodes) <= 10:
  153. #             c = brute_force(sccs[i], A[nodes, :][:, nodes])
  154.  
  155. #         else:
  156. #             c = f(sccs[i], A[nodes, :][:, nodes])
  157. #         ranking += c
  158. #     return ranking
  159.  
  160. # def ensemble(G, A, list_of_funcs):
  161. #     n = A.shape[0]
  162. #     best_score, best_ranking, best_f = -1, range(n), None
  163. #     num_sccs = len([g for g in nx.strongly_connected_component_subgraphs(G)])
  164. #     d = {}
  165. #     for f in list_of_funcs:
  166. #         ranking = f_on_sccs_and_recombine(G, A, f, d)
  167. #         score = score_ranking(A, n, [r-1 for r in ranking])
  168. #         print str(f), score
  169. #         if score > best_score:
  170. #             best_score, best_ranking = score, ranking
  171. #     return best_score, best_ranking
  172.  
  173.  
  174. def ensemble(G, A, list_of_funcs):
  175.     n = A.shape[0]
  176.     sccs = [g for g in nx.strongly_connected_component_subgraphs(G)]
  177.     C = nx.condensation(G)
  178.     ranking = []
  179.     total_score = 0
  180.     for i in nx.topological_sort(C):
  181.         scc = sccs[i]
  182.         nodes = scc.nodes()
  183.         sub_A = A[nodes, :][:, nodes]
  184.         if len(nodes) <= BRUTE_FORCE_SIZE:
  185.             ranking += brute_force(scc, sub_A)
  186.         else:
  187.             n = len(nodes)
  188.             best_score, best_ranking, best_f = -1, range(n), None
  189.             for f in list_of_funcs:
  190.                 c, score = f(scc, sub_A)
  191.                 if score > best_score:
  192.                     best_score, best_ranking = score, c
  193.             ranking += best_ranking
  194.             total_score += best_score
  195.     return ranking, total_score
  196.  
  197. if __name__ == '__main__':
  198.     draw = False
  199.  
  200.     # A = loader.generate_instance_shane(100, .7)
  201.     # G = nx.DiGraph(A)
  202.     # n, A = loader.read_graph("data/Eric_raw.in")
  203.     # G = nx.DiGraph(A)
  204.     # score, result = ensemble(G, A, [Eric, greedy_out, greedy_in])
  205.     # print "score: ", score
  206.     # print result
  207.     # n, A = loader.read_graph("data/Eric_trick.in")
  208.     # G = nx.DiGraph(A)
  209.     # score, result = ensemble(G, A, [Eric, greedy_out, greedy_in])
  210.     # print "score: ", score
  211.     # print result
  212.  
  213.     # sys.exit()
  214.     # f = open("instances_sccs.txt", "w")
  215.     # ct = 0
  216.     _, A1 = loader.read_graph("data/KINGSMEN1.in") # circle
  217.     _, A2 = loader.read_graph("data/KINGSMEN2.in")
  218.     _, A3 = loader.read_graph("data/KINGSMEN3.in")
  219.  
  220.     _, A1_replaced = loader.read_graph("dual_circle_raw.in")
  221.     _, A2_replaced = loader.read_graph("data/Eric_raw.in")
  222.  
  223.     # res = ensemble(nx.DiGraph(A1_replaced), A1_replaced, [MAG_GRASP]*15 + [greedy_in, greedy_out] + [circle])
  224.     # res1 = ensemble(nx.DiGraph(A1), A1, [MAG_GRASP]*15 + [greedy_in, greedy_out] + [circle])
  225.     # print score_ranking(A1, 100, [r-1 for r in res])
  226.     # print score_ranking(A1, 100, [r-1 for r in res1])
  227.  
  228.     # A = loader.generate_circular(100)
  229.     # G = nx.DiGraph(A)
  230.     # res = ensemble(G, A, [circle])
  231.     # print score_ranking(A, 100, [r-1 for r in res])
  232.  
  233.     # for j in [371, 475, 489, 537, 543]:
  234.     # for j in [53, 530, 489, 537, 543]:
  235.     #     i = str(j) + ".in"
  236.     #     n, A = loader.read_graph("instances/"+i)
  237.     #     G = nx.DiGraph(A)
  238.     #     res = ensemble(G, A, [MAG_GRASP]*15 + [greedy_in, greedy_out] + [circle])
  239.     #     print "edges", np.sum(A)
  240.     #     print "score", score_ranking(A, n, [r-1 for r in res])
  241.     #     print [i for i in nx.strongly_connected_components(G)]
  242.     #     print ""
  243.     #     print ""
  244.  
  245.     for j in range(1,622):
  246.         i = str(j) + ".in"
  247.         # print "------------------------------------------------\n\n"
  248.         n, A = loader.read_graph("instances/"+i)
  249.         if np.array_equal(A, A1):
  250.             A = A1_replaced
  251.         if np.array_equal(A, A2):
  252.             A = A2_replaced
  253.         if np.array_equal(A, A3):
  254.             A3_to_remove = [[17, 22], [29, 24], [71, 81], [59, 62], [91, 20], [97, 54], [77, 69], [5, 28], [48, 4]]
  255.             for i,j in A3_to_remove:
  256.                 assert A[i,j] == 1
  257.                 A[i,j] = 0
  258.  
  259.         print "------------------------"
  260.         print "id:", j
  261.         print "nodes:", A.shape[0]
  262.         G = nx.DiGraph(A)
  263.         print "sccs:", len([i for i in nx.strongly_connected_components(G)])
  264.         ranking, _ = ensemble(G, A, [MAG_GRASP]*MAG_GRASP_TIMES + [greedy_in, greedy_out] + [circle])
  265.         score = int(score_ranking(A, A.shape[0], [r-1 for r in ranking]))
  266.         print score, "/", int(np.sum(A))
  267.         loader.write_single_output(ranking, score, fname="outputs_eric/"+str(j)+".out")
  268.         print ""
  269.         print ""
  270.         # print "total edges: ", np.sum(A)
  271.         # lengths = [len(i) for i in nx.strongly_connected_components(G)]
  272.     #     # f.write(str(j) + ", " + str(lengths) + "\n")
  273.     #     # ct = ct + (1 if len(lengths) > 1 else 0)
  274.     #     if draw:
  275.     #         nx.draw_networkx(G)
  276.     #         plt.savefig("figures/"+i[:i.index(".in")]+".png")
  277.     #         plt.clf()
  278.     #     # print j
  279.     # print "total ct", ct
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement