def main(): try: args = parseArguments() except: args = {"-h": True} if "-l" not in args: args["-l"] = False else: args["-l"] = True # handle argument if "-h" in args: printHelp() return if "-a" not in args: greedy(args) return if args["-a"] == "aco": aco(args) elif args["-a"] == "ga": ga(args) elif args["-a"] == "greedy": greedy(args) elif args["-a"] == "mst": mst(args) else: printHelp()
def test_greedy(self): print 'testing greedy function' #my sample data my_data = Data() test_data = 'test.json' my_data.extract_data(test_data) uni_set = my_data.get_all_stores() set_sub = my_data.get_zips() #sorted_set = sorted(set_sub.values(), key=operator.attrgetter('num_nearby_stores'), reverse = True) #for zip in sorted_set: # zip.print_nearby_stores() min_zip_check = greedy(uni_set, set_sub) #test on given input file real_data = Data() data_file = 'gistfile1.json' real_data.extract_data(data_file) uni_set = real_data.get_all_stores() set_sub = real_data.get_zips() min_zip_check = greedy(uni_set, set_sub)
def boxplot(map, max_routes, max_time, iterations, algorithm=None, key=None, min_score=None, depth=None, ratio=None): """Visualize a boxplot for all algorithms.""" random = [] greedy_connections = [] greedy_time = [] greedy_score = [] depth_first_score = [] breadth_first_score = [] # Create dataset based on algorithm scores for i in range(iterations): random.append(randomize(map, max_routes, max_time).score) greedy_connections.append( greedy(map, max_routes, max_time, "connections").score) greedy_time.append(greedy(map, max_routes, max_time, "time").score) greedy_score.append(greedy(map, max_routes, max_time, "score").score) depth_first_score.append( depth_first(map, max_routes, max_time, min_score, depth, ratio).score) breadth_first_score.append( breadth_first(map, max_routes, max_time, min_score, depth, ratio).score) # Create boxplot based on all scores colors = [ "steelblue", "tomato", "coral", "lightsalmon", "lightgreen", "lightblue" ] medianprops = dict(linestyle="solid", linewidth=1, color="black") box_plot_data = [ random, greedy_connections, greedy_time, greedy_score, depth_first_score, breadth_first_score ] box = plt.boxplot( box_plot_data, patch_artist=True, medianprops=medianprops, showfliers=False, labels=[ "random", "greedy (connections)", "greedy (time)", "greedy (score)", "depth first", "breadth first" ], ) for patch, color in zip(box["boxes"], colors): patch.set_facecolor(color) plt.ylabel(f"K Score") plt.title("Boxplot Algorithms") plt.show()
def grasp(limiteIteracion, secuencias): iteracion = 0 mejorValor = -999 res = gdy.greedy(secuencias) while (iteracion < limiteIteracion): g = gdy.greedy(secuencias) bl = blo.busquedaLocal(g) if (mejorValor < bl["SCORE"]): mejorValor = c.deepcopy(bl["SCORE"]) res = bl iteracion += 1 return res
def test_saturation_largest_first(pysal_geos): colors = greedy(world, strategy="saturation_largest_first", min_distance=pysal_geos) assert len(colors) == len(world) assert set(colors) == set([0, 1, 2, 3]) assert colors.value_counts().to_list() == [71, 47, 42, 17]
def test_index(pysal_geos): world["ten"] = world.index * 10 reindexed = world.set_index("ten") colors = greedy(reindexed, min_distance=pysal_geos) assert len(colors) == len(world) assert set(colors) == set([0, 1, 2, 3, 4]) assert colors.value_counts().to_list() == [36, 36, 35, 35, 35]
def DriverNet(args): ''' main function of DriverNet ''' logger.info("Start running.") logger.info("Parameters: %s" %(' '.join(sys.argv))) ggi_matirx = args.network sample_mutation_matrix = args.mutation sample_exp_outlier = args.expression permutation_time = args.permutation_time threads = args.threads notPurturbGraph = args.notPurturbGraph purturbData = args.purturbData output_prefix = args.output edges, ggi, outlier_dict, mutation_dict = preprocess(ggi_matirx, sample_mutation_matrix, sample_exp_outlier) drivers, actual_events = greedy(edges, mutation_dict) logger.info("Driver finding done. Start significance test now.") random_res = permutation(ggi, outlier_dict, mutation_dict, permutation_time, threads, notPurturbGraph, purturbData) pvalues, qvalues = compute_p(drivers, random_res) logger.info("Significance test done.") report(drivers, actual_events, pvalues, qvalues, output_prefix) logger.info("Writing output done. Please check %s.txt." %(output_prefix)) logger.info("All done. Cheers.")
def grd2opt(matrix, need): a1, b = greedy(matrix, need) # We pop last element of list because it is the start node added at end for tour completion # 2opt will re-add it so no worries a1.pop() matrix[0][0] = 0 tour, dist = opt2(matrix, a1) # We make another pass with 2opt # It costs us double time, yes # But that increase is miniscule compared to run time of actual sorting algorithm, greedy in this case # And the tour does improve in the second pass # However, more then 2 passes in total will have no effect, so do not waste time print("First Pass tour length is: " + str(dist)) tour.pop() tour, dist = opt2(matrix, tour) print("Second Pass tour length is: " + str(dist)) tour.pop() tour, dist = opt2(matrix, tour) if __name__ == "__main__": print("Smallest tour is:") print(tour) print("Tour length is: " + str(dist)) else: # print(tour) return tour, dist
def construct_greedy_rbf(self, eng_cap, num_greedy_centers, **options): """ Compute RBF system for greedy implementation """ try: greedy_output = options['greedy_output'] except: greedy_output = False print("\n---- Computing list of modes L ----\n") mode_list = gdy.greedy_modelist(self._dzdt_train, self._comp_keys, eng_cap=eng_cap, msg=greedy_output) L_modes = gdy.combine_L(mode_list, self._n_pod) self._L = L_modes print("\n---- Finding %s-greedy centers ----\n" % self._greedy_alg) A_tmp, Z_center_tmp = rbf.compute_interp_matrix(self._Z_train, self._n_snap_train-1, rbf_kernel=self._kernel, epsilon=self._scale_user) ind_greedy = gdy.greedy(self._dzdt_train, Z_center_tmp, self._times_offline, self._kernel, self._scale_user, self._L, alg=self._greedy_alg, msg=greedy_output, tau=self._tau) self._ind_greedy = np.sort(ind_greedy[:num_greedy_centers+1]) S_greedy = {} for key in self._comp_keys: S_greedy[key] = self._S[key][:, self._ind_greedy] Z_greedy = pod.project_onto_basis(S_greedy, self._Phi, self._S_mean) times_greedy = self._times_offline[self._ind_greedy] return Z_greedy, times_greedy
def test_connected_sequential_bfs(pysal_geos): colors = greedy(world, strategy="connected_sequential_bfs", min_distance=pysal_geos) assert len(colors) == len(world) assert set(colors) == set([0, 1, 2, 3, 4]) assert colors.value_counts().to_list() == [77, 46, 34, 18, 2]
def GRASP(LRC, max_iter, max_iter_bl, max_vecinos_bl): # se inicializa la variable de resultados a vacio glo.RESULTADOS = [] # se inicializa el contador y la solución inicial it = 0 best_sol = [] best_fit = 100000 # para cada iteración while it < max_iter: # se genera una solución inicial a partir del greedy sol_ini = greedy(LRC) # se aplica una búsqueda local a la solución generada sol_act, fit_act, resultados = bl.busqueda_local(sol_ini, max_iter_bl, max_vecinos_bl) # si la solución actual es mejor que la mejor encontrada, se modifica la mejor if fit_act < best_fit: best_sol = sol_act best_fit = fit_act # se aumenta el contador it += 1 # se almacenan los resultados glo.RESULTADOS.append([it, fit_act, resultados, sol_act]) # se devuelve la mejor solución y su fitness return best_sol, best_fit
def factibilidad(sobres): if len( sobres ) < 3: #Solo tiene el 1 y a lo sumo un elemento mas. Siempre se va a obtener el optimo. return True for x in range((sobres[2] + 1) + 1, sobres[len(sobres) - 2] + sobres[len(sobres) - 1]): #dinamica u optima: sobres = main_factibilidad( sys.argv) #Si no llamo al main en cada llamada, falla. solucion_prog_dinamica = dinamica(sobres, x) cantidad_de_sobres_prog_dinamica = 0 for tarjetas, sobres in solucion_prog_dinamica: cantidad_de_sobres_prog_dinamica += sobres #greedy: sobres = main_factibilidad(sys.argv) solucion_greedy = greedy(sobres, x) cantidad_de_sobres_greedy = 0 for tarjetas, sobres in solucion_greedy: cantidad_de_sobres_greedy += sobres if cantidad_de_sobres_greedy > cantidad_de_sobres_prog_dinamica: print 'No es factible obtener una solucion optima con Greedy para los sobres dados.' print 'Contraejemplo =', x, 'tarjetas. Con Greedy se obtienen', cantidad_de_sobres_greedy, 'sobres mientras que la cantidad optima es', cantidad_de_sobres_prog_dinamica break return True
def iterations(map, max_routes, max_time, iterations, algorithm, key=None, min_score=None, depth=None, ratio=None): """Visualize a lineplot of algorithm scores of selected algorithm.""" score = [] # Create dataset based on scores of selected algorithm for i in range(iterations): if algorithm == "random": solution = randomize(map, max_routes, max_time) elif algorithm == "greedy": solution = greedy(map, max_routes, max_time, key) elif algorithm == "depth_first": solution = depth_first(map, max_routes, max_time, min_score, depth, ratio) elif algorithm == "breadth_first": solution = breadth_first(map, max_routes, max_time, min_score, depth, ratio) score.append(solution.score) # Show visualisation lineplot(score, algorithm, key=None)
def permutation_helper(ggi=None, outlier_dict=None, mutation_dict=None, notPurturbGraph=False, purturbData=False): ''' ''' if purturbData: random_outlier_dict = shuffle_data(outlier_dict) random_mutation_dict = shuffle_data(mutation_dict) else: random_outlier_dict = deepcopy(outlier_dict) random_mutation_dict = deepcopy(mutation_dict) if not notPurturbGraph: random_ggi = random_net(ggi) else: random_ggi = deepcopy(ggi) random_edges = get_bipartite(random_ggi, random_outlier_dict, random_mutation_dict) random_drivers, random_events = greedy(random_edges, random_mutation_dict) return random_drivers
def test_area(pysal_geos): colors = greedy(world, strategy="balanced", balance="area", min_distance=pysal_geos) assert len(colors) == len(world) assert set(colors) == set([0, 1, 2, 3, 4]) assert colors.value_counts().to_list() == [55, 49, 39, 32, 2]
def test_distance(pysal_geos): colors = greedy(world, strategy="balanced", balance="distance", min_distance=pysal_geos) assert len(colors) == len(world) assert set(colors) == set([0, 1, 2, 3, 4]) assert colors.value_counts().to_list() == [38, 36, 35, 34, 34]
def branchandbound(testObject):#Loop in subsets of cases = O(2^n) global boundExcess boundExcess=greedy(testObject)[1] length=len(testObject.Cases) initialBinary="" if(not( isinstance(boundExcess, str) )): boundExcess=boundExcess-1 result=brancher([testObject,initialBinary,length,boundExcess]) return result
def greedySearch(sid2pids, pid2pid, prefix): iterationTime = 1000000 fp = open(sid2pids) sid2pids = json.loads(fp.read()) fp.close() fp = open(pid2pid) pid2pid = json.loads(fp.read()) fp.close() PIDS = [] SIDS = [] for sid, pids in sid2pids.items(): ps = [] for pid in pids: p = pid[0] ps.append(p) PIDS.append(ps) ''' PIDSS = [] limits = [] PIDSS.append(PIDS[:]) limits.append(iterationTime) for i in range(1,len(PIDS[0])): iterationTime = iterationTime/2 limits.append(iterationTime) PIDS2 = copy.deepcopy(PIDS) head = copy.deepcopy(PIDS2[0]) head = exchange(head,i) PIDS2[0] = head PIDSS.append(PIDS2[:]) #gready search pools = Pool(threads) it = min(5,len(PIDSS)) for i in range(it): prex = prefix + ".%s" % i PIDS = PIDSS[i] limit = limits[i] pools.apply_async(greedy,(PIDS,pid2pid,limit,prex)) pools.close() pools.join() ''' greedy(PIDS, pid2pid, 10000000, prefix)
def test_greedy__one_iteration(self): target_dist = {("Hallo", "h"): 0.2, ("du", "d"): 0.3, ("und", "u"): 0.4, ("Bye", "b"): 0.1} selection_list = [[("Hallo", "h"), ("du", "d"), ("und", "u"), ("du", "d")], [("Bye", "b"), ("und", "u"), ("du", "d")], [("Irrelevante", "i"), ("Worte", "w")]] res = greedy(target_dist, selection_list, 1) right_cover = [[("Hallo", "h"), ("du", "d"), ("und", "u"), ("du", "d")]] self.assertEqual(1, len(res)) self.assertEqual(right_cover, res)
def modularLowerBound(X, k, func, func_parameter, offset, optObj, approx=0.5, iters=3): #print('computing subdifferentials...') runGreedy = True g = greedy(X, func=func, func_parameter=func_parameter, save_memory=[False, 8], offset=offset) perm = numpy.arange(X.shape[0]) topkIndex_old = [] #run subdifferetial for iters steps for it in range(iters): score = numpy.zeros(X.shape[0]) nn, score[0] = g.f.evaluate([perm[0]]) for i in range(1, X.shape[0]): nn, score[i] = g.f.evaluate_incremental(nn, perm[i]) score[1:] = score[1:] - score[:-1] score += offset[perm] topkIndex = numpy.argpartition(score, -k)[-k:] mlb = sum(score[topkIndex]) topkIndex = perm[topkIndex] perm = numpy.append( topkIndex, numpy.setxor1d(numpy.arange(X.shape[0]), topkIndex)) # use random permutation if cannot improve if len(numpy.setxor1d(topkIndex, topkIndex_old)) == 0: #break perm = numpy.append( topkIndex, numpy.random.permutation( numpy.setxor1d(numpy.arange(X.shape[0]), topkIndex))) #test if approximation factor is large enough elif g.f.evaluate(topkIndex)[1] + sum( offset[topkIndex]) >= approx * optObj: runGreedy = False break else: topkIndex_old = topkIndex if runGreedy: print('running greedy to update A') topkIndex, greedyObj, f_Vsize = g(k) print('Approx factor =', greedyObj / optObj) return topkIndex
def modular_lower_bound(X, k, offset, func='concavefeature', func_parameter=0.5, perm=[], init_method='greedy'): if len(perm) == 0: if init_method == 'random': perm = numpy.random.permutation(X.shape[0]) if func == 'facloc': f = facloc_graph(X, func_parameter[0], func_parameter[1]) elif func == 'satcoverage': f = satcoverage(X, func_parameter[0], func_parameter[1]) elif func == 'concavefeature': f = concavefeature(X, func_parameter) elif func == 'setcover': f = setcover(X, func_parameter[0], func_parameter[1]) elif func == 'videofeaturefunc': f = videofeaturefunc(X) X = X[1] else: print( 'Function can only be facloc, satcoverage, concavefeature, setcover or videofeaturefunc' ) print('finish building submodular function for data size', X.shape[0], '\n') elif init_method == 'greedy': g = greedy(X, func=func, func_parameter=func_parameter, save_memory=[False, 8], offset=offset) perm, f_obj, f_Vsize = g(k) f = g.f else: f = func if len(perm) <= X.shape[0]: perm = numpy.append( perm, numpy.random.permutation(list(set(range(X.shape[0])) - set(perm)))) else: print('length of perm should be less than', X.shape[0]) print('computing subdifferentials') score = numpy.zeros(X.shape[0]) nn, score[0] = f.evaluate([perm[0]]) for i in range(1, X.shape[0]): nn, score[i] = f.evaluate_incremental(nn, perm[i]) score[1:] = score[1:] - score[:-1] return score, perm, f
def start_algorithm(map, max_routes, max_time, min_score, algorithm, iterations, key, depth, ratio): """Find best routes based on input algorithm. Keyword arguments: algorithm (str) algorithm that will be used to improve solution iterations (int) total iterations of improving key (str) options: [Connections, Time, Score]. Method Greedy makes choices depth (int) length of route after which can be pruned ratio (int) score/length ratio in order to best solution after which can be pruned """ # Run random algorithm and find best solution if algorithm == "random": best_score = 0 for i in range(iterations): solution = randomize(map, max_routes, max_time) if solution.score > best_score: best_solution = solution best_score = solution.score # Run greedy algorithm and find best solution if algorithm == "greedy": best_score = 0 for i in range(iterations): solution = greedy(map, max_routes, max_time, key) if solution.score > best_score: best_solution = solution best_score = solution.score # Run depth first algorithm and find best solution if algorithm == "depth_first": best_score = 0 for i in range(iterations): solution = depth_first(map, max_routes, max_time, min_score, depth, ratio) if solution.score > best_score: best_solution = solution best_score = solution.score # Run breadth first algorithm and find best solution if algorithm == "breadth_first": best_score = 0 for i in range(iterations): solution = breadth_first(map, max_routes, max_time, min_score, depth, ratio) if solution.score > best_score: best_solution = solution best_score = solution.score print(f"Score: ", best_solution.score) visualisation(map, best_solution.routes) return best_solution
def time_greedy(): NChildrenList = range(5,100,2) for num_children in NChildrenList: t = time.time() lst = [] for i in range(1,num_children): lst.append(random.randint(20,100)) sol = greedy.greedy(3, lst) sollength = len(sol) elapsed = time.time() - t print "For ", num_children, " took time ", elapsed, " solution has length", sollength
def time_greedy(): NChildrenList = range(5, 100, 2) for num_children in NChildrenList: t = time.time() lst = [] for i in range(1, num_children): lst.append(random.randint(20, 100)) sol = greedy.greedy(3, lst) sollength = len(sol) elapsed = time.time() - t print "For ", num_children, " took time ", elapsed, " solution has length", sollength
def initSubmodularFunc(X, k, func = 'concavefeature', func_parameter = 0.56): g = greedy(X, func = func, func_parameter = func_parameter, save_memory = [False, 8]) V = g.V f = g.f nn, V_obj = f.evaluateV() minGain = V_obj - numpy.asarray([f.evaluate_decremental(nn, x, V)[1] for x in V]) sinGain = numpy.asarray([f.evaluate([x])[1] for x in V]) topkObj = sum(numpy.partition(sinGain, -k)[-k:]) kcluster, greedyObj, f_Vsize = g(k) optObj = min([greedyObj/(1 - 1/numpy.e), topkObj]) return minGain, sinGain, optObj
def greedyPlotting(Graph): act = neighbors_activation(Graph) greedyPlot = [] listNumberActivated = [] random.seed(4) for i in range(10, 50, 1): seed = greedy(i, Graph) newSeed = transformSeed(seed) print(newSeed) result = icm(Graph, newSeed, act) print(result) lengthICM = len(result) greedyPlot.append(lengthICM)
def sorted_simple_bnb(data, weight_knapsack): greedy_ub, _, __ = greedy(data, weight_knapsack) data = data.drop([0]) data["ratio"] = data["value"]/data["weight"] data = data.sort_values(by=["ratio"], ascending=False) # todo: now quick sort, change to another sort ??? weights_subjects = list(data["weight"]) values_subjects = list(data["value"]) ratio = list(data["ratio"]) n = len(values_subjects) queue_bnb = list() found_optimum = False node = [0, 0, 0] # weight, profit, level of item # todo: sorted profit ratio and use it # ratio = [] # for i in range(len(weights_subjects)): # ratio.append(values_subjects[i]/weights_subjects[i]) # ratio.sort(reverse=True) queue_bnb.append(node) ub = calculate_sorted_ub(0, 0, weight_knapsack, ratio, 0) if greedy_ub< ub: ub = greedy_ub counter_cells = 0 while len(queue_bnb)!=0 and not found_optimum: current_node = queue_bnb.pop() node_ub = calculate_sorted_ub(current_node[1], current_node[0], weight_knapsack, ratio, current_node[2]-1) if node_ub >= ub: if current_node[1] >= ub: ub = current_node[1] if (current_node[2] + 1) <= n: counter_cells += 1 queue_bnb.append([current_node[0], current_node[1], current_node[2] + 1]) if current_node[0] + weights_subjects[current_node[2]] <= weight_knapsack: counter_cells += 1 queue_bnb.append([current_node[0] + weights_subjects[current_node[2]], current_node[1] + values_subjects[current_node[2]], current_node[2] + 1]) print("Sorted Simple BnB", counter_cells) return ub, "Sorted Simple BnB", counter_cells
def test(): ggi_matirx = 'sampleInfluenceGraph.txt' sample_mutation_matrix = 'samplePatientMutationMatrix.txt' sample_exp_outlier = 'samplePatientOutlierMatrix.txt' edges, ggi, outlier_dict, mutation_dict = preprocess( ggi_matirx, sample_mutation_matrix, sample_exp_outlier) drivers, actual_events = greedy(edges, mutation_dict) random_res = permutation(ggi, outlier_dict, mutation_dict) pvalues, qvalues = compute_p(drivers, random_res) print(qvalues)
def grd2opt(matrix, need): a1, b = greedy(matrix, need) # We pop last element of list because it is the start node added at end for tour completion # finaltour generator will re-add it so no worries a1.pop() matrix[0][0] = 0 tour, dist = gentour(matrix, a1) if __name__ == "__main__": print("Smallest tour is:") print(tour) print("Tour length is: " + str(dist)) else: # print(tour) return tour, dist
def tabu(testObject): initialSolution=greedy(testObject) if( isinstance(initialSolution[1], str) ): return [" "," "] resultCase=makeTheBinary(initialSolution[0],len(testObject.Cases)) currentExcess=-1*initialSolution[1] caseList=testObject.Cases order=testObject.totalOrder bestSolution=resultCase bestExcess=currentExcess localBest=resultCase localExcess=currentExcess tabuList=[] tabuList.append(localBest) x=0 while(x<150): neighborhood=getNeighborhood(localBest,caseList,order,tabuList) if(len(neighborhood[0])==0): break neigList=neighborhood[0] excessList=neighborhood[1] localBest=neigList[0] localExcess=excessList[0] badMoves=0 y=0 for candidate in neigList: if(not(candidate in tabuList) and localExcess>excessList[y]): localBest=candidate localExcess=excessList[y] y=y+1 if(localExcess<bestExcess): bestSolution=localBest bestExcess=localExcess badMoves=0 else: badMoves=badMoves+1 if(not(localBest in tabuList ) ) : tabuList.append(localBest) if(badMoves==30): break x=x+1 return [bestSolution,bestExcess]
def main(filename, k, portCentralMachine, e0): lines = open(filename, 'r') V = [] for line in lines: e = line.split(',') e[-1] = e[-1][0:-1] V.append(e) print len(V) S = greedy.greedy(V,V,k,e0) print S sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('', portCentralMachine)) sock.send(json.dumps(S)) sock.close()
def vns(testObject): #Loop in subsets of cases = O(2^n) initialSolution = greedy(testObject) if (not (isinstance(initialSolution[1], str))): resultCase = makeTheBinary(initialSolution[0], len(testObject.Cases)) caseList = testObject.Cases currentCase = findCase(caseList, resultCase) order = testObject.totalOrder currentExcess = -1 * initialSolution[1] solvedFlag = 1 resultCase else: solvedFlag = 0 return [" ", " "] while solvedFlag == 1: solvedFlag = 0 neigList = findNeighborhood(resultCase, 1) length = len(neigList) x = 0 while x < length: tempCase = findCase(caseList, neigList[x]) tempExcess = findExcess(order, tempCase) if (tempExcess != -1 and tempExcess < currentExcess): resultCase = neigList[x] currentExcess = tempExcess currentCase = tempCase solvedFlag = 1 x = x + 1 if (solvedFlag == 0): neigList = findNeighborhood(resultCase, 2) length = len(neigList) x = 0 while x < length: tempCase = findCase(caseList, neigList[x]) tempExcess = findExcess(order, tempCase) if (tempExcess != -1 and tempExcess < currentExcess): resultCase = neigList[x] currentExcess = tempExcess currentCase = tempCase solvedFlag = 1 x = x + 1 return [resultCase, currentExcess]
def custom_coloring(node_count: int, edges: list, max_iter: int, max_stall: int): adjacency_list = get_adjacency_list(node_count, edges) # degrees = list(range(node_count)) # degrees.sort(key=lambda x: - len(adjacency_list[x])) total_sol = [] totla_obj = node_count + 1 G = nx.Graph(edges) for _ in range(max_iter): d = nx.coloring.greedy_color(G, strategy='random_sequential') solution = [0] * node_count for i in range(node_count): solution[i] = d[i] obj = max(solution) + 1 improved = True while improved: improved = False color_groups = [] for _ in range(obj): color_groups.append([]) for i, c in enumerate(solution): color_groups[c].append(i) for g in color_groups: g.sort(key=lambda x: -len(adjacency_list[x])) for _ in range(max_stall): shuffle(color_groups) ordered_nodes = list( itertools.chain.from_iterable(color_groups)) new_solution = greedy(ordered_nodes, adjacency_list) new_obj = max(new_solution) + 1 if new_obj < obj: obj = new_obj solution = new_solution improved = True break if obj < totla_obj: totla_obj = obj total_sol = solution return totla_obj, total_sol
def __init__(self, app, **kwargs): Thread.__init__(self) self.exit = Event() self.app = app self.player_brain = no_brain() if kwargs["naive_modelname"]: self.player_brain = naive(kwargs["naive_modelname"]) elif kwargs["greedy"]: self.player_brain = greedy() elif kwargs["knn_modelname"]: self.player_brain = KNN(kwargs["knn_modelname"]) elif kwargs["dgreedy"]: self.player_brain = deep_greedy(*kwargs["dgreedy"]) elif kwargs["boltz"]: self.player_brain = boltz(kwargs["boltz"], kwargs["train"]) else: self.player_brain = no_brain()
def generate_files(master, dirN): for numTasks in range(1, totalNumTasks + 2): speed, pu = load_tasks(numTasks, numMachines, appd, idlePow) workload = [totalWkld] * numTasks for powerCap in range(1000, maxPowerCap, 400): try: newPath = os.path.join(master,dirN) #create_dir(newPath) #out = newPath+"-"+str(powerCap)+"-"+str(numTasks)) nt = str(numTasks) if(numTasks > 8): nt = str(numTasks - 1) if(dirN == "greedy"): for policy in policies: newPath = os.path.join(newPath, policiesList[policies.index(policy)]) create_dir(newPath) out = newPath+"-"+str(powerCap)+"-"+nt order, trn, run = greedy.greedy(workload, speed, pu, idlestates, idleusage, powerCap, policy) fileio.val2file(out, pu, idlestates, idleusage, powerCap, order, trn, run) newPath = os.path.join(master,dirN) elif(dirN == "smartGreedy"): for policy in policies: newPath = os.path.join(newPath, policiesList[policies.index(policy)]) create_dir(newPath) out = newPath+"-"+str(powerCap)+"-"+nt order, trn, run = greedy.smartGreedy(workload, speed, pu, idlestates, idleusage, powerCap, policy) fileio.val2file(out, pu, idlestates, idleusage, powerCap, order, trn, run) newPath = os.path.join(master,dirN) elif(dirN == "halfHeartedGreedy"): for combo in hf: newPath = os.path.join(newPath, hfList[hf.index(combo)]) create_dir(newPath) out = newPath+"-"+str(powerCap)+"-"+nt order, trn, run = greedy.halfHeartedGreedy(workload, speed, pu, idlestates, idleusage, powerCap, combo) fileio.val2file(out, pu, idlestates, idleusage, powerCap, order, trn, run) except: traceback.print_exc() pass
if __name__ == "__main__": G = read_graph("datasets/Wiki-Vote_graph_ic.txt", True) L = read_likes("datasets/Wiki-Vote_likes.txt") K = 30 R = 100 #comparison of PIMUS to IM # S = random.sample(G, 50) # f = greedy(G, L, S, K, R, False) # print 'PIMUS spread:', run_lt(G, L, S, f, R) # S = comparison.greedy_im(G, 5, R) # print 'IM spread:', comparison.run_ic(G, S, R) # comparison of different PIMUS algorithms l = 20 count = 0 spread = 0 for _ in range(l): S = random.sample(G.nodes(), 50) f1 = greedy(G, L, S, K, R) print sorted(f1) spread += run_ic(G, L, S, f1, R) print 'Average spread:', spread/l with open('data/spread{0}.txt'.format(K), 'w+') as f: f.write("{0}".format(spread/l)) console = []
from common import read_input, print_solution from optimize import optimize from opt_2 import opt_2 from greedy import greedy from solver_greedy import solve from or_opt import or_opt from vortex import vortex from kruskal import kruskal_greedy from my_random import random_solve from combine import optimize2, read_path if __name__ == '__main__': assert len(sys.argv) > 1 optimize = optimize(read_input(sys.argv[1])) optimize2 = optimize2(read_input(sys.argv[1]), read_path(sys.argv[2])) greedy = greedy(read_input(sys.argv[1])) opt_2 = opt_2(read_input(sys.argv[1])) or_opt = or_opt(read_input(sys.argv[1])) vortex = vortex(read_input(sys.argv[1])) kruskal = kruskal_greedy(read_input(sys.argv[1])) print_solution(or_opt) print_solution(or_opt) print_solution(vortex) print_solution(kruskal) print_solution(greedy) print_solution(greedy) print_solution(optimize) print_solution(optimize) print_solution(optimize) print_solution(optimize)
import csv num_goods = ['100', '500', '1000'] num_bids = ['100', '500', '1000', '2000', '4000'] greedy_results = [] twoatom_results = [] ibm_results = [] for bid in num_bids : for good in num_goods : print "testing 2-atom-"+good+"-"+bid for i in range(5) : test = parse_2atom('testfiles/2atom/2atom-'+good+'-'+bid+'-000'+str(i)+'.txt') start = time.time() revenue = greedy(test[3], test[4]) length = time.time() - start greedy_results.append([good, bid, revenue, length]) for bid in num_bids : for good in num_goods : print "testing 2-atom-"+good+"-"+bid for i in range(5) : test = parse_2atom('testfiles/2atom/2atom-'+good+'-'+bid+'-000'+str(i)+'.txt') start = time.time() revenue = twoatom(test[3], test[4]) length = time.time() - start twoatom_results.append([good, bid, revenue, length]) for bid in num_bids : print "\n\n\n\n\nstarting IBM BID: " + str(bid) + "\n\n\n\n\n"
def central(filename, k, port, m): # make dummy entry for greedy alg linelen = 6 # magic number for now, num fields e0 = "z,"*(linelen-1)+"z" e1 = "a,"*(linelen-1)+"a" #set up socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', port)) s.listen(1) # open log logfile = './log/central_port' + str(port) centlog = open(logfile,'w') print 'CENTRAL started on port ' + str(port) centlog.write('CENTRAL, port:' + str(port) + 'k: ' + str(k) + ', # machines: ' + str(m) + '\n') centlog.close() # initialize recevied reps V = [[],]*m # receive local solutions while True: # get local reps conn, addr = s.accept() bufsize = 10*stat(filename).st_size # how much data to receive, estimate data = conn.recv(bufsize) conn.close() # process received reps i,Vi = json.loads(data) print 'CENTRAL port ' + str(port) + ', data received from machine ' + str(i) V[i] = deepcopy(Vi) Vflat = [] for v in V: Vflat += v # load local data to be represented lines = open(filename, 'r') D = [] for line in reader(lines): #comma splitting, respects " " if len(line) == linelen: # ignore partial lines D.append(line) lines.close() # compute representatives of local data from received reps S, score = greedy.greedy(Vflat,D,k,e0) # log reps and scores now = time() numpts = len(D) print 'CENTRAL port ' + str(port)+ ', \t time: ' + str(now) + '\t entries: ' + str(numpts) +'\t score: ' + str(score) centlog = open(logfile,'a') centlog.write(str(now) + '\t' + str(numpts) + '\t' + str(score) + '\t' + str(S) + '\n') centlog.close() # write current solution so people, oracle can read it fsoln = './log/central_solution_' + str(port) f = open(fsoln,'w') for rep in S: towrite = rep[0]+','+rep[1]+',"'+rep[2]+'",'+rep[3]+','+rep[4]+','+rep[5]+'\n' f.write(towrite) f.close()
def local(filename, k, port, threshold, idnum): # time of last file update lastupdate = 0 # open log if port > 0: # for regular machine, delete old log logfile = './log/loc' + str(idnum) + '_port' + str(port) loclog = open(logfile,'a') loclog.write('LOCAL, k: ' + str(k) + ', threshold: ' + str(threshold) + '\n') loclog.close() else: # for oracle machine, append to old log logfile = './log/oracle' # make dummy entry for greedy alg linelen = 6 # magic number for now, num fields e0 = "z,"*(linelen-1)+"z" # keep track of reps already sent to central machine reps = [] # monitor source file for updates while True: try: if lastupdate < stat(filename).st_mtime: # update timestamp lastupdate = stat(filename).st_mtime # read data lines = open(filename, 'r') V = [] for line in reader(lines): #comma splitting, respects " " if len(line) == linelen: # ignore partial lines V.append(line) else: print line lines.close() # find representatives numpts = len(V) if numpts <= k: S = V score = -1 else: S,score = greedy.greedy(V,V,k,e0) # if it's an oracle, log and return if port < 0: print 'oracle on port '+ str(port) + ', \t time: ' + str(lastupdate) + '\t entries: ' + str(numpts) +'\t oracle score: ' + str(score) loclog = open(logfile,'a') loclog.write(str(lastupdate) + '\t' + str(numpts) + '\t' + str(score) + '\n') loclog.close() return # log time, # datapts, score print 'local ' + str(idnum) + ' on port '+ str(port) + ', \t time: ' + str(lastupdate) + '\t entries: ' + str(numpts) +'\t score: ' + str(score) loclog = open(logfile,'a') loclog.write(str(lastupdate) + '\t' + str(numpts) + '\t' + str(score) + '\n') loclog.close() # compare to preexisting reps if reps and len(S) == k: diff = k for i in range(k): for j in range(len(reps)): if S[i] == reps[j]: diff -= 1 break else: # on first k calculations reps = deepcopy(S) diff = threshold+1 # if sufficient change, send reps to central machine print 'local ' + str(idnum) + ' on port '+ str(port) + ' diff: ' + str(diff) if diff > threshold and S: print 'local ' + str(idnum) + ' on port '+ str(port) + ' sending to central' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('', port)) sock.send(json.dumps((idnum,S))) sock.close() reps = deepcopy(S) except IOError: continue # if data file won't open, keep trying
valor = int(item_data[1].strip()) item = (nome, peso, valor) items_instancia.append(item) else: capacidade_mochila = int(linha.strip()) num_linha = num_linha + 1 print("===>Tamanho da Instância: {0}".format(qtd_items_instancia)) print("===>Capacidade da mochila: {0}".format(capacidade_mochila)) print("===>Usando algorítmo greed") counter = 1 elapsed_time = 0 t = time.process_time() while elapsed_time < 5: items_to_add = greedy.greedy(items_instancia, capacidade_mochila) elapsed_time = time.process_time() - t counter = counter + 1 peso = 0 valor = 0 for item in items_to_add: peso += item[2] valor += item[3] writer.writerow({'instancia': qtd_items_instancia, 'tempo_execucao': elapsed_time/counter, 'valor_mochila': valor, 'peso_mochila': peso, 'capacidade_mochila': capacidade_mochila, 'peso_total': peso_total_items}) print("===> Tempo inicial: {0}".format(t)) print("===> Tempo de execução: {0}".format(elapsed_time)) f.close()
exit(0) money = open(filename, 'r') #Redirect to a stupid name catted from in on command line filename = filename[:-4] sys.stdout = open(filename + "change.txt", "w+") amount = [0] while True: values = money.readline() if not values: break if values == [''] or values[0] == '#' or values[0] == '\n': continue amount = int(money.readline()) values = values.rstrip('\n') values = values.rstrip('\r') values = values.rstrip(']') values = values.lstrip('[') values = values.split(',') values = map(int, values) coinCount = [0] * len(values) coinCount = greedy(amount, values) print coinCount print sum(coinCount) money.close()