Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
def do_file(file,folder, min_size, max_size):
    print("reading:", file)
    graph = read_input_file(folder+file, min_size=min_size, max_size=max_size)
    orig = graph.copy()
    best_score = 0
    final_ans = None
    best_depth = 0
    for d in range(4,5):
        graph = orig.copy()
        global abort
        if abort:
            break
        abort = False
        global start_time
        start_time = time.time()
        ans, score = find_longest_path_setup(graph, d)
        if score >= best_score and ans:
            final_ans = ans
            best_score = score
            best_depth = d
    if abort:
        print("too long")
        abort = False
    write_output_file(orig, final_ans[1], final_ans[0], "./outputs/" + file.split(".")[0] + ".out")
    print("best score:",best_score,"best depth:",best_depth,"ANSWER:", final_ans )
Ejemplo n.º 4
0
def makeAllOutputFiles():
    for file in os.listdir("inputs"):
        if file.endswith(".in"):
            print(os.path.join("inputs", file))  #input file
            input_path = os.path.join("inputs", file)
            G = read_input_file(input_path)
            T = solve(G)
            assert is_valid_network(G, T)

            #use brute force for small graphs
            if file.startswith("small") and len(T) > 2:
                print("Trying brute forcing on SMALL file: " +
                      os.path.join("inputs", file))  #input file
                BRUTE_TREE = maes_second_dumbass_brute_force(G)
                if average_pairwise_distance_fast(
                        BRUTE_TREE) <= average_pairwise_distance_fast(T):
                    print("Small brute-force alg WINS.")
                    T = BRUTE_TREE
                else:
                    print("Solver alg WINS.")
                    #nothing happens

            #print("Average pairwise distance: {}".format(average_pairwise_distance_fast(T)))
            outname = os.path.splitext(file)[0] + '.out'
            output_path = os.path.join("outputs", outname)
            print(output_path + "\n")
            write_output_file(T, output_path)
            assert validate_file(output_path) == True
Ejemplo n.º 5
0
def do_file(file, folder, min_size, max_size):
    print("reading:", file)
    graph = read_input_file(folder + file, min_size=min_size, max_size=max_size)
    orig = graph.copy()
    ans = find_longest_path_setup(graph, 3)
    write_output_file(orig, ans[1], ans[0], "./outputs/" + file.split(".")[0] + ".out")
    print("ANSWER:", ans)
Ejemplo n.º 6
0
def solver_multi_threading(i, depth=1000):
    path = "inputs/{}-{}.in".format(i[0], i[1])

    G = read_input_file(path)
    print("Input  {} success!".format(path))
    T = solve(G, depth)
    #print("Average pairwise distance: {}".format(average_pairwise_distance_fast(T)))

    print("Output {} success!".format(path))
    write_output_file("outputs/{}-{}.out".format(i[0], i[1]), T)
Ejemplo n.º 7
0
def take_both(word, num):
    G, s = read_input_file('inputs/' + word + '-' + str(num) + '.in')
    sree = kcluster_beef(G, s)
    m = max([use_greedy_happystress(G, s) for i in range(100)],
            key=lambda x: calculate_happiness(x, G))
    if calculate_happiness(sree, G) > calculate_happiness(m, G):
        print(calculate_happiness(sree, G))
        write_output_file(sree, 'outputs/' + word + '-' + str(num) + '.out')
    else:
        print(calculate_happiness(m, G))
        write_output_file(m, 'outputs/' + word + '-' + str(num) + '.out')
Ejemplo n.º 8
0
def single_file(lol):
    path = 'inputs/small/small-' + str(lol) + '.in'
    # path = 'test.in'
    # path = 'inputs/medium/medium-' + str(lol) +  '.in'
    # path = 'inputs/large/large-' + str(lol) +  '.in'
    G = read_input_file(path)
    print(G.nodes)
    # c, k = solve2(G)
    c, k = solve2(G)
    assert is_valid_solution(G, c, k)
    print("Shortest Path Difference: {}".format(calculate_score(G, c, k)))
    write_output_file(G, c, k, 'small-test.out')
Ejemplo n.º 9
0
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))
Ejemplo n.º 10
0
def solve_graph(config):
    input_filenames, cacher = config
    for input_filename in input_filenames:
        global all_costs
        global all_times
        costs_iter = iter(all_costs)
        times_iter = iter(all_times)
        # print("File name:", input_filename)
        # for each solver
        for solver_filename in solvers:
            costs = []
            times = []
            # get the solver from module name
            mod = import_module(solver_filename)
            solve = getattr(mod, 'solve')

            # pass these to the combined solver
            mod.cacher = cacher
            mod.OUTPUT_DIRECTORY = OUTPUT_DIRECTORY
            mod.input_filename = input_filename 

            if input_filename == 'small-206.in':
                print('stop!')  # breakpoint for debugging

            input_path = os.path.join(INPUT_DIRECTORY, input_filename)
            graph = read_input_file(input_path, MAX_SIZE)
            start = time()
            tree = solve(graph)
            end = time()
            times.append(end - start)

            if not is_valid_network(graph, tree):
                print(solver_filename, 'is invalid!')
                nx.draw(graph)
                return

            # print(solver_filename, 'Nodes: ', tree.nodes)
            # for e in tree.edges:
            #     print("edge:", e, "; weight:", weight(graph, e))
            cost = average_pairwise_distance(tree)
            print(solver_filename, 'running', input_filename, '\n Average cost: ', cost, '\n Average time:', sum(times) / len(times), '\n')
            costs.append(cost)

            out_file = os.path.join(OUTPUT_DIRECTORY, input_filename[:-3], solver_filename + '.out')
            os.makedirs(os.path.dirname(out_file), exist_ok=True)
            write_output_file(tree, out_file)
Ejemplo n.º 11
0
def main():
    already_done = [
        1, 2, 4, 6, 7, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 26, 29, 30, 33,
        34, 35, 38, 39, 40, 41, 43, 46, 47, 50, 51, 52, 53, 54, 55, 56, 58, 59,
        60, 63, 64, 70, 73, 74, 76, 77, 79, 81, 83, 84, 85, 88, 89, 90, 96,
        100, 101, 103, 105, 109, 110, 111, 112, 113, 114, 115, 117, 119, 121,
        122, 123, 125, 128, 129, 131, 132, 134, 136, 137, 140, 141, 143, 145,
        147, 151, 152, 156, 157, 158, 159, 160, 161, 162, 166, 167, 169, 172,
        174, 175, 177, 178, 181, 184, 187, 196, 199, 201, 202, 203, 206, 207,
        208, 209, 213, 216, 217, 218, 220, 222, 223, 226, 227, 230, 233, 235,
        237, 238, 240, 241
    ]
    # already_done = [7, 18, 33, 43, 51, 54, 56, 65, 69, 73, 77, 81, 91, 112, 114, 121, 123, 127, 131, 134, 151, 169, 171, 174, 178, 184, 187, 201, 202, 207, 213, 215, 222]
    """
    inputs = glob.glob('compinputslarge/*')
    couldnt = []
    done = 0
    for i in range(len(inputs)):
        input_path = inputs[i]
        
        done += 1
        print("doing #" + str(done) + ": " + input_path)
        output_path = 'comp2large/' + basename(normpath(input_path))[:-3] + '.out'
        G, s = read_input_file(input_path)
        D, k = solve(G, s)
        if k != -1:
            assert is_valid_solution(D, G, s, k)
            write_output_file(D, output_path)
            # print("done, used " + str(k) + " rooms")
        else:
            couldnt += [input_path]
    
    """
    num = int(sys.argv[1])
    moves = int(sys.argv[2])
    print("Doing #" + str(num))
    if num not in already_done:
        input_path = "compinputsmed/medium-" + str(num) + ".in"
        current_sol_path = "comp1med/medium-" + str(num) + ".out"
        output_path = "comp2med/medium-" + str(num) + ".out"
        G, s = read_input_file(input_path)
        D, k = solve(G, s, load=current_sol_path, moves=moves)
        if k != -1:
            assert is_valid_solution(D, G, s, k)
            write_output_file(D, output_path)
def main(filename):
    # print(filename, end=": ")
    random.seed(datetime.now())
    input_name = filename[0:-3]
    path = str(pathlib.Path().absolute()) + "/inputs/" + input_name + '.in'
    G = read_input_file(path)
    found = False
    # degrees = G.degree(list(G.nodes()))
    # for deg in degrees:
    #     if deg[1] == len(degrees) - 1:
    #         edges = list(G.edges(deg[0]))
    #         if len(edges) != len(degrees) - 1:
    #             continue
    #         found = True
    #         T = nx.Graph()
    #         T.add_node(deg[0])
    #         break

    # print("Density: " + str(nx.density(G)))
    if not found:
        T = solve(G)
        # T = solveConstructively(G)

    assert is_valid_network(G, T)
    score = average_pairwise_distance(T)

    scores = {}
    try:
        scoresFile = open('scores.obj', 'rb')
    except:
        pickle.dump(scores, open('scores.obj', 'wb'))
    scores = pickle.load(open('scores.obj', 'rb'))

    better = False

    if input_name not in scores or score < scores[input_name]:
        # print("Found better solution!")
        scores[input_name] = score
        better = True
        output_path = str(
            pathlib.Path().absolute()) + "/outputs/" + input_name + '.out'
        write_output_file(T, output_path)
        pickle.dump(scores, open('scores.obj', 'wb'))
    return (input_name, better, scores[input_name])
Ejemplo n.º 13
0
def repeatedly_solve(path):
    G, s = read_input_file("inputs/" + path + ".in")
    solutions = []
    happiness = []
    for i in range(5):
        D, k = solve_helper(G, s, 12, 0, 0)
        assert is_valid_solution(D, G, s, k)
        # write_output_file(D, "outputs_manual/" + str(path) + "_ratio_" + str(i) + ".out")
        solutions.append(D)
        happiness.append(calculate_happiness(D, G))
    print("i'm done with 5 only ratio")
    for i in range(5):
        D, k = solve_helper(G, s, 0, 12, 0)
        assert is_valid_solution(D, G, s, k)
        # write_output_file(D, "outputs_manual/" + str(path) + "_happiness_" + str(i) + ".out")
        solutions.append(D)
        happiness.append(calculate_happiness(D, G))
    print("i'm done with 5 only happiness")
    for i in range(5):
        D, k = solve_helper(G, s, 0, 0, 12)
        assert is_valid_solution(D, G, s, k)
        # write_output_file(D, "outputs_manual/" + str(path) + "_stress_" + str(i) + ".out")
        solutions.append(D)
        happiness.append(calculate_happiness(D, G))
    print("i'm done with 5 only stress")
    for i in range(5):
        D, k = solve_helper(G, s, 5, 5, 5)
        assert is_valid_solution(D, G, s, k)
        # write_output_file(D, "outputs_manual/" + str(path) + "_all_3_" + str(i) + ".out")
        solutions.append(D)
        happiness.append(calculate_happiness(D, G))
    print("i'm done with 5 all 3")
    print(happiness)
    max_happiness = max(happiness)
    best_index = 0
    print(max_happiness)
    for i in range(20):
        if happiness[i] == max_happiness:
            best_index = i
    print(best_index)
    write_output_file(solutions[best_index], "out_manual/" + str(path) + ".out")
Ejemplo n.º 14
0
def makeAllOutputFiles():
    for file in os.listdir("inputs"):
        if file.endswith(".in"):
            print(os.path.join("inputs", file))  #input file
            input_path = os.path.join("inputs", file)
            G = read_input_file(input_path)
            try:
                T = solve(G)
            except:
                print("ERRORED OUT. CONTINUE ANYWAY")
                T = G
            assert is_valid_network(G, T)

            #randomization optimization
            if len(T) > 2:
                print("Trying randomization to find better result..")
                try:
                    betterT = maes_randomization_alg(
                        G, T, 100)  #50 iterations of randomness
                except:
                    print("ERRORED OUT. CONTINUE ANYWAY")
                    betterT = G
                assert is_valid_network(G, betterT)

                if average_pairwise_distance_fast(
                        betterT) < average_pairwise_distance_fast(T):
                    print("BETTER TREE FOUND.")
                    T = betterT
                else:
                    print("No improvements.")
                    #nothing happens

            #print("Average pairwise distance: {}".format(average_pairwise_distance_fast(T)))
            outname = os.path.splitext(file)[0] + '.out'
            output_path = os.path.join("outputs", outname)
            print(output_path + "\n")
            write_output_file(T, output_path)
            assert validate_file(output_path) == True
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
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()
Ejemplo n.º 17
0
    """
    Args:
        G: networkx.Graph

    Returns:
        T: networkx.Graph
    """
    solver = LocalSearchSolver(G)
    T = solver.solve()
    return T


# Here's an example of how to run your solver.

# Usage: python3 solver.py test.in

if __name__ == '__main__':
    paths = sys.argv[1:]

    for i in tqdm(range(len(paths))):
        path = paths[i]
        G = read_input_file(path)
        T = solve(G)
        assert is_valid_network(G, T)

        print("=" * 30)
        print("Average pairwise distance: {}".format(
            average_pairwise_distance_fast(T)))
        output = path.split('/')[-1].split('.')[0]
        write_output_file(T, 'outputs/{}.out'.format(output))
Ejemplo n.º 18
0
            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.

# Usage: python3 solver.py test.in

# if __name__ == '__main__':
#     assert len(sys.argv) == 2
#     path = sys.argv[1]
#     G = read_input_file(path)
#     c, k = solve(G)
#     assert is_valid_solution(G, c, k)
#     print("Shortest Path Difference: {}".format(calculate_score(G, c, k)))
Ejemplo n.º 19
0
 #testing = False
 # if testing:
 #     path = 'small-4.in'
 #     G = read_input_file('inputs/' + path)
 #     print(path)
 #     T = findTree(G)
 #     assert is_valid_network(G, T)
 #     print("Average pairwise distance: {}\n".format(average_pairwise_distance(T)))
 # else:
 if True:
     files = sorted([
         filename for root, dirs, file in os.walk("./inputs")
         for filename in file
     ],
                    key=lambda x: int(
                        x.replace('large-', '').replace('small-', '').
                        replace('medium-', '').replace('.in', '')))
     for count, f in enumerate(files, 1):
         G = read_input_file("./inputs/" + f)
         print(count)
         print(f)
         T = findTree(G)
         assert is_valid_network(G, T)
         print("Average pairwise distance: {}\n".format(
             average_pairwise_distance(T)))
         write_output_file(T, f'out/{f.replace(".in", ".out")}')
     files = [
         filename for root, dirs, file in os.walk("./out")
         for filename in file
     ]
     print(len(files))
Ejemplo n.º 20
0
    print(G.nodes)
    # c, k = solve2(G)
    c, k = solve2(G)
    assert is_valid_solution(G, c, k)
    print("Shortest Path Difference: {}".format(calculate_score(G, c, k)))
    write_output_file(G, c, k, 'small-test.out')


if __name__ == '__main__':
    # single_file(62)
    for i in range(1, 301):
        print("INPUT: ", i)
        path = 'inputs/medium/medium-' + str(i) + '.in'
        G = read_input_file(path)
        c, k = solve2(G)
        assert is_valid_solution(G, c, k)
        print("Shortest Path Difference: {}".format(calculate_score(G, c, k)))
        output_path = 'outputs/medium-' + str(i) + '.out'
        write_output_file(G, c, k, output_path)

# 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 = read_input_file(input_path)
#         c, k = solve(G)
#         assert is_valid_solution(G, c, k)
#         distance = calculate_score(G, c, k)
#         write_output_file(G, c, k, output_path)
Ejemplo n.º 21
0
    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)))
                else:
                    print("not better pairwise dist: " +
                          str(average_pairwise_distance(current_T)))
                if len(T) == 1:
                    print("MP_edge_brute_force new pairwise distance: 0")
                else:
                    print(
                        "MP_edge_brute_force new pairwise distance: {}".format(
                            average_pairwise_distance(T)))
            else:
                #     not using this because it takes too long and isn't an actual brute force (the other approximations work better)
                #     if G.number_of_nodes() < 24:
Ejemplo n.º 22
0
    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))
Ejemplo n.º 23
0
 def write_best_graph():
     filename = id.split('.')[0]
     write_output_file(G, OUTPUT_PATH + filename + '.out')
     print(method + ' ' + id)
Ejemplo n.º 24
0
if __name__ == '__main__':
    assert len(sys.argv) == 2
    total_pairwise_distance = 0
    #to run on all inputs: python3 solver.py all_inputs
    if sys.argv[1] == "all_inputs":

        for i in range(266, 304):
            path = 'inputs/small-' + str(i) + '.in'
            G = read_input_file(path)
            T = solve(G)
            assert is_valid_network(G, T)
            total_pairwise_distance += average_pairwise_distance(T)
            print(path + " Average Pairwise Distance: {}".format(
                average_pairwise_distance(T)))
            path_string = re.split('[/.]', path)
            write_output_file(T, 'outputs/' + path_string[1] + '.out')
        print(" Total Average Small Pairwise Distance: {}".format(
            total_pairwise_distance / 303))

        for i in range(1, 304):
            path = 'inputs/medium-' + str(i) + '.in'
            G = read_input_file(path)
            T = solve(G)
            assert is_valid_network(G, T)
            total_pairwise_distance += average_pairwise_distance(T)
            print(path + " Average Pairwise Distance: {}".format(
                average_pairwise_distance(T)))
            path_string = re.split('[/.]', path)
            write_output_file(T, 'outputs/' + path_string[1] + '.out')
        print(" Total Average Medium Pairwise Distance: {}".format(
            total_pairwise_distance / 303))
Ejemplo n.º 25
0



# Here's an example of how to run your solver.

# Usage: python3 solver.py test.in

if __name__ == '__main__':
    assert len(sys.argv) == 2
    path = sys.argv[1]
    G = read_input_file(path)
    c, k = solve(G)
    assert is_valid_solution(G, c, k)
    print("Shortest Path Difference: {}".format(calculate_score(G, c, k)))
    write_output_file(G, c, k, 'my_out/30.out')


# 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('my_in/*')
#     for input_path in inputs:
#         output_path = 'my_out/' + basename(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)
#         write_output_file(G, c, k, output_path)

# For testing a folder of inputs to create a folder of outputs, you can use glob (need to import it)
# if __name__ == '__main__':
Ejemplo n.º 26
0
        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)
            elif v in nx.nodes(T) and u not in nx.nodes(T):
                T_star.add_node(u)
                T_star.add_edge(v, u, weight=w)
                if average_pairwise_distance(T_star) < cur:
                    T.add_node(u)
                    T.add_edge(v, u, weight=w)
                else:
                    T_star.remove_edge(v, u)
                    T_star.remove_node(u)

        new = average_pairwise_distance(T)
        if new < old:
            if is_valid_network(G, T):
                write_output_file(T, f"{output_dir}/{graph_name}.out")
                print("Overwritten %s" % (graph_name))
            else:
                continue
        else:
            continue
Ejemplo n.º 27
0
                maxLenPath = length

    return nodeToRemove


# Here's an example of how to run your solver.

# Usage: python3 solver.py test.in

if __name__ == '__main__':
    assert len(sys.argv) == 2
    path = sys.argv[1]
    print(path)
    G = read_input_file(path)
    c, k = solve(G)
    assert is_valid_solution(G, c, k)
    print("Shortest Path Difference: {}".format(calculate_score(G, c, k)))
    write_output_file(G, c, k, 'outputs' + path[6:-2] + 'out')

# 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/large/*')
#     for input_path in inputs:
#         print(input_path)
#         output_path = 'outputs/large/' + basename(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)
#         write_output_file(G, c, k, output_path)
Ejemplo n.º 28
0
                    T.add_edge(node,
                               node2,
                               weight=G.get_edge_data(node, node2)['weight'])
                    new_average = average_pairwise_distance(T)
                    if new_average > current_average:
                        T.remove_node(node2)
                        #T.remove_edge(node, node2)
                    else:
                        current_average = new_average
                        print("Adding an edge between", node, "and", node2,
                              "yields average", new_average)

    print("Dominating vertices:", [node for node in T])

    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) == 2
    path = sys.argv[1]
    G = read_input_file(path)
    T = solve(G)
    assert is_valid_network(G, T)
    print("Average  pairwise distance: {}".format(
        average_pairwise_distance(T)))
    write_output_file(T, 'out/test.out')
Ejemplo n.º 29
0
room += 1
D[25] = room
D[31] = room
room += 1
D[26] = room
D[29] = room
room += 1
D[27] = room
D[49] = room
room += 1
D[30] = room
D[48] = room
room += 1
D[32] = room
D[38] = room
room += 1
D[33] = room
D[45] = room
room += 1
D[35] = room
D[36] = room
room += 1
D[40] = room
D[42] = room
room += 1
k = len(set(D.values()))
assert is_valid_solution(D, G, s, k)
print("Total Happiness: {}".format(calculate_happiness(D, G)))
output_path = "out/other/large-169.out"
write_output_file(D, output_path)
Ejemplo n.º 30
0
# Usage: python3 solver.py test.in

if __name__ == '__main__':
    assert len(sys.argv) == 2
    path = sys.argv[1]
    G, s = read_input_file(path)

    start = time.time()
    D, k = solve(G, s)
    end = time.time()

    assert is_valid_solution(D, G, s, k)
    print("Total Happiness: {}".format(calculate_happiness(D, G)))
    print("Solving took {} seconds.".format(end - start))
    if path[-3:] == ".in":
        write_output_file(D, f'{path[:-3]}.out')
    else:
        write_output_file(D, f'test/test.out')

# 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('file_path/inputs/*')
#     for input_path in inputs:
#         output_path = 'file_path/outputs/' + basename(normpath(input_path))[:-3] + '.out'
#         G, s = read_input_file(input_path, 100)
#         D, k = solve(G, s)
#         assert is_valid_solution(D, G, s, k)
#         cost_t = calculate_happiness(T)
#         write_output_file(D, output_path)