Beispiel #1
0
    def setUp(self):
        dag = DirectedGraph()
        dag.add_node(0)
        dag.add_node(1)
        dag.add_node(2)
        dag.add_node(3)
        dag.add_node(4)
        dag.add_node(5)
        dag.connect(0, 1)
        dag.connect(0, 2)
        dag.connect(0, 3)
        dag.connect(3, 4)
        dag.connect(4, 5)
        self.dag = dag

        cyclic = DirectedGraph()
        cyclic.add_node(0)
        cyclic.add_node(1)
        cyclic.add_node(2)
        cyclic.add_node(3)
        cyclic.add_node(4)
        cyclic.connect(0, 1)
        cyclic.connect(1, 2)
        cyclic.connect(1, 3)
        cyclic.connect(2, 3)
        cyclic.connect(2, 4)
        cyclic.connect(4, 0)
        self.cyclic = cyclic
Beispiel #2
0
    def test_topological_sort(self):
        dg = DirectedGraph()
        dg.extend_vertexes("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")

        assert dg.topological_sort() == [vt("A"), vt("B"), vt("C"), vt("D")]

        dg = DirectedGraph("A", "B", "C")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "A")

        with pytest.raises(RuntimeError, match="存在环"):
            dg.topological_sort()

        dg = DirectedGraph("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("A", "D")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("D", "C")

        result = dg.topological_sort()
        assert result == [
            vt("A"), vt("B"), vt("D"), vt("C")
        ] or result == [vt("A"), vt("D"), vt("B"),
                        vt("C")]
def load_linqs_data(content_file, cites_file):
    '''
    Create a DirectedGraph object and add Nodes and Edges
    This is specific to the data files provided at http://linqs.cs.umd.edu/projects/projects/lbc/index.html
    Return two items 1. graph object, 2. the list of domain labels (e.g., ['AI', 'IR'])
    '''
    linqs_graph = DirectedGraph()
    domain_labels = []
    id_obj_map = {}

    with open(content_file, 'r') as node_file:
        for line in node_file:
            line_info = line.split('\n')[0].split('\t')
            n = Node(line_info[0], map(float, line_info[1:-1]),
                     line_info[-1])  # id, feature vector, label
            linqs_graph.add_node(n)
            if line_info[-1] not in domain_labels:
                domain_labels.append(line_info[-1])
            id_obj_map[line_info[0]] = n

    with open(cites_file, 'r') as edge_file:
        for line in edge_file:
            line_info = line.split('\n')[0].split('\t')
            if line_info[0] in id_obj_map.keys(
            ) and line_info[1] in id_obj_map.keys():
                from_node = id_obj_map[line_info[1]]
                to_node = id_obj_map[line_info[0]]
                linqs_graph.add_edge(Edge(from_node, to_node))

    print "domain labels"
    print domain_labels

    return linqs_graph, domain_labels
Beispiel #4
0
def test_ford_fulkerson_multiple_sources_two_sources():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('s2')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    graph.add_edge('s2', 'b', 5)

    flux = ford_fulkerson_multiple_sources(graph, ['s', 's2'], 't')
    assert flux == 20, 'Flux expected was 19, found: {}'.format(flux)
Beispiel #5
0
def test_ford_fulkerson_multiple_sources_two_sources_with_limit():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('s2')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    graph.add_edge('s2', 'b', 5)

    sources_limit = {'s': 14, 's2': 1}

    flux = ford_fulkerson_multiple_sources_and_limits(graph, ['s', 's2'], 't',
                                                      sources_limit)
    assert flux == 15, 'Flux expected was 15, found: {}'.format(flux)
Beispiel #6
0
def readFile(file):
    try:
        f = open(file, 'r')
        lines = f.readlines()
        mode = 'missing'
        vertices = []
        arestas = []
        arcos = []
        for l in lines:
            if ('*vertices' in l):
                mode = 'vertices'
            elif ('*arcs' in l):
                mode = 'arcs'
            elif ('*edges' in l):
                mode = 'edges'
            else:
                if (mode == 'vertices'):
                    vertices.append(l.replace('\n', ''))
                elif (mode == 'arcs'):
                    arcos.append(l.replace('\n', ''))
                elif (mode == 'edges'):
                    arestas.append(l.replace('\n', ''))
        if (mode == 'arcs'):
            return DirectedGraph(vertices, arcos)
        elif (mode == 'edges'):
            return NonDirectedGraph(vertices, arestas)
    finally:
        f.close()
Beispiel #7
0
def invert_graph(G):
    _G = DirectedGraph()
    for u in G.all_vertexes():
        connections = [(u.data, v) for u, v in G.get_vertex(u).items()]
        for v, w in connections:
            _G.add_edge(v, u, w)
    return _G
Beispiel #8
0
def johnson(g, w):
    vertexes_g = g.get_v()
    edges_g = g.get_e()
    s = NameVertex('s')
    vertexes_g1 = [s] + vertexes_g
    edges_g1 = edges_g.copy()
    for vertex in vertexes_g:
        edges_g1.append(Edge(s, vertex, 0))
    graph2 = DirectedGraph(vertexes_g1, edges_g1)
    if bellman_ford(graph2, w, s) == False:
        print("the in put graph contains a negative_weight cycle")
    else:
        h = dict()
        for vertex in vertexes_g1:
            h[vertex] = vertex.d
        def weight1(edge):
            return w(edge) + h[edge.u] - h[edge.v]
    n = len(vertexes_g)
    d = dict()
    for u in vertexes_g:
        dijkstra(g, weight1, u)
        d[u] = dict()
        for v in vertexes_g:
            d[u][v] = v.d + h[v] - h[u]
    return d
 def test_initialization(self):
     """Test public methods on an empty union."""
     # Create [].
     an_empty_graph = DirectedGraph()
     self.assertEqual(an_empty_graph.n_vertices(), 0)
     self.assertEqual(an_empty_graph.connected(0, 0), False)
     self.assertEqual(an_empty_graph.connected(0, 1), False)
     self.assertEqual(an_empty_graph.neighbors(0), set())
 def test_empty_graph(self):
     """Test public methods on an empty graph."""
     # Build an empty graph.
     a_graph = DirectedGraph()
     checker = Reachability(a_graph)
     # Non-existing vertex is always NOT reachable.
     self.assertFalse(checker.has_path(0, 0))
     self.assertFalse(checker.has_path(0, 1))
Beispiel #11
0
    def test_adjacency_matrix(self):
        dg = DirectedGraph("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")

        assert dg.adjacency_matrix == [[0, 1, 0, 0], [0, 0, 1, 0],
                                       [0, 0, 0, 1], [0, 0, 0, 0]]
Beispiel #12
0
class OpArgMngr(object):
    """Operator argument manager for storing operator workloads."""
    graph = DirectedGraph()
    ops = {}

    @staticmethod
    def add_workload(funcname, *args, **kwargs):
        key = funcname + "." + str(int(time.time()))
        OpArgMngr.ops[key] = {'args': args, 'kwargs': kwargs, 'funcname': funcname}

    def add_assignment(variable, assigned_value):
 def test_non_consecutive_adding(self):
     """Test adding vertices non-consecutively."""
     # Create [].
     a_graph = DirectedGraph()
     # Add 1 to [], which becomes [set(), set()].
     # Here 0 is added implicitly.
     a_graph.add(1)
     self.assertEqual(a_graph.n_vertices(), 2)
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 1), True)
Beispiel #14
0
def load_board(cities_filename, routes_filename):

    board = DirectedGraph()

    cities: dict[str, City] = _resolve_cities(cities_filename)

    for city in cities:
        board.add_node(cities[city].get_name())

    _resolve_routes(board, routes_filename)

    return board, cities
Beispiel #15
0
def main():
    G = DirectedGraph()
    G.add_vertex('A')
    G.add_vertex('B')
    G.add_vertex('C')
    G.add_vertex('D')
    G.add_vertex('E')
    G.add_edge('A', 'B')
    G.add_edge('B', 'C')
    G.add_edge('B', 'D')
    G.add_edge('A', 'E')
    print(strongly_connected(G))
Beispiel #16
0
def generate_directed_subgraph(original_graph, nodes_subset) -> DirectedGraph:

    new_graph = DirectedGraph()

    for node in original_graph.get_nodes():
        if node in nodes_subset:
            new_graph.add_node(node)

    for edge in original_graph.get_edges():
        if edge[0] in nodes_subset and edge[1] in nodes_subset:
            new_graph.add_edge(edge[0], edge[1], edge[2])

    return new_graph
Beispiel #17
0
    def __init__(self, dict_graph):
        self.graph = DirectedGraph(dict_graph)
        self.index = 0
        self.stack = []

        # Runs Tarjan
        # Set all node index to None
        for v in self.graph.nodes:
            v.index = None

        self.sccs = []
        for v in self.graph.nodes:
            if v.index == None:
                self.strongconnect(v, self.sccs)
 def test_neighbors(self):
     """Test root()."""
     # Create [{1, 2}, {2}, set()].
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(0, 2)
     a_graph.connect(1, 2)
     # Check neighbors on existing vertices.
     self.assertEqual(a_graph.neighbors(0), {1, 2})
     self.assertEqual(a_graph.neighbors(1), {2})
     self.assertEqual(a_graph.neighbors(2), set())
     # Check neighbors on non-existing vertices.
     self.assertEqual(a_graph.neighbors(3), set())
     self.assertEqual(a_graph.neighbors(4), set())
 def test_linked_list(self):
     """Test public methods on a linked list."""
     # Build a linked list:
     #   0 -> 1 -> 2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(1, 2)
     # Sort.
     a_sorter = TopologicalSort(a_graph)
     sorted_vertices = a_sorter.sort()
     # Only one correct sequence.
     self.assertEqual(sorted_vertices, (2, 1, 0))
     # Check the result using a graph.Reachability object.
     a_checker = Reachability(a_graph)
     self.assertTrue(self._sorted(sorted_vertices, a_checker))
Beispiel #20
0
def generate_rand_dawg(nchars, nwords, wordlenpdf=None):
    """
    Generate a random DAWG whose word lengths are distributed by function
    wordlenpdf, using gnerate_rand_lexicon above.
    input:
        nchars: number of characters in lexicon
        nwords: number of words in lexicon
        wordlenpdf: a function

    """
    rand_lex = generate_rand_lexicon(nchars, nwords, wordlenpdf)
    G = DirectedGraph()
    G.parselex(rand_lex)
    trie_to_dawg(G)
    return G
 def test_binary_tree(self):
     """Test public methods on a binary tree."""
     # Build a binary tree:
     #     0
     #    / \
     #   1   2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(0, 2)
     # Sort.
     a_sorter = TopologicalSort(a_graph)
     sorted_vertices = a_sorter.sort()
     # Either of the two sequences is correct.
     self.assertTrue(sorted_vertices in {(2, 1, 0), (1, 2, 0)})
     # Check the result using a graph.Reachability object.
     a_checker = Reachability(a_graph)
     self.assertTrue(self._sorted(sorted_vertices, a_checker))
Beispiel #22
0
    def test_traverse(self):
        vertexes_names = []

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

        dg = DirectedGraph("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")

        # bfs
        dg.bfs_traverse("A", traverse_visit_callback)
        assert vertexes_names == ["A", "B", "C", "D"]
        vertexes_names = []
        # dfs
        dg.dfs_traverse("A", traverse_visit_callback)
        assert vertexes_names == ["A", "B", "C", "D"]
 def test_binary_tree(self):
     """Test public methods on a binary tree."""
     # Build a binary tree:
     #     0
     #    / \
     #   1   2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(0, 2)
     checker = Reachability(a_graph)
     # All the vertices are reachable from the root.
     self.assertTrue(checker.has_path(0, 1))
     self.assertTrue(checker.has_path(0, 2))
     # Vertices in another subtree are NOT reachable.
     self.assertFalse(checker.has_path(1, 2))
     self.assertFalse(checker.has_path(2, 1))
     # Parent is NOT reachable.
     self.assertFalse(checker.has_path(1, 0))
     self.assertFalse(checker.has_path(2, 0))
Beispiel #24
0
    def test_create(self):
        dg = DirectedGraph()
        dg.extend_vertexes("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")
        assert [v.name for v in dg.vertexes] == ["A", "B", "C", "D"]
        assert dg.adjacency_dict == {
            vt("A"): [vt("B")],
            vt("B"): [vt("C")],
            vt("C"): [vt("D")],
            vt("D"): [],
        }

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

        with pytest.raises(exceptions.VertexNotExistError):
            dg.add_new_edge("E", "B")
 def test_implicit_adding_by_connecting(self):
     """Test connect(), which implicitly calls add()."""
     # Create [].
     a_graph = DirectedGraph()
     # Implicitly add 0, 1, 2 to [], then connect 1 with 2,
     # which makes [set(), {2}, set()].
     a_graph.connect(1, 2)
     self.assertEqual(a_graph.n_vertices(), 3)
     # Trivially connected vertices.
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(1, 1), True)
     self.assertEqual(a_graph.connected(2, 2), True)
     # Uni-directional connection created by connect().
     self.assertEqual(a_graph.connected(1, 2), True)
     self.assertEqual(a_graph.connected(2, 1), False)
     # Disconnected vertices.
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 0), False)
     self.assertEqual(a_graph.connected(0, 2), False)
     self.assertEqual(a_graph.connected(2, 0), False)
 def test_linked_list(self):
     """Test public methods on a linked list."""
     # Build a linked list:
     #   0 -> 1 -> 2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(1, 2)
     checker = Reachability(a_graph)
     # A vertex is always reachable from/to itself.
     self.assertTrue(checker.has_path(0, 0))
     self.assertTrue(checker.has_path(1, 1))
     self.assertTrue(checker.has_path(2, 2))
     # A downstream vertex is reachable from an upstream vertex.
     self.assertTrue(checker.has_path(0, 1))
     self.assertTrue(checker.has_path(1, 2))
     self.assertTrue(checker.has_path(0, 2))
     # A upstream vertex is NOT reachable from an downstream vertex.
     self.assertFalse(checker.has_path(1, 0))
     self.assertFalse(checker.has_path(2, 0))
     self.assertFalse(checker.has_path(2, 1))
Beispiel #27
0
    def make_graph(cls, root, strategy):
        """Compute the graph implied by some GameState."""
        graph = DirectedGraph()

        queue = deque()
        visited = set()

        # Add root to queue
        visited.add(root)
        queue.append(root)

        while queue:
            node = queue.popleft()
            if not node.is_over:
                for next in strategy.get_next_states(node):
                    graph.add_arc(node, next)
                    if next not in visited:
                        # Add `next` to queue.
                        visited.add(next)
                        queue.append(next)

        return graph
 def test_consecutive_adding(self):
     """Test adding vertices consecutively."""
     # Create [].
     a_graph = DirectedGraph()
     # Add 0 to [], which becomes [set()].
     a_graph.add(0)
     self.assertEqual(a_graph.n_vertices(), 1)
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 1), False)
     # Add 0 to [set()], nothing changes.
     a_graph.add(0)
     self.assertEqual(a_graph.n_vertices(), 1)
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 1), False)
     # Add 1 to [set()], which becomes [set(), set()].
     a_graph.add(1)
     self.assertEqual(a_graph.n_vertices(), 2)
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 1), True)
Beispiel #29
0
def main():
  g = DirectedGraph()
  for i in range(9):
    g.add_vertex(i)
  g.add_edge(0, 1, 4)
  g.add_edge(0, 7, 8)
  g.add_edge(1, 2, 8)
  g.add_edge(1, 7, 11)

  g.add_edge(2, 3, 7)
  g.add_edge(2, 8, 2)
  g.add_edge(2, 5, 4)
  g.add_edge(3, 4, 9)
  
  g.add_edge(3, 5, 14)
  g.add_edge(4, 5, 10)
  g.add_edge(5, 6, 2)
  g.add_edge(6, 7, 1)
  g.add_edge(6, 8, 6)
  g.add_edge(7, 8, 7)

  print(g)
  prim(g)
Beispiel #30
0
def test_ford_fulkerson():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    flux = ford_fulkerson(graph, 's', 't')
    assert flux == 19, 'Flux expected was 19, found: {}'.format(flux)