def combine_outputs(): output_dir = "outputs" output_Avik = "outputsAvik" output_Raghav = "outputsRaghav" input_dir = "inputs" for input_path in os.listdir(input_dir): graph_name = input_path.split(".")[0] G = read_input_file(f"{input_dir}/{input_path}") Avik_T = read_output_file(f"{output_Avik}/{graph_name}.out", G) Raghav_T = read_output_file(f"{output_Raghav}/{graph_name}.out", G) T = min([Avik_T,Raghav_T], key = lambda x: average_pairwise_distance(x)) write_output_file(T, f"{output_dir}/{graph_name}.out") print("%s Written"%(graph_name))
def combine(folders): inputs = {} best_scores = {} best_outputs = {} for filename in os.listdir(INPUT_PATH): inputs[filename] = read_input_file(INPUT_PATH + filename) for folder in folders: for filename in os.listdir(folder): if filename != '.DS_Store': output_graph = read_output_file(folder + filename, inputs[filename.split('.')[0] + '.in']) if output_graph.number_of_nodes() == 1: best_scores[filename] = 0 best_outputs[filename] = output_graph else: score = average_pairwise_distance_fast(output_graph) if filename not in best_scores: best_scores[filename] = score best_outputs[filename] = output_graph elif filename in best_scores and score < best_scores[filename]: best_scores[filename] = score best_outputs[filename] = output_graph for id in best_outputs: write_output_file(best_outputs[id], OUTPUT_PATH + id)
def solveFile(fileName: str, log = False) -> bool: """ Solve a graph saved in ./inputs/{fileName}.in and output it in output folder. Return if solve file succeed. """ try: G = read_input_file("./inputs/%s.in" % fileName) T = solver.ABC(G, N_EMPLOYED, N_ONLOOKER, N_ITERATIONS, FIRE_LIMIT, TERMINATION_LIMIT, log = log) assert(is_valid_network(G, T)) if os.path.exists("./outputs/%s.out" % fileName): oldT = read_output_file("./outputs/%s.out" % fileName, G) if len(T) == 1 and len(oldT) != 1: write_output_file(T, "./outputs/%s.out" % fileName) return True if len(oldT) == 1 or average_pairwise_distance(oldT) <= average_pairwise_distance(T): # do nothing print("File %s is skipped because old tree is better. " % fileName) return True write_output_file(T, "./outputs/%s.out" % fileName) return True except KeyboardInterrupt: raise KeyboardInterrupt except: # stdout print("ERROR: An error occured when processing on %s: %s" % (fileName, sys.exc_info()[0])) return False
def scorer(filename): input = INPUT_PATH + filename print(input) out_filename = filename.split('.')[0] + '.out' print(OUTPUT_PATH + out_filename) if os.path.isfile(OUTPUT_PATH + out_filename): output_graph = read_output_file(OUTPUT_PATH + out_filename, read_input_file(input)) print(average_pairwise_distance_fast(output_graph))
def make_output_from_dict(rooms_to_students, path, G, s): """ Converts the dictionary of rooms to students to a valid return of the solver and writes to output file Args: rooms_to_students: Dictionary of room to a list of students path: filepath to output file to write dictionary output """ dct = convert_dictionary(rooms_to_students) try: din = parse.read_output_file(path, G, s) except (FileNotFoundError, AssertionError): if (len(rooms_to_students) <= 0): print("Empty Room Configuration") return if (is_valid_solution(dct, G, s, len(rooms_to_students))): parse.write_output_file(dct, path) D = parse.read_output_file(path, G, s) happy2 = calculate_happiness(D, G) print("current happiness of this file: ", happy2) return happy0 = calculate_happiness(din, G) happy1 = calculate_happiness(dct, G) #print("happiness of previous configuration: ", happy0) #print("happiness of this configuration: ", happy1) if ((happy1 > happy0) and (is_valid_solution(dct, G, s, len(rooms_to_students)))): print("Valid") parse.write_output_file(dct, path) D = parse.read_output_file(path, G, s) happy2 = calculate_happiness(D, G) print("current happiness of this file: ", happy2) assert (max(happy1, happy0) == happy2)
def compare_scores(set_size, new_output_path, old_output_path): ''' Compare results of old and new outputs generated from the same input. Args: set_size: size of outputs to compare i.e. small or medium or large new_output_path: directory name of which new outputs are stored old_output_path: directory name of which old outputs are stored Returns: difference: dictionary that stores the difference in shortest path along with the graphs generated by new outputs and old outputs. ''' difference = {} input_path = 'inputs/' + set_size + '/' for input_path in glob.glob(input_path + '*'): name = basename(normpath(input_path))[:-3] G = parse.read_input_file(input_path) new_output = new_output_path + '/' + set_size + '/' + name + '.out' old_output = old_output_path + '/' + set_size + '/' + name + '.out' if os.path.exists(new_output) and os.path.exists(old_output): g1 = parse.read_output_file(G, new_output) g2 = parse.read_output_file(G, old_output) difference[name] = (g1 - g2, g1, g2) return difference
def main(): SOLVERS_FILENAME = 'solvers.txt' INPUT_DIRECTORY = ["our_inputs/large", "our_inputs/medium", "our_inputs/small"] OUTPUT_DIRECTORY = ["our_outputs/large", "our_outputs/medium", "our_outputs/small"] SUBMISSION_DIRECTORY = "outputs" with open(SOLVERS_FILENAME, 'r') as f: solvers = f.read().splitlines() solver = "dummy" while solver not in solvers: solver = input("Please input a solver name.") input_filenames = {} for d in INPUT_DIRECTORY: f_lst = os.listdir(d) f_lst.sort() input_filenames[d] = f_lst all_costs = [] for sizes in OUTPUT_DIRECTORY: size = os.path.basename(sizes) graphs = os.listdir(sizes) graphs.sort() for graph in graphs: if "txt" in graph: continue for f in os.listdir(os.path.join(sizes, graph)): if solver not in f: continue out_file = os.path.join(SUBMISSION_DIRECTORY, graph + '.out') os.makedirs(os.path.dirname(out_file), exist_ok=True) copyfile(os.path.join(sizes, graph, f), out_file) input_path = os.path.join("our_inputs", size, graph) + ".in" g = read_input_file(input_path, 100) tree = read_output_file(out_file, g) cost = average_pairwise_distance(tree) all_costs.append(cost) print(graph, ":", cost) average = sum(all_costs) / len(all_costs) print() print('Overall average cost:', average)
def setup(): finished_file = open(FINISHED_FILE_PATH, 'r') for file in finished_file: finished_files.add(file.split('\n')[0]) for filename in os.listdir(INPUT_PATH): #print(filename) out_filename = filename.split('.')[0] + '.out' if filename not in finished_files: inputs[filename] = read_input_file(INPUT_PATH + filename) max_edge_weight = 0 for edge in inputs[filename].edges: max_edge_weight = max(max_edge_weight, inputs[filename].get_edge_data(edge[0], edge[1])['weight']) max_weight[filename] = max_edge_weight if os.path.isfile(OUTPUT_PATH + out_filename): output_graph = read_output_file(OUTPUT_PATH + out_filename, inputs[filename]) if output_graph.number_of_nodes() == 1: best_scores[filename] = 0 else: best_scores[filename] = average_pairwise_distance_fast(output_graph) else: best_scores[filename] = float('inf')
def setup(inputs, best_scores, best_methods, finished_files): finished_file = open(FINISHED_FILE_PATH, 'r') for file in finished_file: finished_files.add(file.split('\n')[0]) for filename in os.listdir(INPUT_PATH): out_filename = filename.split('.')[0] + '.out' if filename not in finished_files: inputs[filename] = read_input_file(INPUT_PATH + filename) shortest_paths[filename] = nx.shortest_path(inputs[filename]) t_k[filename] = nx.minimum_spanning_tree(inputs[filename], algorithm='kruskal') t_p[filename] = nx.minimum_spanning_tree(inputs[filename], algorithm='prim') t_b[filename] = nx.minimum_spanning_tree(inputs[filename], algorithm='boruvka') min_set = approximation.dominating_set.min_weighted_dominating_set( inputs[filename]) steiner_tree = approximation.steinertree.steiner_tree( inputs[filename], min_set) t_mds[filename] = steiner_tree max_edge_weight = 0 for edge in inputs[filename].edges: max_edge_weight = max( max_edge_weight, inputs[filename].get_edge_data(edge[0], edge[1])['weight']) max_weight[filename] = max_edge_weight if os.path.isfile(OUTPUT_PATH + out_filename): output_graph = read_output_file(OUTPUT_PATH + out_filename, inputs[filename]) if output_graph.number_of_nodes() == 1: best_scores[filename] = 0 else: best_scores[filename] = average_pairwise_distance_fast( output_graph) else: best_scores[filename] = float('inf')
def check(size): output = "smallresult.txt" output = size + "result.txt" print(output, file=open(output, "w")) directory = "small/" directory = size + "/" for filename in os.listdir(directory): #print(filename) if (filename.endswith(".in")): file = filename[:-3] inpath = os.path.join(directory, file + ".in") outpath = os.path.join(directory, file + ".out") G, s = parse.read_input_file(inpath) x = parse.read_output_file(outpath, G, s) uniqueValues = set(x.values()) k = len(uniqueValues) valid = utils.is_valid_solution(x, G, s, k) if (valid == False): print("false output @", file) break happy = utils.calculate_happiness(x, G) print(file, "\tyields", happy, file=open(output, "a"))
def solve_file(files): infile, outfile = files G, T, cost = parse.read_input_file(infile), None, float('inf') if os.path.exists(outfile): try: T = parse.read_output_file(outfile, G) except: print(f"{outfile} could not be read.") return None cost = utils.average_pairwise_distance_fast(T) new_T, new_cost = solve(G, T, cost) if new_cost < cost: parse.write_output_file(new_T, outfile) if LOCK is not None: LOCK.acquire() print(f"New minimum found for {infile}, with cost {new_cost}.") if LOCK is not None: LOCK.release() else: if LOCK is not None: LOCK.acquire() print(f"No new minimum found for {infile}.") if LOCK is not None: LOCK.release()
import os from shutil import copyfile from parse import read_input_file, read_output_file, write_output_file if __name__ == "__main__": test_to_files = {} inputs_to_graphs = {} sizes = ('small', 'medium', 'large') input_dir = "./all_inputs/" output_dir = "./best_outputs/" for size in sizes: for i in range(1, 301): test = size + "-" + str(i) test_to_files[test] = [] inputs_to_graphs[test] = read_input_file(input_dir + test + ".in") for root, dirs, files in os.walk("./"): for file in files: filepath = root + os.sep + file if filepath.endswith(".out"): test = file.split(".")[0] print(filepath, test) test_to_files[test].append( (filepath, read_output_file(inputs_to_graphs[test], filepath))) for test in test_to_files: best_output = max(test_to_files[test], key=lambda item: item[1]) copyfile(best_output[0], output_dir + test + ".out")
from parse import read_input_file, read_output_file, write_output_file import networkx as nx import os import sys import matplotlib.pyplot as plt if __name__ == "__main__": output_dir = "outputs" new_output_dir = "outputs subset" input_dir = "inputs subset" for input_path in os.listdir(input_dir): graph_name = input_path.split(".")[0] print(graph_name) G = read_input_file(f"{input_dir}/{input_path}") # print('Output Graph:', average_pairwise_distance(T)) T = read_output_file(f"{output_dir}/{graph_name}.out", G) T_star = read_output_file(f"{output_dir}/{graph_name}.out", G) old = average_pairwise_distance(T) t_nodes = list(nx.nodes(T)) for u, v, w in G.edges.data('weight'): cur = average_pairwise_distance(T) if u in nx.nodes(T) and v not in nx.nodes(T): T_star.add_node(v) T_star.add_edge(u, v, weight=w) if average_pairwise_distance(T_star) < cur: T.add_node(v) T.add_edge(u, v, weight=w) else: T_star.remove_edge(u, v) T_star.remove_node(v)
from parse import read_input_file, read_output_file, write_output_file if __name__ == "__main__": test_to_files = {} inputs_to_graphs = {} sizes = ('small', 'medium', 'large') input_dir = "./all_inputs/" output_dir = "./best_outputs/" for size in sizes: for i in range(1, 301): test = size + "-" + str(i) test_to_files[test] = [] inputs_to_graphs[test] = read_input_file(input_dir + test + ".in") print( read_output_file(inputs_to_graphs['small-42'], './outputs_set_cover/small-42.out')) print( read_output_file(inputs_to_graphs['small-42'], './output_depth_5/small-42.out')) # ./ outputs_set_cover / small - 19. # out # wow # ./ outputs_set_cover / small - 24. # out # wow # ./ outputs_set_cover / small - 42. # out # wow # ./ outputs_set_cover / small - 48. # out # wow
files = glob.glob('mergeFolder/*') files.sort() improvements = 0 for new_output in files: # Iterates through every file to merge print("Begin processing {}".format(new_output)) input_path = size + "/" + new_output[12:] input_path = input_path[:len(input_path) - 4] + ".in" input_path = "inputs/" + input_path old_output = 'outputs/' + input_path[7:][:-3] + '.out' G = read_input_file(input_path) currBest_distance = read_output_file(G, old_output) this_distance = read_output_file(G, new_output) if currBest_distance < this_distance: improvements += 1 print("Output distance IMPROVED by: " + str(this_distance - currBest_distance)) currBest_file = open(old_output, "w") merge_file = open(new_output, "r") currBest_file.write(merge_file.read()) currBest_file.close() merge_file.close()
# Requires a folder "inputs" with the input files, and two folders "comp1" and "comp2" with the two output sets to compare # The folders should have no subfolders # The folders should have the same files (e.g. for file small-1, there should be inputs/small-1.in, comp1/small-1.out, comp2/small-1.out) # Since this will overwrite the outputs in "comp1", you should make sure those are backed up (push them to Git or something) if __name__ == '__main__': inputs = glob.glob('compinputslarge/*') done = 0 changed = 0 kept = 0 improvement = 0 for input_path in inputs: first_path = 'comp1large/' + basename(normpath(input_path))[:-3] + '.out' second_path = 'comp2large/' + basename(normpath(input_path))[:-3] + '.out' G, s = read_input_file(input_path) try: D1 = read_output_file(first_path, G, s) h1 = calculate_happiness(D1, G) except: h1 = 0 try: D2 = read_output_file(second_path, G, s) h2 = calculate_happiness(D2, G) except: h2 = 0 if h1 + h2 > 0: done += 1 # print("doing #" + str(done) + ": " + input_path) if h1 < h2: write_output_file(D2, first_path) # print("chose comp2: " + str(h2) + " vs. " + str(h1)) changed += 1
def solve(G): global saved_costs, solver_filenames g = GraphSolver(G) for v in list(g.G.nodes): if len( list(g.neighbors(v)) ) == g.n - 1: # Special case when one vertex is connected to all of them g.visit(v) return g.T solvers = [ import_module(solver_filename) for solver_filename in solver_filenames ] skipped_costs = [] skipped_solvers = [] # Don't calculate for inputs we already know costs for deterministically skip = [] if cacher is not None: for i in range(len(solvers)): # It turns out all of our algorithms are not deterministic so that condition is going to be deleted if cacher.is_cached(input_filename, solver_filenames[i]): # if getattr(solvers[i], 'isDeterministic', False) and cacher.is_cached(input_filename, solver_filenames[i]): skipped_costs.append( cacher.get_cost(input_filename, solver_filenames[i])) skip.append(i) skipped_solvers.append(solver_filenames[i]) solver_filenames = [ f for i, f in enumerate(solver_filenames) if i not in skip ] solvers = [s for i, s in enumerate(solvers) if i not in skip] trees = [] # to be populated ############### Parallelizing ######################## if len(solvers) > 0: pool = Pool(len(solvers)) async_solvers = [ pool.apply_async(solver.solve, [G]) for solver in solvers ] trees = [ async_solver.get(1000000000) for async_solver in async_solvers ] pool.close() pool.join() ################ Non - parallelizing #################### # trees = [solver.solve(G) for solver in solvers] ######################################################### # Cache costs costs = [average_pairwise_distance(t) for t in trees] if cacher is not None: for i in range(len(trees)): cacher.cache_if_better_or_none(input_filename, solver_filenames[i], costs[i], None, trees[i]) # Create lists with the same length all_trees = [None] * len(skipped_costs) + trees all_costs = skipped_costs + costs solver_filenames = skipped_solvers + solver_filenames # Sort all_trees = [ tree for c, tree in sorted(zip(all_costs, all_trees), key=lambda pair: pair[0]) ] solver_filenames = [ filename for c, filename in sorted(zip(all_costs, solver_filenames), key=lambda pair: pair[0]) ] all_costs = sorted(all_costs) # Print saved costs second_smallest = all_costs[1] individual_saved_costs = [ second_smallest - cost if second_smallest - cost > 0 else 0 for cost in all_costs ] saved_costs = [sum(x) for x in zip(saved_costs, individual_saved_costs)] print(saved_costs) # Get the tree to return min_tree = all_trees[0] if min_tree is None: out_file = join(OUTPUT_DIRECTORY, input_filename[:-3], solver_filenames[0] + '.out') if isfile(out_file): print('read outfile', out_file) min_tree = read_output_file(out_file, G) else: print( "WARNING: all_prev_outputs.txt is probably out of sync. {} was not found." .format(out_file)) print('Recalculating for input {}'.format(input_filename)) # Recalculate for this input prev_type = cacher.set_cache_type('none') min_tree = solve(G) cacher.set_cache_type(prev_type) return min_tree
assert is_valid_solution(G, c, k) distance = calculate_score(G, c, k) write_output_file(G, c, k, output_path)""" if __name__ == '__main__': inputs = glob.glob('inputs/small/*') count = 1 for input_path in inputs: output_path = 'outputs/small/' + basename( normpath(input_path))[:-3] + '.out' G = read_input_file(input_path) """resultc, resultk, largest = None, None, 0 for i in range(50): c, k = solve(G) if not is_valid_solution(G, c, k): continue currentScore = calculate_score(G, c, k) if largest < currentScore: resultc, resultk = c, k largest = currentScore""" for i in range(100): c, k = solve(G, 10, 0) currentScore = calculate_score(G, c, k) existingSol = read_output_file(G, output_path) if currentScore > existingSol: write_output_file(G, c, k, output_path) print("enhanced by: " + str((currentScore - existingSol) / existingSol) + "%") print(str(count) + " out of " + str(len(inputs)) + " Done.") count += 1
#locations = ['small/', 'medium/', 'large/'] ''' G = read_input_file(inputs[1]) c, k = solve(G) output_path = 'outputs/small/' + path.basename(path.normpath(inputs[1]))[:-3] + '.out' write_output_file(G, c, k, output_path) ''' for location in locations: inputs = glob.glob('inputs/' + location + '*') i = 1 for input_path in inputs: output_path = 'outputs/' + location + path.basename( path.normpath(input_path))[:-3] + '.out' G = read_input_file(input_path) curScore = read_output_file(G, output_path) c, k = solve(G) distance = calculate_score(G, c, k) if distance > curScore: write_output_file(G, c, k, output_path) print("Finished " + location + str(i)) i += 1 ''' endedOn = 125 for num in range(len(inputs) - endedOn): input_path = inputs[endedOn + num] output_path = 'outputs/small/' + path.basename(path.normpath(input_path))[:-3] + '.out' G = read_input_file(input_path) c, k = solve(G) assert is_valid_solution(G, c, k) distance = calculate_score(G, c, k)
def solve(G, s, output_file=''): """ Args: G: networkx.Graph s: stress_budget Returns: D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2} k: Number of breakout rooms """ students = len(G.nodes) # DEFAULT ASSIGNMENT # old_D = read_output_file(output_file, G, s) old_happiness = calculate_happiness(old_D, G) old_assignment = {} for k, v in old_D.items(): old_assignment.setdefault(v, []).append(k) old_rooms = len(old_assignment) def get_D(): new_high, best_D, best_k = 0, None, 100 D = {} for n in range(students): D[n] = 0 nonlocal s # D = read_output_file(output_file, G, s) room_to_student = {} for k, v in D.items(): room_to_student.setdefault(v, []).append(k) def get_room_happiness(arr): if calculate_stress_for_room(arr, G) > s / len(room_to_student): return -100 else: return calculate_happiness_for_room(arr, G) def get_happiness(): if not is_valid_solution(D, G, s, len(room_to_student)): return -100 else: return calculate_happiness(D, G) def swap_happiness(n1, n2): swap(n1, n2) happiness = get_happiness() swap(n1, n2) return happiness def add_student(n1, room): room_to_student[room].append(n1) r1 = room_to_student[D[n1]] old_room = D[n1] D[n1] = room r1.remove(n1) if not r1: room_to_student.pop(old_room) index = 0 temp = {} for r in room_to_student.keys(): temp[index] = room_to_student[r] index += 1 room_to_student.clear() for k, v in temp.items(): room_to_student[k] = v D.clear() for k, v in convert_dictionary(room_to_student).items(): D[k] = v def add_happiness(n1, room): old_room = room_to_student[D[n1]][:] old_room.remove(n1) new_room = room_to_student[room][:] new_room.append(n1) happiness_old = get_room_happiness(old_room) happiness_new = get_room_happiness(new_room) if happiness_new > 0: return happiness_new + happiness_old else: return happiness_new def swap(n1, n2): r1, r2 = room_to_student[D[n1]], room_to_student[D[n2]] i1, i2 = r1.index(n1), r2.index(n2) r1[i1], r2[i2] = n2, n1 D[n2], D[n1] = D[n1], D[n2] def remove(n1): r1 = room_to_student[D[n1]] if len(r1) > 1: r1.remove(n1) D[n1] = len(room_to_student) room_to_student[D[n1]] = [n1] def maybe_swap(n1, n2, T): curr_hap = get_happiness() swap_hap = swap_happiness(n1, n2) delta = curr_hap - swap_hap # print(n1, n2, swap_hap, curr_hap, r, p) r = random.random() if delta < 0: swap(n1, n2) elif swap_hap > 0 and r < math.exp(-delta / T): swap(n1, n2) def maybe_add(n1, T): room = random.randrange(len(room_to_student)) curr_hap = get_room_happiness(room_to_student[room]) curr_hap += get_room_happiness(room_to_student[D[n1]]) add_hap = add_happiness(n1, room) delta = curr_hap - add_hap # print(n1, n2, swap_hap, curr_hap, r, p) r = random.random() if delta < 0: add_student(n1, room) elif add_hap > 0 and r < math.exp(-delta / T**2): add_student(n1, room) print('---Original Stress: ', s, ' Original Happiness: ', old_happiness, 'Orig. Rooms: ', old_rooms) # original_s = s # s = 1.5 * s loops = 100 for countdown in range(loops * 5, loops * 4, -1): # if s > original_s: # s -= (loops - countdown + 1)**2 * s / loops # if s < original_s: # s = original_s curr, curr_rooms = get_happiness(), len(room_to_student) print(curr, 'Stress: ', s, 'Rooms: ', curr_rooms, countdown) # if curr > new_high and is_valid_solution(D, G, s, curr): # new_high, best_D, best_k = curr, D.copy(), curr_rooms # else: # print(curr, 'Stress: ', s, 'Rooms: ', curr_rooms, countdown) # break for _ in range(students * 4): curr, curr_rooms = get_happiness(), len(room_to_student) print(curr, 'Stress: ', s, 'Rooms: ', curr_rooms, countdown) n1, n2 = floor(random.randrange(students)), floor( random.randrange(students)) # ADD CASE if random.random() < countdown / (loops) and countdown > loops: maybe_add(n1, countdown) # REMOVE CASE if random.random() < countdown / (loops * 1000) and curr < -50: remove(n1) # SWAP CASE if D[n1] != D[n2]: maybe_swap(n1, n2, countdown) # if best_D and is_valid_solution(best_D, G, s, best_k): # return best_D, best_k return D, len(room_to_student) output, rooms = get_D() new_happiness = calculate_happiness(output, G) validity = is_valid_solution(output, G, s, rooms) if new_happiness > old_happiness and validity: print("Nice! Original: ", old_happiness, "New: ", new_happiness, validity) return output, rooms else: print("sadness :( Original: ", old_happiness, "New: ", new_happiness, validity) print('Original Stress: ', s, ' Original Happiness: ', old_happiness, 'Orig. Rooms: ', old_rooms) print() return None
overall_improvements = 0 # Counts the number of outputs improved inputs = glob.glob('inputs/*') for input_path in inputs: # Iterate through folders in inputs files = glob.glob(input_path + "/*") for file_path in files: # Iterates through every file in every folder print("Begin processing {}".format(file_path)) G = read_input_file(file_path) # Reads in the next graph size = input_path[7:] v, e = solve(G, size) # Calculates the list of vertices (v) and edges (e) to remove output_path = 'outputs/' + file_path[7:][:-3] + '.out' currBest_distance = read_output_file(G, output_path) #currBest_distance = -1 # DEBUG this_distance = calculate_score(G, v, e) if currBest_distance >= this_distance: print("Current output is better or equal to this output. No output file written.") else: overall_improvements += 1 print("Output distance IMPROVED by: " + str(this_distance - currBest_distance)) print("NEW shortest path is length: " + str(this_distance)) write_output_file(G, v, e, output_path) print("TOTAL OUTPUTS IMPROVED: " + str(overall_improvements)) # Here's an example of how to run your solver.
print("Best Alg: " + str(optimal_algorithm)) print("Score: " + str(alg_score) + "%") # To run: python3 solver.py inputs if __name__ == '__main__': assert len(sys.argv) == 2 arg_path = sys.argv[1] alg_quality = {} total = 0 input_graphs = os.listdir(arg_path) total_dist = 0 for graph_in in input_graphs: #print("---------------") #print("Calculating Minimal Tree for: " + graph_in) G = read_input_file(arg_path + '/' + graph_in) # foo() T, alg, avgdist = solve(G) #solve will return both the graph T and the optimal algorithm name. if (alg in alg_quality): alg_quality[alg] += 1 else: alg_quality[alg] = 1 assert is_valid_network(G, T) # print("Average pairwise distance: {}".format(average_pairwise_distance(T))) graph_out = 'outputs/' + graph_in[:len(graph_in) - 3] + '.out' write_output_file(T, graph_out) read_output_file(graph_out, G) total += 1 total_dist += avgdist print_best_algorithm(alg_quality, total) print("AVG OF AVGS (minimize this): " + str(total_dist / total))
redo = [] num_inputs = len(inputs) for input_path in inputs[2:]: print("Filename:", input_path, "Input", i, "out of", str(num_inputs) + "...") i += 1 output_path_num = int( os.path.basename(os.path.normpath(input_path))[:-3].split("-")[1]) if output_path_num in blacklist: print("Skipping Blacklist Num...") continue G, s = read_input_file(input_path, 100) output_path = 'medium_outputs/' + os.path.basename( os.path.normpath(input_path))[:-3] + '.out' D = read_output_file(output_path, G, s) output_happiness = calculate_happiness(D, G) print("Current Happiness:", output_happiness) D_new, k_new, val_new = verify(G, s, output_happiness) print("Returned Happiness", val_new) if D_new and round(val_new, 3) > round(output_happiness, 3): new_happiness = calculate_happiness(D_new, G) print(new_happiness, val_new) assert round(new_happiness, 3) == round(val_new, 3) assert is_valid_solution(D_new, G, s, k_new) print("New Happiness Found:", new_happiness) print() write_output_file(D_new, output_path) redo.append(input_path) else:
# #write file # output_path = "outputs/" + number + ".out" # write_output_file(D, output_path) # D = read_output_file(output_path, G, s) # print("Total Happiness: {}".format(cost_t)) # For testing a folder of inputs to create a folder of outputs, you can use glob (need to import it) if __name__ == '__main__': inputs = glob.glob('inputs/*') for input_path in inputs: output_path = 'outputs/' + basename(normpath(input_path))[:-3] + '.out' G, s = read_input_file(input_path) # Check output file savedrooms = read_output_file(output_path, G, s) savedhappiness = calculate_happiness(savedrooms, G) # Find the size of file t_end = 0 size = basename(normpath(input_path)).split("-")[0] # print(size) if size == "small": t_end = 10 elif size == "medium": t_end = 50 elif size == "large": t_end = 120 t_end = time.time() + t_end # Solving
return T # Here's an example of how to run your solver. # Usage: python3 solver.py test.in if __name__ == '__main__': assert len(sys.argv) == 3 path = sys.argv[1] rang = sys.argv[2] print(path) G = read_input_file(path) start = time.time() try: current_T = read_output_file( 'outputs/' + path.split('.')[0].split('/')[1] + '.out', G) if current_T.number_of_nodes() > 1: if G.number_of_edges() < 24: # DON'T USE MP, MUCH SLOWER SINCE DATA HAS TO BE COPIED TO PROCESSORS!!! # T = solve_edge_combinations_brute_force_MP(G) T = solve_edge_combinations_brute_force(G) assert is_valid_network(G, T) if len(T) == 1 or average_pairwise_distance( T) < average_pairwise_distance(current_T): write_output_file( T, 'outputs/' + path.split('.')[0].split('/')[1] + '.out') print("Old pairwise distance: {}".format( average_pairwise_distance(current_T)))
print() print("Trying file: " + path) G = read_input_file(p + '/' + path) T, met = solve(G) if (met in methods): methods[met] += 1 else: methods[met] = 1 assert is_valid_network(G, T) print("Average pairwise distance: {}".format( average_pairwise_distance(T))) out = 'out/' + path[:len(path) - 3] out = out + '.out' # print('output path: ' + out) write_output_file(T, out) read_output_file(out, G) total += 1 best_method = max(methods, key=methods.get) percent = (float)(methods[best_method] * 100) / total print() print("The best method is " + str(best_method) + ", at " + str(percent) + "%") for m in methods: print(str(m) + ": " + str((methods[m] * 100) / total) + "%") # Avg-weight/Cost-Checking Hybird Method: # this is outperformed by full cost-checking method, # an I'm not sure why. rip. this is what it does: # First, Use avg to cull obvious large leaf edges: # Remove edges with weights that are # greater than or equal to the average,
import sys import matplotlib.pyplot as plt sys.path.append("./project-sp21-skeleton") from parse import read_input_file, read_output_file from maximizeShortestPath import shortestPath, pathLength if __name__ == '__main__': number = sys.argv[1] size = sys.argv[2] file_path = "savedInputs/inputs/" + size + "/" + size + "-" + number + ".in" G = read_input_file(file_path) path = 'project-sp21-skeleton/outputs/' + size + "/" + size + '-' + number + ".out" distance = read_output_file(G, path) target = G.number_of_nodes() - 1 print("Target is: " + str(target)) print("Old improvement: " + str(distance)) # Manually remove edges H = G.copy() H.remove_edges_from([(9, 21), (27, 26), (33, 34), (2, 3), (19, 18), (23, 63), (59, 60), (10, 11), (34, 54), (53, 54), (23, 24), (35, 34), (43, 44)]) oldSP = pathLength(G, shortestPath(G, target)) newSP = pathLength(H, shortestPath(H, target)) print("New improvement: " + str(newSP - oldSP)) pos = nx.kamada_kawai_layout(H)
import sys import os import json from parse import read_input_file, validate_file, read_output_file if __name__ == '__main__': outputs_dir = sys.argv[1] submission_name = sys.argv[2] submission = {} scores = {} for folder in os.listdir("inputs"): if not folder.startswith('.'): for input_path in os.listdir("inputs/" + folder): G = read_input_file(f"inputs/{folder}/{input_path}") graph_name = input_path.split('.')[0] output_file = f'{outputs_dir}/{folder}/{graph_name}.out' if os.path.exists(output_file) and validate_file(output_file): output = open( f'{outputs_dir}/{folder}/{graph_name}.out').read() submission[input_path] = output scores[graph_name] = round( read_output_file(G, output_file) * 1000) / 1000 with open(submission_name, 'w') as f: f.write(json.dumps(submission)) with open("../real-number-one-leaderboard/scores.json", 'w') as f: f.write(json.dumps(scores))