예제 #1
0
def main():
    source = 'Chicago'
    destination = 'Phoenix'
    g = Digraph()
    for name in ('Boston', 'Providence', 'New York', 'Chicago', 'Denver',
                 'Phoenix', 'Los Angeles'):  #Create 7 nodes
        g.addNode(Node(name))
    g.addEdge(Edge(g.getNode('Boston'), g.getNode('Providence')))
    g.addEdge(Edge(g.getNode('Boston'), g.getNode('New York')))
    g.addEdge(Edge(g.getNode('Providence'), g.getNode('Boston')))
    g.addEdge(Edge(g.getNode('Providence'), g.getNode('New York')))
    g.addEdge(Edge(g.getNode('New York'), g.getNode('Chicago')))
    g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Denver')))
    g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Phoenix')))
    g.addEdge(Edge(g.getNode('Denver'), g.getNode('Phoenix')))
    g.addEdge(Edge(g.getNode('Denver'), g.getNode('New York')))
    g.addEdge(Edge(g.getNode('Los Angeles'), g.getNode('Boston')))

    sp = DFS(g,
             g.getNode(source),
             g.getNode(destination), [],
             None,
             toPrint=True)

    if sp != None:
        print('Shortest path from', source, 'to', destination, 'is',
              printPath(sp))
    else:
        print('There is no path from', source, 'to', destination)
def test_repr_edge():
    v1 = Vertex()
    v2 = Vertex(a=1, b=2)
    e1 = Edge(v1, v2)
    e2 = Edge(v1, v2, weight=1, c=3, d=4)
    assert re.match(r'^V#\d+\s->\sV#\d+\sa=1\sb=2$', repr(e1))
    assert re.match(r'^V#\d+\s->\sV#\d+\sa=1\sb=2\s-\sweight=1\sc=3\sd=4$', repr(e2))
예제 #3
0
    def shortest_path(self, origin, destination, weighted_poly):
        """Find and return shortest path between origin and destination.

        Will return in-order list of Points of the shortest path found. If
        origin or destination are not in the visibility graph, their respective
        visibility edges will be found, but only kept temporarily for finding
        the shortest path. 
        """

        origin_exists = origin in self.visgraph
        dest_exists = destination in self.visgraph
        if origin_exists and dest_exists:
            return shortest_path(self.visgraph, origin, destination,
                                 weighted_poly)
        orgn = None if origin_exists else origin
        dest = None if dest_exists else destination
        add_to_visg = Graph([])
        if not origin_exists:
            for v in visible_vertices(origin, self.graph, destination=dest):
                add_to_visg.add_edge(Edge(origin, v))
        if not dest_exists:
            for v in visible_vertices(destination, self.graph, origin=orgn):
                add_to_visg.add_edge(Edge(destination, v))
        return shortest_path(self.visgraph, origin, destination, weighted_poly,
                             add_to_visg)
예제 #4
0
def convertDHCtoUHC(inString):
    # G is the original instance
    G = Graph(inString, weighted=False, directed=True)
    # newG is the converted instance -- create an empty graph using empty string
    newG = Graph('', weighted=False, directed=False)
    # Create all of the nodes of newG -- a triplet of A, B, and C
    # nodes in newG for every node in G.  Also create an A-B edge and
    # a B-C edge within each triplet.
    for node in G:
        # Create triplet.
        nodeA = node + 'A'
        nodeB = node + 'B'
        nodeC = node + 'C'
        newNodes = (nodeA, nodeB, nodeC)
        for newNode in newNodes:
            newG.addNode(newNode)
        # Create A-B and B-C edges within the triplet.
        newG.addEdge(Edge([nodeA, nodeB]))
        newG.addEdge(Edge([nodeB, nodeC]))
    # Create all the remaining edges of newG, i.e., create an undirected
    # A-C edge corresponding to each directed edge in G.
    for edge in G.edges():
        (node1, node2) = edge.nodes
        newEdge = Edge([node1 + 'A', node2 + 'C'])
        newG.addEdge(newEdge)

    return str(newG)
예제 #5
0
def build_city_graph(graph_type):
    providence = Node('providence')
    boston = Node('boston')
    new_york = Node('new york')
    denver = Node('denver')
    phoenix = Node('phoenix')
    chicago = Node('chicago')
    los_angeles = Node('los angeles')

    edges = []
    edges.append(Edge(providence, boston))
    edges.append(Edge(providence, new_york))
    edges.append(Edge(denver, phoenix))
    edges.append(Edge(denver, new_york))
    edges.append(Edge(new_york, chicago))
    edges.append(Edge(chicago, denver))
    edges.append(Edge(chicago, phoenix))
    edges.append(Edge(boston, providence))
    edges.append(Edge(boston, new_york))
    edges.append(Edge(los_angeles, boston))

    graph = graph_type()
    graph.add_node(providence)
    graph.add_node(boston)
    graph.add_node(new_york)
    graph.add_node(denver)
    graph.add_node(phoenix)
    graph.add_node(chicago)
    graph.add_node(los_angeles)

    for edge in edges:
        graph.add_edge(edge)

    return graph
예제 #6
0
def test_case_2():
    vertex_to_name = {x: str(x + 1) for x in range(4)}
    edge_list = [
        Edge(0, 2, -2),
        Edge(1, 0, 4),
        Edge(1, 2, 3),
        Edge(2, 3, 2),
        Edge(3, 1, -1)
    ]
    g = Graph(Graph.GRAPH_TYPE_DIRECTED_WEIGHT, vertex_to_name, edge_list)
    node_text_map, edges, directed = g.get_show_info()
    GraphVisualization.show(node_text_map,
                            edges,
                            is_directed=directed,
                            view_graph=True,
                            rank_dir="LR")
    distances, paths = shortest_path_floyd_warshall(g)
    print("shortest path from and weight sum as:")
    for i in range(g.get_vertices_count()):
        for j in range(g.get_vertices_count()):
            path_str = "-".join(
                [g.get_vertex_name(vertex) for vertex in paths[i][j]])
            print("%s to %s: %s%s %d" %
                  (g.get_vertex_name(i), g.get_vertex_name(j), path_str, '*' *
                   (15 - len(path_str)), distances[i][j]))
def main():
    # Two sources and single distination
    v_in = Vertex("x")  # one source
    v1 = Edge(name="e0")(v_in)
    v2 = Edge(name="e1")(v1)
    v3 = Edge(name="e2")(v2, v1)  # fork and concate
    v4 = Edge(name="e3")(v3)
    v5 = Edge(name="e4")(v4)
    y = Vertex("y")  # second source
    y.value = np.random.rand(4, 3)
    v_out = SquareLoss(name="square-loss")(v5, y)  # single distination

    print "----- Vertices and Edges in Graph -----"
    print len(cg.vertices)
    print len(cg.edges)

    print "----- Forward pass (Inference) -----"
    inputs = np.random.rand(4, 3)
    v_in.forward(inputs)
    labels = np.random.rand(4, 3)
    y.forward(labels)
    print v1.value
    print v5.value

    print "----- Compute Loss -----"
    v_out.backward(1)
    print v1.grad
 def test_apply_remove_connection_from_edge(self):
     mother_graph = Graph()
     m_n1 = Vertex()
     m_e1 = Edge(m_n1)
     mother_graph.add_elements([m_n1, m_e1])
     daughter_graph = Graph()
     d_e1 = Edge()
     daughter_graph.add_elements([d_e1])
     mother_daughter_mapping = Mapping()
     mother_daughter_mapping[m_e1] = d_e1
     prod_option = ProductionOption(mother_graph, mother_daughter_mapping,
                                    daughter_graph)
     production = Production(mother_graph, [prod_option])
     host_graph = Graph()
     h_n1 = Vertex()
     h_e1 = Edge(None, h_n1)
     host_graph.add_elements([h_n1, h_e1])
     mother_host_mapping = Mapping()
     mother_host_mapping[m_n1] = h_n1
     mother_host_mapping[m_e1] = h_e1
     result = production.apply(host_graph, mother_host_mapping)
     # Test if the vertex was deleted
     assert len(result.vertices) == 0
     assert len(result.edges) == 1
     # Test if the vertex was removed from the edges connection field
     assert result.edges[0].vertex2 is None
 def test_apply_vertex_new_connection(self):
     mother_graph = Graph()
     m_n1 = Vertex()
     m_e1 = Edge(m_n1)
     mother_graph.add_elements([m_n1, m_e1])
     daughter_graph = Graph()
     d_n1 = Vertex()
     d_e1 = Edge(d_n1)
     daughter_graph.add_elements([d_n1, d_e1])
     mother_daughter_mapping = Mapping()
     mother_daughter_mapping[m_n1] = d_n1
     prod_option = ProductionOption(mother_graph, mother_daughter_mapping,
                                    daughter_graph)
     production = Production(mother_graph, [prod_option])
     host_graph = Graph()
     h_n1 = Vertex()
     h_e1 = Edge(h_n1)
     host_graph.add_elements([h_n1, h_e1])
     mother_host_mapping = Mapping()
     mother_host_mapping[m_n1] = h_n1
     mother_host_mapping[m_e1] = h_e1
     result = production.apply(host_graph, mother_host_mapping)
     # Test if there are no superfluous elements in the graph
     assert len(result.vertices) == 1
     assert len(result.edges) == 1
     # Test if graph has the correct connections and element count
     assert result.is_isomorph(daughter_graph)
     # Test if there are no extra neighbours introduced to the vertex.
     assert len(result.vertices[0].edges) == 1
     assert result.edges[0] in result.vertices[0].edges
     # Test if the new edge was correctly connected to the vertex.
     assert result.edges[0].vertex1 == result.vertices[0]
예제 #10
0
    def test_weighted_edge(self):
        graph = Graph()
        graph.add_edge("A", "B", 3)

        self.assertEqual(graph.as_adjency_list(values_only=False), {
            "A": [Edge("B", 3)],
            "B": [Edge("A", 3)],
        })
예제 #11
0
def test_case_2():
    vertex_to_name = {x: str(x) for x in range(4)}
    edge_list = [Edge(0, 1, 1), Edge(0, 2, 4), Edge(0, 3, 3), Edge(1, 3, 2), Edge(2, 3, 5)]
    g = Graph(Graph.GRAPH_TYPE_UNDIRECTED_WEIGHT, vertex_to_name, edge_list)
    node_text_map, edges, directed = g.get_show_info()
    GraphVisualization.show(node_text_map, edges, is_directed=directed, view_graph=True, rank_dir="LR")
    weight_sum, edges = prim_algorithm(g)
    print('minimum span tree weight sum= ', weight_sum, ' select edges: ', edges)
 def test_graph_create(self):
     node_list = [Node(1), Node(2), Node(3)]
     edge_list = [
         Edge('2 miles', node_list[0], node_list[1]),
         Edge('6 miles', node_list[1], node_list[2])
     ]
     graph = Graph(node_list, edge_list)
     self.assertEqual(node_list, graph.nodes)
     self.assertEqual(edge_list, graph.edges)
예제 #13
0
def test_topological_sorting_fail_on_undirected_graph():
    vertices = [Vertex() for i in range(3)]
    edges = [
        Edge(head=vertices[0], tail=vertices[1]),
        Edge(head=vertices[1], tail=vertices[2]),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=False)
    with pytest.raises(GraphDirectionTypeError):
        topological_sort(graph)
예제 #14
0
def test_strongly_connected_components_fail_on_undirected_graph():
    vertices = [Vertex() for i in range(3)]
    edges = [
        Edge(head=vertices[0], tail=vertices[1]),
        Edge(head=vertices[1], tail=vertices[2]),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=False)
    with pytest.raises(GraphDirectionTypeError):
        find_strongly_connected_components(graph)
예제 #15
0
def test_case_1():
    vertex_to_name = {
        0: 'S',
        1: 'A',
        2: 'B',
        3: 'C',
        4: 'D',
        5: 'E',
        6: 'F',
        7: 'G'
    }
    g = Graph(Graph.GRAPH_TYPE_UNDIRECTED, vertex_to_name, None)
    g.add_edges([
        Edge(0, 1),
        Edge(0, 2),
        Edge(0, 3),
        Edge(1, 4),
        Edge(2, 5),
        Edge(3, 6),
        Edge(4, 7),
        Edge(5, 7),
        Edge(6, 7)
    ])
    node_text_map, edges, directed = g.get_show_info()
    GraphVisualization.show(node_text_map,
                            edges,
                            is_directed=directed,
                            view_graph=True,
                            rank_dir="LR")
    print('depth first traverse by iteration: ',
          [g.get_vertex_name(x) for x in depth_first_traverse_by_iteration(g)])
    print('depth first traverse by recursion: ',
          [g.get_vertex_name(x) for x in depth_first_traverse_by_recursion(g)])
    print('breadth first traverse: ',
          [g.get_vertex_name(x) for x in breadth_first_traverse(g)])
예제 #16
0
def test_all_paths():
    vertices = [Vertex() for i in range(6)]
    edges = [
        Edge(head=vertices[0], tail=vertices[1]),
        Edge(head=vertices[0], tail=vertices[2]),
        Edge(head=vertices[0], tail=vertices[3]),
        Edge(head=vertices[0], tail=vertices[4]),
        Edge(head=vertices[1], tail=vertices[5]),
        Edge(head=vertices[2], tail=vertices[3]),
        Edge(head=vertices[2], tail=vertices[5]),
        Edge(head=vertices[3], tail=vertices[5]),
        Edge(head=vertices[4], tail=vertices[5]),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=False)
    edge_paths = list(construct_all_paths(graph=graph,
                                     start=vertices[0],
                                     end=vertices[2]))
    paths = []
    for edge_path in edge_paths:
        path = [vertices[0]] + [edge.tail for edge in edge_path]
        paths.append(path)
    assert len(paths) == 7
    actual_paths = [
        [vertices[0], vertices[1], vertices[5], vertices[2]],
        [vertices[0], vertices[1], vertices[5], vertices[3], vertices[2]],
        [vertices[0], vertices[2]],
        [vertices[0], vertices[3], vertices[2]],
        [vertices[0], vertices[3], vertices[5], vertices[2]],
        [vertices[0], vertices[4], vertices[5], vertices[2]],
        [vertices[0], vertices[4], vertices[5], vertices[3], vertices[2]],
    ]
예제 #17
0
    def test_basic_bfs_alternate(self):
        """
        Graph

        [1]-----[2]
                /|   [5]
               / |  /
              /  | /
           [4]--[3]

        :return:
        """
        edges = [
            Edge('one', 'two'),
            Edge('two', 'four'),
            Edge('two', 'three'),
            Edge('three', 'two'),
            Edge('three', 'four'),
            Edge('three', 'five'),
            Edge('four', 'two'),
            Edge('four', 'three'),
            Edge('five', 'three')
        ]

        g = Graph(edges)
        bfs_graph = BreadthFirstPaths(g, 'five')

        expected = ['five', 'three', 'four']
        actual = bfs_graph.path_to('four')
        self.assertEqual(expected, actual)
예제 #18
0
def test_dijkstra_algorithm():
    vertices = [Vertex() for i in range(6)]
    edges = [
        Edge(head=vertices[0], tail=vertices[1], weight=4),
        Edge(head=vertices[0], tail=vertices[2], weight=2),
        Edge(head=vertices[1], tail=vertices[2], weight=1),
        Edge(head=vertices[1], tail=vertices[3], weight=5),
        Edge(head=vertices[2], tail=vertices[3], weight=8),
        Edge(head=vertices[2], tail=vertices[4], weight=10),
        Edge(head=vertices[3], tail=vertices[4], weight=2),
        Edge(head=vertices[3], tail=vertices[5], weight=6),
        Edge(head=vertices[4], tail=vertices[5], weight=5),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=False)
    shortest_paths = run_dijkstra_algorithm(graph=graph, source=vertices[0])
    for i in range(6):
        assert shortest_paths[vertices[i]].source is vertices[0]
        assert shortest_paths[vertices[i]].destination is vertices[i]
    assert shortest_paths[vertices[0]].last_hop is None
    assert shortest_paths[vertices[0]].distance == 0
    assert shortest_paths[vertices[1]].last_hop.head is vertices[2]
    assert shortest_paths[vertices[1]].distance == 3
    assert shortest_paths[vertices[2]].last_hop.head is vertices[0]
    assert shortest_paths[vertices[2]].distance == 2
    assert shortest_paths[vertices[3]].last_hop.head is vertices[1]
    assert shortest_paths[vertices[3]].distance == 8
    assert shortest_paths[vertices[4]].last_hop.head is vertices[3]
    assert shortest_paths[vertices[4]].distance == 10
    assert shortest_paths[vertices[5]].last_hop.head is vertices[3]
    assert shortest_paths[vertices[5]].distance == 14
예제 #19
0
def test_prim_algorithm_fail_on_directed_graph():
    vertices = [Vertex() for i in range(6)]
    edges = [
        Edge(head=vertices[0], tail=vertices[1]),
        Edge(head=vertices[1], tail=vertices[2]),
        Edge(head=vertices[2], tail=vertices[0]),
        Edge(head=vertices[3], tail=vertices[4]),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=True)
    with pytest.raises(GraphDirectionTypeError):
        run_prim_algorithm(graph=graph, start=vertices[0])
예제 #20
0
    def test_dfs_int_vertices_negaitve(self):

        graph = Graph()

        graph.add_edge(Edge(Vertex(1), Vertex(2), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(3), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(4), Vertex(2), 1))

        self.assertEqual(dfs(graph, Vertex(5), Vertex(0)), float("inf"))
        self.assertEqual(dfs(graph, Vertex(1), Vertex(5)), float("inf"))
    def find_lower_adjacent(self, triangle):
        edges = []
        edges.append(Edge(triangle[0], triangle[1]))
        edges.append(Edge(triangle[1], triangle[2]))
        edges.append(Edge(triangle[0], triangle[2]))

        num_of_lower_adjacent = 0
        neighbours = set()
        for edge in edges:
            num_of_lower_adjacent += len(self.edge_triangle_map[edge])
            neighbours |= (self.edge_triangle_map[edge])
        return num_of_lower_adjacent, list(neighbours)
def test_path_finder_fail():
    vertices = [Vertex() for i in range(4)]
    edges = [
        Edge(vertices[0], vertices[1]),
        Edge(vertices[1], vertices[2]),
        Edge(vertices[2], vertices[0]),
        Edge(vertices[2], vertices[3]),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=True)
    graph.bfs(start=vertices[0])
    with pytest.raises(Exception):
        graph.find_path(start=vertices[3], end=vertices[1])
예제 #23
0
def test_degree():
    g = Graph()

    edges = [
        (Edge('A', 'B'), 12),
        (Edge('A', 'C'), 8),
        (Edge('A', 'D'), 2),
    ]

    for tpl in edges:
        g.add_edge(tpl[0], tpl[1])

    assert g.degree('A') is 3
    def find_upper_adjacent(self, triangle):
        edges = []
        edges.append(Edge(triangle[0], triangle[1]))
        edges.append(Edge(triangle[1], triangle[2]))
        edges.append(Edge(triangle[0], triangle[2]))

        num_of_upper_adjacent = 0
        for edge in edges:
            triangles_edge_is_partof = self.edge_triangle_map[edge]
            for tr in triangles_edge_is_partof:
                if self.is_partof_k_plus_one_simplex(triangle, tr):
                    num_of_upper_adjacent += 1
        return num_of_upper_adjacent
예제 #25
0
파일: test.py 프로젝트: redgoose/trains
    def test_edge(self):

        edge = Edge('A', 'B')

        self.assertEqual(edge.u, 'A')
        self.assertEqual(edge.v, 'B')
        self.assertEqual(edge.weight, 1)

        edge = Edge('X', 'Y', 15)

        self.assertEqual(edge.u, 'X')
        self.assertEqual(edge.v, 'Y')
        self.assertEqual(edge.weight, 15)
예제 #26
0
class InitGraph:

    ## set up all the film/actor nodes as Dictionary:
    ## key: url, value: film/actor node
    ## store the edges as a list with starting node of actor and ending node as movie
    filmNodes = []
    actorNodes = []
    filmNameDict = {}
    actorNameDict = {}
    edges = []
    nodes = {}
    hub = {}

    #parse a json file
    with open(
            '/Users/Jenny/Desktop/cs242/Assignment2.0/Scraper/Scraper/quotes.json',
            'r') as content_file:
        content = content_file.read()
    data = json.loads(content)

    for i in range(len(data)):
        temp = data[i]
        name = None
        edge = None

        ## when we discover the current index of the json file is an actor
        if temp['isActor'] == True:
            node = ActorNode(temp['actorName'], temp['url'], temp['year'])
            nodes[temp['url']] = node
            actorNodes.append(node)
            actorNameDict[temp['actorName']] = []
            for cast in temp['castings']:
                for ch in cast:
                    actorNameDict[temp['actorName']].append(ch)
            for url in temp['films']:
                if nodes.get(url) is not None:
                    edge = Edge(node, nodes.get(url))

        ## when we discover the current index of the json file is a film
        elif temp['isFilm'] == True:
            node = FilmNode(temp['filmName'], temp['url'], temp['year'],
                            temp['filmValue'])
            nodes[temp['url']] = node
            filmNodes.append(node)
            filmNameDict[temp['filmName']] = temp['starrings']
            for url in temp['actors']:
                if nodes.get(url) is not None:
                    edge = Edge(nodes.get(url), node)

        if edge is not None:
            edges.append(edge)
예제 #27
0
def test_connected_components():
    vertices = [Vertex() for i in range(6)]
    edges = [
        Edge(head=vertices[0], tail=vertices[1]),
        Edge(head=vertices[1], tail=vertices[2]),
        Edge(head=vertices[2], tail=vertices[0]),
        Edge(head=vertices[3], tail=vertices[4]),
    ]
    graph = Graph(vertices=vertices, edges=edges, directed=False)
    connected_components = find_connected_components(graph)
    assert len(connected_components) == 3
    assert {v for v in connected_components[0].adjacency_lists} == {v for v in vertices[:3]}
    assert {v for v in connected_components[1].adjacency_lists} == {v for v in vertices[3:5]}
    assert {v for v in connected_components[2].adjacency_lists} == {vertices[5]}
예제 #28
0
파일: test.py 프로젝트: redgoose/trains
    def test_large_graph(self):

        graph = Graph()

        for i in range(0, 1000):
            graph.add_edge(Edge(str(i), str(i + 1), 5))

            graph.add_edge(Edge(str(i), str(500), 5))
        graph.add_edge(Edge(str(1000), str(250), 5))

        self.assertEqual(graph.get_distance_for_path(['0', '1', '2']), 10)
        self.assertEqual(graph.get_num_paths(start='0', end='500', restriction={'max_distance': 50}), 1023)
        self.assertEqual(graph.get_min_distance(start='50', end='51'), 5)
        self.assertEqual(graph.get_min_distance(start='1000', end='250'), 5)
        self.assertEqual(graph.get_min_distance(start='0', end='1000'), 2505)
예제 #29
0
def test_edge_initialization():
    """Edge initailization requires two node endpoints. The nodes must be
    different."""
    with pytest.raises(TypeError):
        edge = Edge()

    with pytest.raises(TypeError):
        edge = Edge(1)

    edge = Edge(1, 2)
    assert edge.node1 == Node(1)
    assert edge.node2 == Node(2)

    with pytest.raises(ValueError):
        edge = Edge("node1", "node1")  # Must be different
예제 #30
0
 def setUp(self):
     self.nodes = [
         Node('v1'),
         Node('v2'),
         Node('v3'),
         Node('v4'),
     ]
     self.edges = [
         Edge('edge 1', node_from='v1', node_to='v2'),
         Edge('edge 2', node_from='v1', node_to='v3'),
         Edge('edge 3', node_from='v3', node_to='v2'),
         Edge('edge 4', node_from='v3', node_to='v4'),
         Edge('edge 5', node_from='v4', node_to='v3'),
     ]
     self.graph = Graph(self.nodes, self.edges)