예제 #1
0
def read_city_graph(filename):
    f = open(filename)
    g = WeightedGraph()
    global vertecies
    vertecies = {}
    global edges
    edges = {}

    line = f.readline()
    while line:
        fields = line.split(",")

        if fields[0] == "V":
            v = int(fields[1])
            lat = float(fields[2])
            lon = float(fields[3])
            g.add_vertex(v)
            vertecies[v] = (int(lat * 100000), int(lon * 100000))
        elif fields[0] == "E":
            e = (int(fields[1]), int(fields[2]))
            g.add_edge(int(fields[1]), int(fields[2]))
            edges[e] = {"street": fields[3]}
        line = f.readline()

    return g
예제 #2
0
def run_tournament(game: PDGame) -> None:
    """Run a tournament between all strategies.

    If <show_heatmap> is set, then display a heatmap that shows the match-ups
    between the strategies.
    """

    all_strategies = get_all_strategies()

    graph = WeightedGraph()
    for s1 in all_strategies:
        for s2 in all_strategies:
            new_game = PDGame(game.num_rounds)
            strategy1 = s1.__copy__()
            strategy2 = s2.__copy__()

            player1 = Player(strategy1, 1)
            player2 = Player(strategy2, 2)

            if isinstance(player1.strategy, LearningStrategy):
                player1 = get_trained_learner(player2, game.num_rounds)

            graph.add_vertex(player1.strategy.name)

            graph.add_vertex(player2.strategy.name)

            run_game(new_game, player1, player2)
            if strategy1.name == 'Learning Strategy' and strategy2.name == 'Learning Strategy':
                player1.curr_points, player2.curr_points = 0, 0

            graph.add_edge((player1.strategy.name, player1.curr_points),
                           (player2.strategy.name, player2.curr_points))

    display_heatmap(graph)
예제 #3
0
def test_weighted_graph():
    g = WeightedGraph()

    g.insert_edge("a", {(9, "b"), (6, "c"), (1, "d")})

    assert g.get_neighbors("a") == {(9, "b"), (6, "c"), (1, "d")}
    assert g.get_neighbors("b") == {(9, "a")}
    assert g.get_neighbors("c") == {(6, "a")}
    assert g.get_neighbors("d") == {(1, "a")}

    assert g.get_weight("a", "b") == 9
    assert g.get_weight("a", "c") == 6
    assert g.get_weight("a", "d") == 1
예제 #4
0
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Pathfinding Algorithm Visualizer")
        self.layout = QVBoxLayout()

        columns = 40
        rows = 30
        self.graph = WeightedGraph(columns, rows)
        self.grid_ui = GridUI(self.graph, columns, rows)
        self.grid_ui.setContentsMargins(0, 0, 0, 0)
        self.grid_ui.setStyleSheet('background-color: white;')

        self.buttons_layout = QHBoxLayout()
        self.start_button = QPushButton('Start')
        self.reset_button = QPushButton('Reset grid')
        self.path_button = QPushButton('Clear path')
        self.change_button = QPushButton('Change parameters')
        self.buttons_layout.addWidget(self.start_button)
        self.buttons_layout.addWidget(self.reset_button)
        self.buttons_layout.addWidget(self.path_button)
        self.buttons_layout.addWidget(self.change_button)
        self.layout.addWidget(self.grid_ui)
        self.layout.addLayout(self.buttons_layout)
        self.widget = QWidget()
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)

        self.reset_button.clicked.connect(self.clear_grid)
        self.change_button.clicked.connect(self.show_parameter_popup)
        self.start_button.clicked.connect(self.generate_path)
        self.path_button.clicked.connect(self.clear_path)

        self.parameters = ParametersPopup()
        self.parameters.buttonBox.accepted.connect(
            self.update_graph_with_parameters)

        self.ui_thread = QThread()
        self.ui_thread.start()
        self.ui_QObj = UIQObj()
        self.ui_QObj.moveToThread(self.ui_thread)
        self.ui_QObj.update.connect(self.handle_ui_update)
        self.ui_QObj.start.connect(self.ui_QObj.run)
        self.ui_QObj.start.emit()

        self.path_thread = QThread()
        self.path_thread.start()
        self.path_QObj = PathQObj()
        self.path_QObj.moveToThread(self.path_thread)
        self.path_QObj.start.connect(self.path_QObj.run)
예제 #5
0
def main():
    with open(sys.argv[1]) as f:
        lines = f.read().splitlines()

    adj = []
    for line in lines:
        row = []
        for node in line.split(','):
            if node == '-':
                row.append(None)
            else:
                row.append(int(node))
        adj.append(row)

    num_nodes = len(adj)
    # make sure the adjacency matrix is square
    assert all(len(row) == num_nodes for row in adj)

    graph = WeightedGraph()
    for i in range(num_nodes):
        graph.add_node(i)

    for x, row in enumerate(adj):
        for y, weight in enumerate(row):
            if weight is not None:
                graph.add_arc(x, y, weight)

    mst = min_spanning_tree(graph)

    # Now we want to consider half of the adjacency matrix, so we can
    # sum the total weight of all arcs.

    half_adj = []
    for i, row in enumerate(adj):
        new_row = []
        for j, weight in enumerate(row):
            if i <= j:
                new_row.append(weight)
            else:
                new_row.append(None)
        half_adj.append(new_row)

    # Now remove all of the arcs in the mst, so the arcs we are left
    # with are the ones that we are able to remove.
    for mst_arc_source, mst_arc_target in mst:
        half_adj[mst_arc_source][mst_arc_target] = None
        half_adj[mst_arc_target][mst_arc_source] = None
    print(sum(sum(filter(None, row)) for row in half_adj))
예제 #6
0
    def __init__(self):
        self.g, self.coord = graph_build()
        self.route_graph = WeightedGraph()
        self.s_name_text = ""
        self.d_name_text = ""

        self.new_path = False
        self.address_q = Queue()
        self.waypoints = []
        self.sd_dict = dict()
        self.path_dict = dict()
        self.name_vert_dict = dict()

        self.sd_list = set()
        self.ordered_list = []
        self.master_path = []
예제 #7
0
def main():
    global matrix

    with open(sys.argv[1]) as f:
        lines = f.readlines()
    matrix = [[int(n) for n in l.strip().split(',')] for l in lines]
    """
    matrix = [[131, 673, 234, 103, 18],
              [201, 96, 342, 965, 150],
              [630, 803, 746, 422, 111],
              [537, 699, 497, 121, 956],
              [805, 732, 524, 37, 331]]
    """

    matrix_size = len(matrix)
    # the cost of arriving at each node is the value at that node
    g = WeightedGraph()
    for lnum, line in enumerate(matrix):
        for cnum, value in enumerate(line):
            g.add_node((lnum, cnum))
            # from below
            if (0 <= lnum + 1 < matrix_size):
                g.add_arc((lnum + 1, cnum), (lnum, cnum), value)

            # from above
            if (0 <= lnum - 1 < matrix_size):
                g.add_arc((lnum - 1, cnum), (lnum, cnum), value)

            # from right
            if (0 <= cnum + 1 < matrix_size):
                g.add_arc((lnum, cnum + 1), (lnum, cnum), value)

            # from left
            if (0 <= cnum - 1 < matrix_size):
                g.add_arc((lnum, cnum - 1), (lnum, cnum), value)

    route, cost = a_star(g, (0, 0), (matrix_size - 1, matrix_size - 1))
    print(cost + matrix[0][0])
예제 #8
0
g.add_edge(('D', 'E'))
g.add_edge(('E', 'F'))
g.add_edge(('F', 'G'))
g.add_edge(('G', 'H'))
g.add_edge(('H', 'I'))
g.add_edge(('I', 'J'))
g.add_edge(('J', 'A'))
g.add_edge(('C', 'H'))

depth_first_search_traversal(graph=g.graph_dict, starting_vertex='A', goal_vertex='F', verbose=True)

path = breadth_first_search_find_path(graph=g.graph_dict, starting_vertex='A', goal_vertex='F')
print(path)


wg = WeightedGraph()
wg.add_edge(('A', 'B'), 1)
wg.add_edge(('B', 'C'), 6)
wg.add_edge(('C', 'D'), 3)
wg.add_edge(('D', 'E'), 8)
wg.add_edge(('E', 'F'), 2)
wg.add_edge(('F', 'G'), 5)
wg.add_edge(('G', 'H'), 1)
wg.add_edge(('H', 'I'), 8)
wg.add_edge(('I', 'J'), 4)
wg.add_edge(('J', 'A'), 3)
wg.add_edge(('C', 'H'), 2)

cost, path = djikstra(wg.graph_dict, 'A', 'F', True)
print(cost, path)