Пример #1
0
def main():
    g0 = UndirectedGraph()
    g0.addVertex(1)
    g0.addVertex(2)
    g0.addVertex(3)
    g0.addEdge((1, 2))
    g0.addEdge((1, 3))
    print(g0)
    x = g0.isTree(1, {})
    if x:
        print("g0 is a tree")
    else:
        print("g0 is not a tree")

    print("\n")
    g0.addVertex(4)
    g0.addEdge((3, 4))
    print(g0)
    x = g0.isTree(1, {})
    if x:
        print("g0 is a tree")
    else:
        print("g0 is not a tree")

    print("\n")
    g0.addEdge((2, 4))
    print(g0)
    x = g0.isTree(1, {})
    if x:
        print("g0 is a tree")
    else:
        print("g0 is not a tree")

    print("\n")

    g1 = UndirectedGraph()
    g1.addVertex(1)
    g1.addVertex(2)
    g1.addVertex(3)
    g1.addVertex(4)
    g1.addVertex(5)
    g1.addEdge((1, 2))
    g1.addEdge((1, 3))
    g1.addEdge((2, 4))
    g1.addEdge((2, 5))
    g1.addEdge((4, 5))

    print(g1)
    x = g1.isTree(1, {})
    if x:
        print("g1 is a tree")
    else:
        print("g1 is not a tree")
Пример #2
0
    def setUp(self):
        self.graph = UndirectedGraph()
        self.filled_graph = UndirectedGraph()

        for i in range(6):
            self.filled_graph.add_vertex(i + 1)

        self.filled_graph.add_edge(1, 2)
        self.filled_graph.add_edge(1, 4)
        self.filled_graph.add_edge(2, 4)
        self.filled_graph.add_edge(2, 3)
        self.filled_graph.add_edge(4, 3)
        self.filled_graph.add_edge(3, 6)
        self.filled_graph.add_edge(4, 5)
        self.filled_graph.add_edge(5, 6)
Пример #3
0
    def test_ugraph_edges(self):
        # Checks for antisimetry
        g = UndirectedGraph.rand(5)
        self.assertTrue(g.is_antisymmetric())

        with self.assertRaises(IsNotUndirectedGraphError):
            UndirectedGraph(3, [[0, 0], [0, 2], [2, 0], [1, 0]])
Пример #4
0
 def test_load_graph_duplicate_non_conflicting_lines(self):
     try:
         UndirectedGraph(
             "test/graph-with-duplicate-non-conflicting-lines.csv")
     except ValueError:
         self.fail(
             "Graph file contains duplicate, but non-conflicting edges.")
Пример #5
0
 def test_adj(self):
     graph = UndirectedGraph(5, [(0, 1), (2, 3), (0, 4)])
     self.assertEqual(graph.adj(0), [1, 4])
     self.assertEqual(graph.adj(1), [0])
     self.assertEqual(graph.adj(2), [3])
     self.assertEqual(graph.adj(3), [2])
     self.assertEqual(graph.adj(4), [0])
Пример #6
0
    def test_adjacency_matrix(self):
        ug = UndirectedGraph("A", "B", "C", "D")
        ug.add_new_edge("A", "B")
        ug.add_new_edge("B", "C")
        ug.add_new_edge("C", "D")

        assert ug.adjacency_matrix == [[0, 1, 0, 0], [1, 0, 1, 0],
                                       [0, 1, 0, 1], [0, 0, 1, 0]]
Пример #7
0
def from_networkx(ngraph):
    if ngraph.is_directed():
        raise NotImplementedError()
    else:
        graph = UndirectedGraph(ngraph.number_of_nodes())
        for edge in ngraph.edges_iter():
            graph.add_edge(int(edge[0]), int(edge[1]))
    return graph
Пример #8
0
def journeyToMoon(n, astronaut):
    '''
    Function signature supplied by Hackerrank,
    and my implementation using supplied arguments: n, astronaut.
    '''
    graph = UndirectedGraph(n, astronaut)
    subset_sizes = disjoint_subset_sizes(graph)

    return number_of_pairs(subset_sizes)
def test_degeneracy_ordering_nonempty(adjacencies: List[Set[Vertex]]) -> None:
    g = UndirectedGraph(adjacencies=adjacencies)
    connected_vertices = g.connected_vertices()

    ordering = list(degeneracy_ordering(g))
    assert set(ordering) == connected_vertices
    assert all(g.degree(ordering[0]) <= g.degree(v) for v in ordering[1:])

    ordering_min1 = list(degeneracy_ordering(g, drop=1))
    assert ordering_min1 == ordering[:-1]
Пример #10
0
 def test_find_shortest_path(self):
     dg = UndirectedGraph("A", "B", "C", "D")
     dg.add_new_edge("A", "B")
     dg.add_new_edge("B", "D")
     dg.add_new_edge("B", "C")
     dg.add_new_edge("A", "C")
     dg.add_new_edge("C", "D")
     result = dg.find_shortest_path("A", "D")
     assert result == [vt("A"), vt("B"), vt("D")] or result == [
         vt("A"), vt("C"), vt("D")
     ]
Пример #11
0
def random_undirected_graph(order: int, size: int) -> UndirectedGraph:
    adjacencies: List[Set[Vertex]] = [set() for _ in range(order)]
    print(f"order={order}, size={size}")
    for v, w in generate_n_edges(order, size):
        adjacencies[v].add(w)
        adjacencies[w].add(v)
    print(adjacencies)
    g = UndirectedGraph(adjacencies=adjacencies)
    assert g.order == order
    assert g.size() == size
    return g
Пример #12
0
    def test_simple(self):
        graph = UndirectedGraph(4)

        graph.add(0, 1, 10)
        graph.add(0, 2, 4)
        graph.add(1, 2, 5)
        graph.add(1, 3, 6)
        graph.add(2, 3, 5)

        value = stoer_wagner(graph)

        expected_value = 11  # (0, 1, 2) & 3

        self.assertEqual(value, expected_value)
Пример #13
0
    def test_create(self):
        ug = UndirectedGraph("A", "B", "C")
        ug.add_new_edge("A", "B")
        ug.add_new_edge("B", "C")

        assert [v.name for v in ug.vertexes] == ["A", "B", "C"]
        assert ug.adjacency_dict == {
            vt("A"): [vt("B")],
            vt("B"): [vt("A"), vt("C")],
            vt("C"): [vt("B")]
        }

        with pytest.raises(exceptions.VertexNotExistError):
            ug.get_vertex_by_name("E")

        with pytest.raises(exceptions.VertexNotExistError):
            ug.add_new_edge("C", "E")
Пример #14
0
def main():
    graph_filename = input("Graph filename: ")
    graph = UndirectedGraph(graph_filename)

    start_node = input("Start node: ")
    end_node = input("End node: ")

    shortest_path = graph.shortest_path(start_node, end_node)
    path = shortest_path['path']
    cost = shortest_path['cost']

    if path is None:
        print(f"There is no path connecting {start_node} to {end_node}.")
    else:
        print(
            f"Path from {start_node} to {end_node} is {path_to_string(path)},",
            f"and have cost {cost}.")
Пример #15
0
    def test_traverse(self):
        vertexes_names = []

        def traverse_visit_callback(vertex):
            vertexes_names.append(vertex.name)

        un = UndirectedGraph("A", "B", "C", "D")
        un.add_new_edge("A", "B")
        un.add_new_edge("B", "C")
        un.add_new_edge("C", "D")

        # bfs
        un.bfs_traverse("A", traverse_visit_callback)
        assert vertexes_names == ["A", "B", "C", "D"]
        vertexes_names = []
        # dfs
        un.dfs_traverse("A", traverse_visit_callback)
        assert vertexes_names == ["A", "B", "C", "D"]
Пример #16
0
    def test_simple(self):
        graph = UndirectedGraph(5)

        graph.add(0, 1, 7)
        graph.add(0, 2, 3)
        graph.add(0, 3, 2)
        graph.add(0, 4, 6)
        graph.add(1, 2, 9)
        graph.add(1, 3, 4)
        graph.add(1, 4, 8)
        graph.add(2, 3, 4)
        graph.add(2, 4, 5)
        graph.add(3, 4, 5)

        min_tree_weight, tree_edges = prim(graph)
        expected_min_weight = 14

        self.assertEqual(expected_min_weight, min_tree_weight)
Пример #17
0
def read_random_graph(orderstr: str,
                      size: Optional[int]) -> Tuple[UndirectedGraph, int]:
    order = to_int(orderstr)
    fully_meshed_size = order * (order - 1) // 2
    if size is None:
        size = fully_meshed_size
    elif size > fully_meshed_size:
        raise ValueError(
            f"{order} nodes accommodate at most {fully_meshed_size} edges")
    edges_name = f"random_edges_order_{orderstr}"
    stats_name = f"random_stats"
    edges_path = os.path.join(os.pardir, "data", edges_name + ".txt")
    stats_path = os.path.join(os.pardir, "data", stats_name + ".txt")
    adjacencies = read_edges(edges_path, orderstr, order, size)
    clique_count = read_stats(stats_path, orderstr, size)
    g = UndirectedGraph(adjacencies=adjacencies)
    assert g.order == order
    assert g.size() == size
    return g, clique_count
Пример #18
0
    def testIndependentSet(self):
        n = 100
        e = 5 * n
        g = UndirectedGraph()
        for i in range(e):
            u = int(random() * n)
            v = int(random() * n)
            if u == v:
                continue
            if not g.contains(u):
                g.add_node(u)
            if not g.contains(v):
                g.add_node(v)
            g.connect(u, v)

        ind_set = g.independent_set(8)
        for i in ind_set:
            neighbors = g.e[i]
            self.assertEqual(neighbors.intersection(ind_set), set([]))
Пример #19
0
def build_graph(adj, features, labels):
    edges = np.array(adj.nonzero()).T
    y_values = np.array(labels.nonzero()).T

    domain_labels = []
    for i in range(labels.shape[1]):
        domain_labels.append("c" + str(i))

    # create graph
    graph = UndirectedGraph()
    id_obj_map = []
    for i in range(adj.shape[0]):
        n = Node(i, features[i, :], domain_labels[y_values[i, 1]])
        graph.add_node(n)
        id_obj_map.append(n)
    for e in edges:
        graph.add_edge(Edge(id_obj_map[e[1]], id_obj_map[e[0]]))

    return graph, domain_labels
Пример #20
0
 def setUp(self):
     self.graph = UndirectedGraph("graph.csv")
Пример #21
0
def test_degeneracy_ordering_empty() -> None:
    g = UndirectedGraph(adjacencies=[])
    assert list(degeneracy_ordering(g)) == []
    assert list(degeneracy_ordering(g, drop=1)) == []
Пример #22
0
def dfs_iterative(graph, start_node):
    visited = [start_node]
    stack = [start_node]
    print('Visited', start_node)
    while stack != []:
        popped = stack.pop()
        if popped not in visited:
            print('Visited', popped)
            visited.append(popped)
        for node in graph.adjacents(popped):
            if node not in visited:
                stack.append(node)


if __name__ == '__main__':
    g = UndirectedGraph()
    g.add_edge(0, 1)
    g.add_edge(0, 2)
    g.add_edge(0, 3)
    g.add_edge(1, 4)
    g.add_edge(1, 5)
    g.add_edge(2, 6)
    g.add_edge(2, 7)
    g.add_edge(3, 7)

    bfs(g, 0)
    print('=' * 50)
    dfs(g, 0)
    print('=' * 50)
    dfs_iterative(g, 0)
Пример #23
0
        def remove_independent_set(regions):
            """
                Processes a set of regions, detecting and removing an independent set
                of vertices from the regions' graph representation, and re-triangulating
                the resulting holes.

                Arguments:
                regions -- a set of non-overlapping polygons that tile some part of the plane

                Returns: a new set of regions covering the same subset of the plane, with fewer vertices
            """
            # Take note of which points are in which regions
            points_to_regions = {}
            for idx, region in enumerate(regions):
                for point in region.points:
                    if point in points_to_regions:
                        points_to_regions[point].add(idx)
                        continue

                    points_to_regions[point] = set([idx])

            # Connect graph
            g = UndirectedGraph()
            for region in regions:
                for idx in range(region.n):
                    u = region.points[idx % region.n]
                    v = region.points[(idx + 1) % region.n]
                    if not g.contains(u):
                        g.add_node(u)
                    if not g.contains(v):
                        g.add_node(v)
                    g.connect(u, v)

            # Avoid adding points from outer triangle
            removal = g.independent_set(8, avoid=bounding_triangle.points)

            # Track unaffected regions
            unaffected_regions = set([i for i in range(len(regions))])
            new_regions = []
            for p in removal:
                # Take note of affected regions
                affected_regions = points_to_regions[p]
                unaffected_regions.difference_update(points_to_regions[p])

                def calculate_bounding_polygon(p, affected_regions):
                    edges = []
                    point_locations = {}
                    for j, i in enumerate(affected_regions):
                        edge = set(regions[i].points)
                        edge.remove(p)
                        edges.append(edge)
                        for v in edge:
                            if v in point_locations:
                                point_locations[v].add(j)
                            else:
                                point_locations[v] = set([j])

                    boundary = []
                    edge = edges.pop()
                    for v in edge:
                        point_locations[v].remove(len(edges))
                        boundary.append(v)
                    for k in range(len(affected_regions) - 2):
                        v = boundary[-1]
                        i = point_locations[v].pop()
                        edge = edges[i]
                        edge.remove(v)
                        u = edge.pop()
                        point_locations[u].remove(i)
                        boundary.append(u)

                    return shapes.Polygon(boundary)

                # triangulate hole
                poly = calculate_bounding_polygon(p, affected_regions)
                triangles = spatial.triangulatePolygon(poly)
                for triangle in triangles:
                    self.dag.add_node(triangle)
                    for j in affected_regions:
                        region = regions[j]
                        self.dag.connect(triangle, region)
                    new_regions.append(triangle)

            for i in unaffected_regions:
                new_regions.append(regions[i])

            return new_regions
Пример #24
0
                    self._marked[a] = True
                    self.queue.append(a)

    def has_path_to(self, v: int):
        return self._marked[v]

    def path_to(self, v: int):
        if self.has_path_to(v) == False: return None
        path = []
        x = v
        while x != self._s:
            path.append(x)
            x = self._edgeto[x]
        path.append(self._s)
        for i in reversed(path):
            print(f"{i}->", end='')

    def marked(self, v: int):
        return self._marked[v]


G1 = UndirectedGraph(5)
G1.add_edge(0, 1)
G1.add_edge(1, 2)
G1.add_edge(2, 3)
print(G1)
bfs = BFS(G1, 0)
print(bfs.has_path_to(3))
print(bfs.path_to(4))
print(bfs.path_to(3))
Пример #25
0
from server import *
from graph import UndirectedGraph  # assumes we use the graph module from class
#test10(29577354,29577354)

rgraph = read_city_graph("edmonton-roads-2.0.1.txt")  # read data
cost_distance(29577354, 29577354)
graph = UndirectedGraph({1, 2, 3, 4, 5, 6}, [(1, 2), (1, 3), (1, 6), (2, 1),
                                             (2, 3), (2, 4), (3, 1), (3, 2),
                                             (3, 4), (3, 6), (4, 2), (4, 3),
                                             (4, 5), (5, 4), (5, 6), (6, 1),
                                             (6, 3), (6, 5)])
weights = {
    (1, 2): 7,
    (1, 3): 9,
    (1, 6): 14,
    (2, 1): 7,
    (2, 3): 10,
    (2, 4): 15,
    (3, 1): 9,
    (3, 2): 10,
    (3, 4): 11,
    (3, 6): 2,
    (4, 2): 15,
    (4, 3): 11,
    (4, 5): 6,
    (5, 4): 6,
    (5, 6): 9,
    (6, 1): 14,
    (6, 3): 2,
    (6, 5): 9
}
Пример #26
0
 def __init__(self, V):
     self.weights = UndirectedGraph(V)
     self.units = numpy.random.random(V) < 0.5
     self.biases = numpy.zeros(V)
Пример #27
0
    # tests are files that have the 'in' extension
    if test.endswith('.in') is False:
        continue

    print(f'\nSolving {test}')

    # read the file
    with open(f'./tests/{test}', 'r') as f:
        n = int(f.readline().strip())
        m = int(f.readline().strip())
        # make sure the test is valid
        assert n > 0, 'Number of nodes is invalid'
        # I can have a maximum number of edges of n*(n-1)/2
        assert m <= n * (n - 1) / 2, 'Number of edges is too big'
        # create our graph
        g = UndirectedGraph(n, {})
        for _ in range(m):
            line = f.readline().strip()
            a, b = [int(x) for x in line.split(' ')]
            g.add_edge(a, b)

        # print(g)

        # answer the questions
        f_out = open('./tests/' + test.replace('.in', '.out'), 'w')
        no_queries = int(f.readline().strip())
        for _ in range(no_queries):
            line = f.readline().strip()
            a, b = [int(x) for x in line.split(' ')]
            res = g.get_shortest_path(a, b)
            assert res == g.get_shortest_path_simple_bfs(
Пример #28
0
 def test_load_graph_conflicting_lines(self):
     with self.assertRaises(ValueError):
         UndirectedGraph("test/graph-with-conflicting-lines.csv")
Пример #29
0
 def test_calculation(self):
     graph = UndirectedGraph(5, [(0, 1), (2, 3), (0, 4)])
     self.assertEqual(disjoint_subset_sizes(graph), [3, 2])
Пример #30
0
    def test_create_exceptions(self):
        with self.assertRaises(TypeError):
            graph = UndirectedGraph(None, [(0, 1), (2, 3), (0, 4)])

        with self.assertRaises(TypeError):
            graph = UndirectedGraph(4, None)