コード例 #1
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)
コード例 #2
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
コード例 #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 )
コード例 #4
0
ファイル: abc_client.py プロジェクト: tsunrise/cs170-proj
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
コード例 #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)
コード例 #6
0
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))
コード例 #7
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)
コード例 #8
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')
コード例 #9
0
def heuristic_avg_cost(params):
    """
	Loss function of average cost over training graphs.
	"""
    total_cost, count = 0, 0
    for input in os.listdir('training/'):
        G = read_input_file('training/' + input)
        T = dijkstra_two_solve(G, [p1, p2, p3, p4])
        assert is_valid_network(G, T)
        total_cost += average_pairwise_distance_fast(T)
        count += 1
    return total_cost / count
コード例 #10
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')
コード例 #11
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))
コード例 #12
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)
コード例 #13
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)
コード例 #14
0
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])
コード例 #15
0
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)
コード例 #16
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")
コード例 #17
0
def calculate_best_scores():
    best_sols = dict()
    error = []
    for folder in os.listdir("inputs"):
        for file in os.listdir(f'inputs/{folder}'):
            graph_name = file.split('.')[0]
            #print(graph_name)
            output_file = f'outputs/{folder}/{graph_name}.out'
            try:
                G = parse.read_input_file(f'inputs/{folder}/{graph_name}.in')
                score, cities, edges = parse.read_output_file2(G, output_file)
                best_sols[graph_name] = {
                    "score": score,
                    "c": cities,
                    "e": edges
                }
            except AssertionError:
                error.append(graph_name)

    print(error)

    return best_sols
コード例 #18
0
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')
コード例 #19
0
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"))
コード例 #20
0
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')
コード例 #21
0
ファイル: solver.py プロジェクト: maewang00/cs170-final-proj
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
コード例 #22
0
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
コード例 #23
0
ファイル: solver.py プロジェクト: chfog/cs170project
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()
コード例 #24
0
import networkx as nx
from parse import read_input_file, write_output_file
from utils import is_valid_solution, calculate_happiness, calculate_stress_for_room, convert_dictionary
import sys
import copy

path = "inputs/large/large-169.in"
G, s = read_input_file(path)

D = {}
room = 0
D[0] = room
D[46] = room
room += 1
D[1] = room
D[10] = room
room += 1
D[2] = room
D[44] = room
room += 1
D[3] = room
D[22] = room
room += 1
D[4] = room
D[28] = room
room += 1
D[5] = room
D[14] = room
room += 1
D[6] = room
D[16] = room
コード例 #25
0
import networkx as nx
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))
コード例 #26
0
    return genMaxShortestPath(G, nodeLimit, edgeLimit)


# For testing a folder of inputs to create a folder of outputs, you can use glob (need to import it)
if __name__ == '__main__':

    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))
コード例 #27
0
ファイル: solver.py プロジェクト: tianqiyang/CS170Proj
 #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))
コード例 #28
0
ファイル: solver.py プロジェクト: kmoy1/CheapestNetwork
    alg_score = (float) (alg_quality[optimal_algorithm] * 100) / total
    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)
コード例 #29
0
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")
コード例 #30
0
ファイル: solver4.py プロジェクト: jw-13/cs170-project-sp20
            for w, d2 in G.adj[v].items():
                if w in visited:
                    continue
                new_weight = d2.get("weight")
                push(frontier, (new_weight, next(c), v, w, d2))


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)