コード例 #1
0
    def load_graph(self, **kwargs):
        """
        Loads a specific predefined board
        """

        if 'file_path' not in kwargs:
            messagebox.showerror('Missing file path',
                                 'No file path was provided!')

        if isinstance(self.window.renderer, CanvasRenderer):
            self.window.renderer.destruct()
            renderer = GraphRenderer(self.window.content_area)
            renderer.set_controller(self)
            self.window.set_renderer(renderer)

        # Update panel widgets
        generate_options(self.window.options_area, module=2)
        generate_stats(self.window.stats_area, module=2)

        self.window.renderer.clear()
        # Load the graph from file, and provide networkx graph instance for rendering
        Graph.read_graph_from_file(kwargs['file_path'],
                                   networkx_graph=self.window.renderer.graph)

        self.window.renderer.render_graph()
コード例 #2
0
ファイル: controller.py プロジェクト: myth/trashcan
    def load_graph(self, **kwargs):
        """
        Loads a specific predefined board
        """

        if 'file_path' not in kwargs:
            messagebox.showerror(
                'Missing file path',
                'No file path was provided!'
            )

        if isinstance(self.window.renderer, CanvasRenderer):
            self.window.renderer.destruct()
            renderer = GraphRenderer(self.window.content_area)
            renderer.set_controller(self)
            self.window.set_renderer(renderer)

        # Update panel widgets
        generate_options(self.window.options_area, module=2)
        generate_stats(self.window.stats_area, module=2)

        self.window.renderer.clear()
        # Load the graph from file, and provide networkx graph instance for rendering
        Graph.read_graph_from_file(kwargs['file_path'], networkx_graph=self.window.renderer.graph)

        self.window.renderer.render_graph()
コード例 #3
0
    def setUp(self) -> None:

        vertix_set = ["A", "B", "C", "D", "E", "F"]
        edge_set = [["B", "C"], ["D", "E"], ["F"], [], ["F"], []]

        weights = [[1, 2], [1, 1], [2], [], [1], []]

        self.directed_graph = Graph(vertix_set, edge_set)
        self.directed_weighted_graph = Graph(vertix_set, edge_set, weights)
コード例 #4
0
ファイル: s8_8_WordLadder.py プロジェクト: scaraclette/pycode
def buildGraph(wordFile):
  d = {}
  g = Graph()
  wfile = open(wordFile, 'r')
  # Create buckets of words that differ by one letter
  for line in wfile:
    word = line[:-1]
    for i in range(len(word)):
      bucket = word[:i] + '_' + word[i+1:]
      if bucket in d:
        d[bucket].append(word)
      else:
        d[bucket] = word
  # Add vertices and edges for words in the same bucket
  for bucket in d.keys():
    for word1 in d[bucket]:
      for word2 in d[bucket]:
        if word1 != word2:
          g.addEdge(word1, word2)

  return g
コード例 #5
0
    def test_journey_to_the_moon(self):
        graph = Graph()
        graph.extend_edges([(0, 2), (1, 8), (1, 4), (2, 8), (2, 6), (3, 5),
                            (6, 9)])
        self.assertEqual(len(graph.vertices), 9)
        self.assertEqual(graph.vertices[2].degree(), 3)

        search = GraphSearch(graph)
        self.assertEqual(search.graph, graph)
        parents = search.bfs()
        self.assertEqual(len(parents), 7)
        self.assertEqual(parents[0], None)
        self.assertFalse(3 in parents)
        self.assertFalse(5 in parents)
        search = GraphSearch(graph, 3)
        p2 = search.bfs()
        self.assertEqual(len(p2), 2)
        #
        # Solve problem
        processed = set()
        countries = []
        rest = [0]
        total = 0
        while rest:
            country = set(GraphSearch(graph, rest[0]).bfs())
            countries.append(country)
            processed.update(country)
            rest = tuple(set(graph.vertices) - processed)

        for i, country in enumerate(countries, 1):
            total += len(country) * (10 - len(processed))
            for other in countries[i:]:
                total += len(country) * len(other)

        self.assertEqual(len(countries), 2)
        self.assertEqual(total, 23)
コード例 #6
0
    def test_bfs(self):
        graph = Graph()
        graph.extend_edges([(0, 2), (1, 8), (1, 4), (2, 8), (2, 6), (3, 5),
                            (6, 9)])
        self.assertEqual(len(graph.vertices), 9)
        self.assertEqual(graph.vertices[2].degree(), 3)

        search = graph.bfs(0)
        self.assertEqual(search.graph, graph)
        self.assertEqual(len(search.parents), 7)
        self.assertEqual(search.parents[0], None)
        self.assertFalse(3 in search.parents)
        self.assertFalse(5 in search.parents)
        #
        search2 = graph.bfs(3)
        self.assertEqual(len(search2.parents), 2)
コード例 #7
0




if __name__ == "__main__":
    n1 = Node(1,1,'A',1,False,5)
    n2 = Node(1,2,'B',1,False,4)
    n3 = Node(1,3,'C',1,False,2,1)
    n4 = Node(1,4,'D',1,False,6,1)
    n5 = Node(1,5,'E',1,False,8,1)
    n6 = Node(1,4,'F',1,False,2,1)
    n7 = Node(1,4,'G',1,True,0,1)
    n8 = Node(1,4,'S',1,False,3,1)
    n9 = Node(1,4,'H',1,False,4,1)
    n10 = Node(1,4,'I',1,False,9,1)
    
    
    nodes = [n1,n2,n3,n4,n5,n6,n7,n8,n9,n10]
    edges = [('A','S',1),('A','G',10),('S','C',1),('S','B',2),('B','D',5),('C','D',3),('C','G',4),('D','G',0)]

    g = MyGraph(nodes)
    g.addEdges(edges)
    g.printGraph()
    p = PathFinding(g,1)
    print("NODE WITH IDENTIFIER A: ")

    p.astar(g.getNode('A'))


コード例 #8
0
class TestGraph(unittest.TestCase):

    directed_graph = directed_weighted_graph = None

    def setUp(self) -> None:

        vertix_set = ["A", "B", "C", "D", "E", "F"]
        edge_set = [["B", "C"], ["D", "E"], ["F"], [], ["F"], []]

        weights = [[1, 2], [1, 1], [2], [], [1], []]

        self.directed_graph = Graph(vertix_set, edge_set)
        self.directed_weighted_graph = Graph(vertix_set, edge_set, weights)

    def test_init(self):
        self.assertEqual(self.directed_graph.G["B"], [("D", 1), ("E", 1)])

    def test_breadth_first_levelorder_search(self):
        path_beginning_vertex_a = self.directed_graph.breadth_first_search("A")
        expected_path_beginning_vertex_a = ["A", "B", "C", "D", "E", "F"]

        self.assertEqual(path_beginning_vertex_a,
                         expected_path_beginning_vertex_a)

    def test_breadth_first_levelorder_search_center_vertex(self):
        path_beginning_vertex_middle = self.directed_graph.breadth_first_search(
            "B")
        expected_path_beginning_vertex_middle = ["B", "D", "E", "F"]

        self.assertEqual(path_beginning_vertex_middle,
                         expected_path_beginning_vertex_middle)

    def test_breadth_first_levelorder_search_no_outbound(self):
        path_beginning_vertex_no_outbound = self.directed_graph.breadth_first_search(
            "F")
        expected_path_beginning_vertex_no_outbound = ["F"]

        self.assertEqual(path_beginning_vertex_no_outbound,
                         expected_path_beginning_vertex_no_outbound)

    def test_depth_first_postorder_search(self):
        path_beginning_vertex_a = self.directed_graph.depth_first_search("A")
        expected_path_beginning_vertex_a = ["A", "C", "F", "B", "E", "D"]

        self.assertEqual(path_beginning_vertex_a,
                         expected_path_beginning_vertex_a)

    def test_depth_first_postorder_search_center_vertex(self):
        path_beginning_vertex_middle = self.directed_graph.depth_first_search(
            "B")
        expected_path_beginning_vertex_middle = ["B", "E", "F", "D"]

        self.assertEqual(path_beginning_vertex_middle,
                         expected_path_beginning_vertex_middle)

    def test_depth_first_postorder_search_no_outbound(self):
        path_beginning_vertex_no_outbound = self.directed_graph.depth_first_search(
            "F")
        expected_path_beginning_vertex_no_outbound = ["F"]

        self.assertEqual(path_beginning_vertex_no_outbound,
                         expected_path_beginning_vertex_no_outbound)

    def test_dijkstra(self):
        init_vertex = "A"
        target_vertex = "F"

        # Test Weighted Graph
        self.assertEqual(
            self.directed_weighted_graph.dijkstra(init_vertex)["target_dist"]
            [target_vertex], 3)

        # Test unWeighted Graph
        self.assertEqual(
            self.directed_graph.dijkstra(init_vertex)["target_dist"]
            [target_vertex], 2)
コード例 #9
0
 def test_insertvertex(self):
     graphm = Graph()
     self.assertEqual(graphm.insert_vertex('a').element(), 'a')
コード例 #10
0
 def test_insertedge(self):
     graphm = Graph()
     v0 = graphm.insert_vertex('a')
     v1 = graphm.insert_vertex('b')
     graphm.insert_edge(v0, v1, 2)
     self.assertEqual(graphm.edges().pop().element(), 2)
コード例 #11
0
 def test_vertexcount(self):
     graphm = Graph()
     graphm.insert_vertex('a')
     graphm.insert_vertex('b')
     self.assertEqual(graphm.vertex_count(), 2)
コード例 #12
0
    source.color = 'gray'
    source.distance = 0
    source.predecessor = None
    queue = list()
    queue.append(source)
    while queue:
        curr_node = queue.pop()
        for node in G.adjacency_list[curr_node]:
            if node.color == 'white':
                node.color = 'gray'
                node.distance = curr_node.distance + 1
                node.predecessor = curr_node
                queue.insert(0, node)
        curr_node.color = 'black'


def print_path(G, source, target):
    if source.id == target.id:
        print(source)
    elif target.predecessor is None:
        print(f'No path from {str(source)} to {str(target)} exists.')
    else:
        print_path(G, source, target.predecessor)
        print(target)


if __name__ == '__main__':
    adjacency_list = []
    graph = Graph(adjacency_list)