def simple_wgraph():
    """Return a simple weighted graph with edges."""
    from weighted_graph import WeightedGraph
    wg = WeightedGraph()
    for edge in SIMPLE_WGRAPH:
        wg.add_edge(edge[0], edge[1], edge[2])
    return wg
Ejemplo n.º 2
0
 def test_topological_sort_error(self):
     """test_topological_sort_error: Make sure that 'topological_sort' raises the correct error
     """
     node_0 = WeightedNode(1, [2], {(1, 2): 1})
     node_1 = WeightedNode(2, [1], {(2, 1): 1})
     graph = WeightedGraph([node_0, node_1])
     with self.assertRaises(TypeError):
         graph.topological_sort()
Ejemplo n.º 3
0
    def test_remove(self):
        """test_remove: Test removing a node
        """
        node_1 = WeightedNode(1, [2], {(1, 2): 2})
        node_2 = WeightedNode(2, [1], {(2, 1): 2})
        graph = WeightedGraph([node_1, node_2])
        graph.remove_node(node_1)

        self.assertEqual(graph.vertices, set({2}))
        self.assertEqual(graph.edges, {2: set({})})
        self.assertEqual(graph.weights, {})
Ejemplo n.º 4
0
 def test_longest_path(self):
     """test_longest_path: Test that the longest path is correctly generated using
     the '_bellman_ford' function
     """
     node_0 = WeightedNode(0, [1, 4], {(0, 1): 1, (0, 4): 11})
     node_1 = WeightedNode(1, [2], {(1, 2): 2})
     node_2 = WeightedNode(2, [3], {(2, 3): 3})
     node_3 = WeightedNode(3, [], {})
     node_4 = WeightedNode(4, [5], {(4, 5): 14})
     node_5 = WeightedNode(5, [3], {(5, 3): 12})
     graph = WeightedGraph([node_0, node_1, node_2, node_3, node_4, node_5])
     self.assertEqual(graph.longest_path(0, 3), 'Path: [0, 4, 5, 3]\nDistance traveled: 37')
Ejemplo n.º 5
0
    def test_add_node(self):
        """test_add_node: Test adding a new node
        """
        node_1 = WeightedNode(1, [2], {(1, 2): 2})
        node_2 = WeightedNode(2, [1], {(2, 1): 2})
        node_3 = WeightedNode(3, [1, 2], {(3, 1): 2, (3, 2): 4})
        graph = WeightedGraph([node_1, node_2])
        graph.add_node(node_3)

        self.assertEqual(graph.vertices, set({1, 2, 3}))
        self.assertEqual(graph.edges, {1: set({2}), 2: set({1}), 3: set({1, 2})})
        self.assertEqual(graph.weights, {(1, 2): 2, (2, 1): 2, (3, 1): 2, (3, 2): 4})
Ejemplo n.º 6
0
def main():
    """main: Example case for finding longest and shortest path
    """
    node_0 = WeightedNode(0, [1, 4], {(0, 1): 1, (0, 4): 11})
    node_1 = WeightedNode(1, [2], {(1, 2): 2})
    node_2 = WeightedNode(2, [3], {(2, 3): 3})
    node_3 = WeightedNode(3, [], {})
    node_4 = WeightedNode(4, [5], {(4, 5): 14})
    node_5 = WeightedNode(5, [3], {(5, 3): 12})
    graph = WeightedGraph([node_0, node_1, node_2, node_3, node_4, node_5])

    print('The longest path is {0}'.format(graph.longest_path(0, 3)))
    print('The shortest path is {0}'.format(graph.shortest_path(0, 3)))
def make_graph():
    g = WeightedGraph()
    g.add_edge('a', 'b')
    g.add_edge('b', 'c')
    g.add_edge('c', 'f')
    g.add_edge('g', 'f')
    g.add_edge('a', 'd')
    g.add_edge('d', 'e')
    g.add_edge('e', 'a')
    return g
Ejemplo n.º 8
0
 def test_topological_sort(self):
     """test_topological_sort: There is a picture in this folder showing the visual
     representation of this graph. Testing generating a topologically sorted list
     of graph vertices
     """
     node_0 = WeightedNode(5, [11], {(5, 11): 1})
     node_1 = WeightedNode(11, [2, 9, 10], {(11, 2): 1, (11, 9): 1, (11, 10): 1})
     node_2 = WeightedNode(2, [], {})
     node_3 = WeightedNode(7, [8, 11], {(7, 8): 1, (7, 11): 1})
     node_4 = WeightedNode(8, [9], {(8, 9): 1})
     node_5 = WeightedNode(9, [], {})
     node_6 = WeightedNode(3, [8, 10], {(3, 8): 1, (3, 10): 1})
     node_7 = WeightedNode(10, [], {})
     graph = WeightedGraph([node_0, node_1, node_2, node_3, node_4, node_5, node_6, node_7])
     self.assertEqual(graph.topological_sort(), [7, 5, 11, 3, 10, 8, 9, 2])
Ejemplo n.º 9
0
 def test_no_weighted_hamiltonian(self):
     """test_known_no_hamiltonian_weighted: Test a weighted directed graph with no
     hamiltonian cycles
     """
     node0 = WeightedNode(0, [1, 3], {(0, 1): 4, (0, 3): 5})
     node1 = WeightedNode(1, [0, 3, 4, 2], {
         (1, 0): 2,
         (1, 3): 3,
         (1, 4): 6,
         (1, 2): 1
     })
     node2 = WeightedNode(2, [1, 4], {(2, 1): 2, (2, 4): 5})
     node3 = WeightedNode(3, [0, 1], {(3, 0): 2, (3, 1): 5})
     node4 = WeightedNode(4, [1, 2], {(4, 1): 3, (4, 2): 5})
     graph = WeightedGraph([node0, node1, node2, node3, node4])
     self.assertEqual(graph.get_hamiltonian_cycles(), [])
Ejemplo n.º 10
0
def test_prims_lazy_mst():
    w_graph = WeightedGraph(4)
    w_graph.add_edge(1, 0, -10)
    w_graph.add_edge(1, 2, -35)
    w_graph.add_edge(0, 2, -15)
    w_graph.add_edge(0, 3, -12)
    w_graph.add_edge(1, 3, -11)
    w_graph.add_edge(2, 3, -30)
    prims_lazy = PrimsLazyMst(w_graph)
    prims_lazy.get_mst()
Ejemplo n.º 11
0
def mst(wg: WeightedGraph, start: int = 0) -> Optional[WeightedPath]:
    path: WeightedPath = []
    visited: Set[V] = set()
    pq: PriorityQueue = PriorityQueue()

    visited.add(start)
    for edge in wg.edges_for_index(start):
        pq.push(edge)

    while not pq.is_empty and len(visited) < wg.vertex_count:
        edge: WeightedEdge = pq.pop()
        if edge.v in visited:
            continue
        visited.add(edge.v)
        path.append(edge)
        for edge in wg.edges_for_index(edge.v):
            pq.push(edge)
    return path
Ejemplo n.º 12
0
def non_ref():
    """Create simple non referential graph."""
    from weighted_graph import WeightedGraph
    empty_wg = WeightedGraph()
    empty_wg.add_edge('A', 'B', 5)
    empty_wg.add_edge('A', 'C', 5)
    empty_wg.add_edge('B', 'D', 5)
    empty_wg.add_edge('B', 'E', 5)
    empty_wg.add_edge('C', 'F', 5)
    empty_wg.add_edge('C', 'G', 5)
    return empty_wg
def make_graph_three():
    my_graph = WeightedGraph()
    my_graph.add_node('a')
    my_graph.add_node('b')
    my_graph.add_node('c')
    my_graph.add_edge('a', 'c')
    my_graph.add_edge('b', 'a')
    return my_graph
Ejemplo n.º 14
0
 def test_get_shortest_hamiltonian(self):
     """test_get_shortest_hamiltonian: Test finding the short hamiltonian path
     or paths in a directed weighted graph
     """
     node0 = WeightedNode(0, [1, 3], {(0, 1): 4, (0, 3): 3})
     node1 = WeightedNode(1, [0, 3, 4, 2], {
         (1, 0): 3,
         (1, 3): 4,
         (1, 4): 4,
         (1, 2): 3
     })
     node2 = WeightedNode(2, [1, 4], {(2, 1): 1, (2, 4): 3})
     node3 = WeightedNode(3, [0, 1, 4], {(3, 0): 5, (3, 1): 3, (3, 4): 6})
     node4 = WeightedNode(4, [1, 2, 3], {(4, 1): 2, (4, 2): 6, (4, 3): 7})
     graph = WeightedGraph([node0, node1, node2, node3, node4])
     self.assertEqual(graph.get_shortest_hamiltonian_cycle(),
                      [([0, 3, 4, 2, 1, 0], 19), ([1, 0, 3, 4, 2, 1], 19),
                       ([2, 1, 0, 3, 4, 2], 19), ([3, 4, 2, 1, 0, 3], 19),
                       ([4, 2, 1, 0, 3, 4], 19)])
Ejemplo n.º 15
0
 def test_known_weighted_hamiltonian(self):
     """test_known_weighted_hamiltonian_cycles: Weighted directed graph which is known
     to have hamiltonian cycles
     """
     node0 = WeightedNode(0, [1, 3], {(0, 1): 4, (0, 3): 3})
     node1 = WeightedNode(1, [0, 3, 4, 2], {
         (1, 0): 3,
         (1, 3): 4,
         (1, 4): 4,
         (1, 2): 3
     })
     node2 = WeightedNode(2, [1, 4], {(2, 1): 1, (2, 4): 3})
     node3 = WeightedNode(3, [0, 1, 4], {(3, 0): 5, (3, 1): 3, (3, 4): 6})
     node4 = WeightedNode(4, [1, 2, 3], {(4, 1): 2, (4, 2): 6, (4, 3): 7})
     graph = WeightedGraph([node0, node1, node2, node3, node4])
     self.assertEqual(
         graph.get_hamiltonian_cycles(),
         [[0, 3, 4, 2, 1, 0], [0, 1, 2, 4, 3, 0], [1, 2, 4, 3, 0, 1],
          [1, 0, 3, 4, 2, 1], [2, 4, 3, 0, 1, 2], [2, 1, 0, 3, 4, 2],
          [3, 4, 2, 1, 0, 3], [3, 0, 1, 2, 4, 3], [4, 3, 0, 1, 2, 4],
          [4, 2, 1, 0, 3, 4]])
Ejemplo n.º 16
0
def cyclic():
    """Create simple cyclic graph."""
    from weighted_graph import WeightedGraph
    empty_wg = WeightedGraph()
    empty_wg.add_edge('A', 'B', 5)
    empty_wg.add_edge('B', 'C', 5)
    empty_wg.add_edge('C', 'A', 5)
    return empty_wg
Ejemplo n.º 17
0
    def get_global_hypothesis(self, tracks, conflicting_tracks):
        """
        Generate a global hypothesis by finding the maximum weighted independent
        set of a graph with tracks as vertices, and edges between conflicting tracks.
        """
        gh_graph = WeightedGraph()
        for index, track in enumerate(tracks):
            s = track.get_track_score()
            gh_graph.add_weighted_vertex(str(index), s)

        gh_graph.set_edges(conflicting_tracks)

        mwis_ids = gh_graph.mwis()
        
        return mwis_ids
Ejemplo n.º 18
0
def test_kruskal():
    w_graph = WeightedGraph(4)
    w_graph.add_edge(1, 0, -10)
    w_graph.add_edge(1, 2, -35)
    w_graph.add_edge(0, 2, -15)
    w_graph.add_edge(0, 3, -12)
    w_graph.add_edge(1, 3, -11)
    w_graph.add_edge(2, 3, -30)
    '''
    w_graph.add_edge(4,6,-1)
    w_graph.add_edge(3,8,-2)
    w_graph.add_edge(8,7,-5)
    w_graph.add_edge(6,8,-8)
    w_graph.add_edge(7,6,-17)
    '''

    k = KruskalMst(w_graph)
    k.get_mst()
    '''
Ejemplo n.º 19
0
    def global_hypothesis(self, track_trees, conflicting_tracks):
        """
        Generate a global hypothesis by finding the maximum weighted independent
        set of a graph with tracks as vertices, and edges between conflicting tracks.
        """
        logging.info("Running MWIS on weighted track trees...\n")
        gh_graph = WeightedGraph()
        for index, kalman_filter in enumerate(track_trees):
            gh_graph.add_weighted_vertex(str(index),
                                         kalman_filter.get_track_score())

        gh_graph.set_edges(conflicting_tracks)

        mwis_ids = gh_graph.mwis()
        logging.info("Completed MWIS.\n")

        return mwis_ids
def global_hypothesis(track_trees, t):

    MWIS_tracks = []
    gh_graph = WeightedGraph()

    tracks = [item for sublist in track_trees for item in sublist]

    if tracks:

        conflicting_tracks = []

        for track_index, track in enumerate(tracks):
            for conflict_index, conflict_track in enumerate(
                    tracks[track_index:]):
                conflict_index += track_index

                if any(x in track.get_past_measurements()
                       for x in conflict_track.get_past_measurements()):
                    if track_index != conflict_index:
                        conflicting_tracks.append(
                            (track_index, conflict_index))

        for index, kalman_filter in enumerate(tracks):
            gh_graph.add_weighted_vertex(str(index),
                                         kalman_filter.get_score(t))

        gh_graph.set_edges(conflicting_tracks)

        mwis_ids = gh_graph.mwis()

        for index in list(mwis_ids):
            MWIS_tracks.append([tracks[index]])

        for track_index, track in enumerate(MWIS_tracks):
            track = track[0]
            for conflict_index, conflict_track in enumerate(MWIS_tracks):
                conflict_track = conflict_track[0]
                if abs(track.get_state() - conflict_track.get_state()
                       ) < 10 and conflict_track.is_con() and track.is_con():
                    if track_index != conflict_index:
                        if track.get_score(t) > conflict_track.get_score(t):
                            track.kill()

    return MWIS_tracks
Ejemplo n.º 21
0
    def test_shortest_path(self):
        """test_shortest_path: Test that the shortest math is correctly generated using
        the '_dijkstra' function
        """
        node_0 = WeightedNode(0, [1, 4], {(0, 1): 1, (0, 4): 11})
        node_1 = WeightedNode(1, [2], {(1, 2): 2})
        node_2 = WeightedNode(2, [3], {(2, 3): 3})
        node_3 = WeightedNode(3, [], {})
        node_4 = WeightedNode(4, [5], {(4, 5): 14})
        node_5 = WeightedNode(5, [3], {(5, 3): 12})
        graph = WeightedGraph([node_0, node_1, node_2, node_3, node_4, node_5])
        self.assertEqual(graph.shortest_path(0, 3), 'Path: [0, 1, 2, 3]\nDistance traveled: 6')

        node_0 = WeightedNode(5, [11, 9], {(5, 11): 4, (5, 9): 1})
        node_1 = WeightedNode(11, [2, 9, 10], {(11, 2): 6, (11, 9): 2, (11, 10): 9})
        node_2 = WeightedNode(2, [5], {(2, 5): 2})
        node_3 = WeightedNode(7, [8, 11], {(7, 8): 2, (7, 11): 5})
        node_4 = WeightedNode(8, [9], {(8, 9): 5})
        node_5 = WeightedNode(9, [2], {(9, 2): 4})
        node_6 = WeightedNode(3, [8, 10], {(3, 8): 2, (3, 10): 7})
        node_7 = WeightedNode(10, [9], {(10, 9): 4})
        graph = WeightedGraph([node_0, node_1, node_2, node_3, node_4, node_5, node_6, node_7])
        self.assertEqual(graph.shortest_path(5, 9), 'Path: [5, 9]\nDistance traveled: 1')
Ejemplo n.º 22
0
def empty_wg():
    """Create an empty graph."""
    from weighted_graph import WeightedGraph
    return WeightedGraph()
Ejemplo n.º 23
0
# Takes a dictionary of edges to reach each node and returns a list of
# edges that goes from `start` to `end`
def path_dict_to_path(start: int, end: int, path_dict: Dict[int, WeightedEdge]) -> WeightedPath:
    if len(path_dict) == 0:
        return []
    edge_path: WeightedPath = []
    e: WeightedEdge = path_dict[end]
    edge_path.append(e)
    while e.u != start:
        e = path_dict[e.u]
        edge_path.append(e)
    return list(reversed(edge_path))


if __name__ == "__main__":
    city_graph2: WeightedGraph[str] = WeightedGraph(["Seattle", "San Francisco", "Los Angeles", "Riverside", "Phoenix", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston", "Detroit", "Philadelphia", "Washington"])

    city_graph2.add_edge_by_vertices("Seattle", "Chicago", 1737)
    city_graph2.add_edge_by_vertices("Seattle", "San Francisco", 678)
    city_graph2.add_edge_by_vertices("San Francisco", "Riverside", 386)
    city_graph2.add_edge_by_vertices("San Francisco", "Los Angeles", 348)
    city_graph2.add_edge_by_vertices("Los Angeles", "Riverside", 50)
    city_graph2.add_edge_by_vertices("Los Angeles", "Phoenix", 357)
    city_graph2.add_edge_by_vertices("Riverside", "Phoenix", 307)
    city_graph2.add_edge_by_vertices("Riverside", "Chicago", 1704)
    city_graph2.add_edge_by_vertices("Phoenix", "Dallas", 887)
    city_graph2.add_edge_by_vertices("Phoenix", "Houston", 1015)
    city_graph2.add_edge_by_vertices("Dallas", "Chicago", 805)
    city_graph2.add_edge_by_vertices("Dallas", "Atlanta", 721)
    city_graph2.add_edge_by_vertices("Dallas", "Houston", 225)
    city_graph2.add_edge_by_vertices("Houston", "Atlanta", 702)
Ejemplo n.º 24
0
weights = {
    (0, 1): 3,
    (1, 7): 4,
    (7, 2): 2,
    (2, 5): 1,
    (5, 6): 8,
    (0, 3): 2,
    (3, 2): 6,
    (3, 4): 1,
    (4, 8): 8,
    (8, 0): 4
}
vertex_values = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

weighted_graph = WeightedGraph(weights, vertex_values)
weighted_graph.build_from_edges()
'''
assert weighted_graph.calc_distance(8,4) == 7
assert [weighted_graph.calc_distance(8,n) for n in range(9)] == [
    4, 7, 12, 6, 7, 13, 21, 11, 0]

print("PASSED")
'''

print("Asserting calc_shortest_path for WeightedGraph class")
assert weighted_graph.calc_shortest_path(8, 4) == [8, 0, 3, 4]
assert weighted_graph.calc_shortest_path(8, 7) == [8, 0, 1, 7]
assert weighted_graph.calc_shortest_path(8, 6) == [8, 0, 3, 2, 5, 6]
print("PASSED")
        if visited[edge.v]:
            continue  # 방문한 곳이면 넘어간다.
        result.append(edge)  # 최소 가중치의 에지를 결과에 추가한다.
        visit(edge.v)  # 연결된 에지를 방문한다.

    return result


def print_weighted_path(wg: WeightedGraph, wp: WeightedPath) -> None:
    for edge in wp:
        print(f"{wg.vertex_at(edge.u)} {edge.weight}> {wg.vertex_at(edge.v)}")
    print(f"가중치 총합: {total_weight(wp)}")


if __name__ == "__main__":
    city_graph2: WeightedGraph[str] = WeightedGraph(["시애틀", "샌프란시스코", "로스앤젤레스", "리버사이드", "피닉스", "시카고",
                                                     "보스턴", "뉴욕", "애틀랜타", "마이애미", "댈러스", "휴스턴", "디트로이트", "필라델피아", "워싱턴"])

    city_graph2.add_edge_by_vertices("시애틀", "시카고", 1737)
    city_graph2.add_edge_by_vertices("시애틀", "샌프란시스코", 678)
    city_graph2.add_edge_by_vertices("샌프란시스코", "리버사이드", 386)
    city_graph2.add_edge_by_vertices("샌프란시스코", "로스앤젤레스", 348)
    city_graph2.add_edge_by_vertices("로스앤젤레스", "리버사이드", 50)
    city_graph2.add_edge_by_vertices("로스앤젤레스", "피닉스", 357)
    city_graph2.add_edge_by_vertices("리버사이드", "피닉스", 307)
    city_graph2.add_edge_by_vertices("리버사이드", "시카고", 1704)
    city_graph2.add_edge_by_vertices("피닉스", "댈러스", 887)
    city_graph2.add_edge_by_vertices("피닉스", "휴스턴", 1015)
    city_graph2.add_edge_by_vertices("댈러스", "시카고", 805)
    city_graph2.add_edge_by_vertices("댈러스", "애틀랜타", 721)
    city_graph2.add_edge_by_vertices("댈러스", "휴스턴", 225)
    city_graph2.add_edge_by_vertices("휴스턴", "애틀랜타", 702)
def path_dict_to_path(start: int, end: int,
                      path_dict: Dict[int, WeightedEdge]) -> WeightedPath:
    if not path_dict:
        return []
    edge_path = deque()
    edge: WeightedEdge = path_dict[end]
    edge_path.appendleft(edge)
    while edge.u != start:
        edge = path_dict[edge.u]
        edge_path.appendleft(edge)
    return list(edge_path)


if __name__ == "__main__":
    city_graph2: WeightedGraph[City] = WeightedGraph(list(City))

    city_graph2.add_edge_by_vertices(City.SEA, City.CHI, 1737)
    city_graph2.add_edge_by_vertices(City.SEA, City.SFO, 678)
    city_graph2.add_edge_by_vertices(City.SFO, City.RVS, 386)
    city_graph2.add_edge_by_vertices(City.SFO, City.LAX, 348)
    city_graph2.add_edge_by_vertices(City.LAX, City.RVS, 50)
    city_graph2.add_edge_by_vertices(City.LAX, City.PHX, 357)
    city_graph2.add_edge_by_vertices(City.RVS, City.PHX, 307)
    city_graph2.add_edge_by_vertices(City.RVS, City.CHI, 1704)
    city_graph2.add_edge_by_vertices(City.PHX, City.DAL, 887)
    city_graph2.add_edge_by_vertices(City.PHX, City.HOU, 1015)
    city_graph2.add_edge_by_vertices(City.DAL, City.CHI, 805)
    city_graph2.add_edge_by_vertices(City.DAL, City.ATL, 721)
    city_graph2.add_edge_by_vertices(City.DAL, City.HOU, 225)
    city_graph2.add_edge_by_vertices(City.HOU, City.ATL, 702)
def make_graph_no_edges():
    my_graph = WeightedGraph()
    my_graph.add_node('a')
    my_graph.add_node('b')
    my_graph.add_node('c')
    return my_graph
Ejemplo n.º 28
0
        # на данный момент это минимальный вес, поэтому добавляем в дерево
        result.append(edge)
        # идем дальше
        visit(edge.v)
    return result


def print_weighted_graph(wg: WeightedGraph, wp: WeightedPath) -> None:
    for edge in wp:
        print(
            f'{wg.vertex_at(edge.u)} {edge.weight} --> {wg.vertex_at(edge.v)}')
    print(f'Total weight: {total_weight(wp)}')


if __name__ == '__main__':
    city_graph2: WeightedGraph[str] = WeightedGraph(['Seattle', 'San Francisco', 'Los Angeles', 'Riverside', 'Phoenix', 'Chicago', \
        'Boston', 'New York', 'Atlanta', 'Miami', 'Dallas', 'Houston', 'Detroit', 'Philadelphia', 'Washington'])
    city_graph2.add_edge_by_vertices('Seattle', 'Chicago', 1737)
    city_graph2.add_edge_by_vertices('Seattle', 'San Francisco', 678)
    city_graph2.add_edge_by_vertices('San Francisco', 'Riverside', 386)
    city_graph2.add_edge_by_vertices('San Francisco', 'Los Angeles', 348)
    city_graph2.add_edge_by_vertices('Los Angeles', 'Riverside', 50)
    city_graph2.add_edge_by_vertices('Los Angeles', 'Phoenix', 357)
    city_graph2.add_edge_by_vertices('Riverside', 'Phoenix', 307)
    city_graph2.add_edge_by_vertices('Riverside', 'Chicago', 1704)
    city_graph2.add_edge_by_vertices('Phoenix', 'Dallas', 887)
    city_graph2.add_edge_by_vertices('Phoenix', 'Houston', 1015)
    city_graph2.add_edge_by_vertices('Dallas', 'Chicago', 805)
    city_graph2.add_edge_by_vertices('Dallas', 'Atlanta', 721)
    city_graph2.add_edge_by_vertices('Dallas', 'Houston', 225)
    city_graph2.add_edge_by_vertices('Houston', 'Atlanta', 702)
    city_graph2.add_edge_by_vertices('Houston', 'Miami', 968)
Ejemplo n.º 29
0
		weight = weighted_graph.W[edge]
		u, v = edge
		if dist[v] > (dist[u] + weight):
			dist[v] = dist[u] + weight
			parent[v] = u
			pq.update({v: dist[v]})
	topo_sorted_vertexes = topological_sort(weighted_graph)
	for v in topo_sorted_vertexes:
		for e in weighted_graph.get_set_of_children(v):
			relax((v,e))

	print(dist)





if __name__ == "__main__":
	print("====== Testing Weighted Graph =========")
	WG = WeightedGraph(directed = True)

	Vertices = ["a","b", "c", "d", "e"]
	Edges = [(("a", "b"), 19), (("a", "c"), 7), (("b", "c"), 11), (("b", "d"), 4), (("d", "c"), 15), (("d", "e"), 13), (("c", "e"), 5)]
	WG.make_graph(Vertices, Edges)
	print(WG.W)
	djikstra(WG, "a")
	DAG_shortest_path(WG, "a")



from dlib_models import download_model, download_predictor, load_dlib_models
download_model()
download_predictor()


def get_descriptor(img, face_detect, shape_predictor, fpath):
    detection = list(face_detect(img))[0]
    print("found", fpath)
    shape = shape_predictor(img, detection)
    descriptor = np.array(face_rec_model.compute_face_descriptor(img, shape))
    return fpath, descriptor


pics = os.listdir("./../images/")
image_data = [io.imread("./../images/" + pic) for pic in pics]

load_dlib_models()
from dlib_models import models
face_detect = models["face detect"]
face_rec_model = models["face rec"]
shape_predictor = models["shape predict"]

graph = WeightedGraph(
    get_descriptor(image, face_detect, shape_predictor, pics[i])
    for i, image in enumerate(image_data))
graph.whispers_loop(4)

for node in graph.nodes:
    print(node.ID, node.fpath)
Ejemplo n.º 31
0
def print_path(wp: WeightedPath, wg: WeightedGraph) -> None:
    vertex_ids = list(map(lambda x: x.u, wp))
    result = list(map(lambda id: wg.vertex_at(id), vertex_ids))
    print(result)
Ejemplo n.º 32
0
    return result


def print_weighted_path(weighted_graph, weighted_path):
    for edge in weighted_path:
        print(
            f'{weighted_graph.vertex_at(edge.u)} {edge.weight}> {weighted_graph.vertex_at(edge.v)}'
        )

    print(f'Total weight: {total_weight(weighted_path)}')


if __name__ == '__main__':
    city_graph = WeightedGraph([
        'Seattle', 'San Francisco', 'Los Angeles', 'Riverside', 'Phoenix',
        'Chicago', 'Boston', 'New York', 'Atlanta', 'Miami', 'Dallas',
        'Houston', 'Detroit', 'Philadelphia', 'Washington'
    ])

    city_graph.add_edge_by_vertices('Seattle', 'Chicago', 1737)
    city_graph.add_edge_by_vertices('Seattle', 'San Francisco', 678)
    city_graph.add_edge_by_vertices('San Francisco', 'Riverside', 386)
    city_graph.add_edge_by_vertices('San Francisco', 'Los Angeles', 348)
    city_graph.add_edge_by_vertices('Los Angeles', 'Riverside', 50)
    city_graph.add_edge_by_vertices('Los Angeles', 'Phoenix', 357)
    city_graph.add_edge_by_vertices('Riverside', 'Phoenix', 307)
    city_graph.add_edge_by_vertices('Riverside', 'Chicago', 1704)
    city_graph.add_edge_by_vertices('Phoenix', 'Dallas', 887)
    city_graph.add_edge_by_vertices('Phoenix', 'Houston', 1015)
    city_graph.add_edge_by_vertices('Dallas', 'Chicago', 805)
    city_graph.add_edge_by_vertices('Dallas', 'Atlanta', 721)
Ejemplo n.º 33
0
    (1,7): 4,
    (7,2): 2,
    (2,5): 1,
    (5,6): 8,
    (0,3): 2,
    (3,2): 6,
    (3,4): 1,
    (4,8): 8,
    (8,0): 4
}
vertex_values = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']


print('\nTesting...\n')

weighted_graph_1 = WeightedGraph(weights, vertex_values)
shortest_path_1 = weighted_graph_1.calc_shortest_path(8,4)
print("    Testing Weighted Graph 2's calc_shortest_path")
assert [node.index for node in shortest_path_1] == [8, 0, 3, 4], " Weighted Graph 1's calc_shortest_path was not right, it should be [8, 0, 3, 4], but was {}".format([node.index for node in shortest_path_1])
print("    Weighted Graph 1's row_indices Passed!!!\n")

weighted_graph_2 = WeightedGraph(weights, vertex_values)
shortest_path_2 = weighted_graph_2.calc_shortest_path(6,8)
print("    Testing Weighted Graph 2's calc_shortest_path")
assert [node.index for node in shortest_path_2] == [6, 5, 2, 3, 0, 8], " Weighted Graph 2's calc_shortest_path was not right, it should be [6, 5, 2, 3, 0, 8], but was {}".format([node.index for node in shortest_path_2])
print("    Weighted Graph 2's row_indices Passed!!!\n")

weighted_graph_3 = WeightedGraph(weights, vertex_values)
shortest_path_3 = weighted_graph_3.calc_shortest_path(7,4)
print("    Testing Weighted Graph 3's calc_shortest_path")
assert [node.index for node in shortest_path_3] == [7, 2, 3, 4], " Weighted Graph 3's calc_shortest_path was not right, it should be [7, 2, 3, 4], but was {}".format([node.index for node in shortest_path_3])
def make_graph_cycle():
    g = WeightedGraph()
    g.add_edge('a', 'b')
    g.add_edge('b', 'c')
    g.add_edge('c', 'a')
    return g