def test_get_vertices_for_directed_graph(self): g = Graph(True) g.add_edge((1, 2)) actual = g.get_vertices() expected = [1, 2] self.assertEqual(actual, expected, 'should return all vertices')
def test_get_vertices_for_directed_graph(self): g = Graph(True) g.add_edge((1,2)) actual = g.get_vertices() expected = [1,2] self.assertEqual(actual, expected, 'should return all vertices')
def update_MST_4(G: Graph, T: Graph, e: Tuple[str, str], weight: int): """ Sig: Graph G(V, E), Graph T(V, E), edge e, int -> Pre: Post: Ex: TestCase 4 below """ (u, v) = e assert (e in G and e in T and weight > G.weight(u, v)) G.set_weight(u, v, weight) T.remove_edge(u, v) a_nodes = set() dfs(T, u, a_nodes) all_edges = G.edges min_edge = e for (l, m) in all_edges: # Variant: len(all_edges) - all_edges.index((l, m)) if (l in a_nodes and m not in a_nodes) or (m in a_nodes and l not in a_nodes): (u, v) = min_edge if G.weight(l, m) < G.weight(u, v): min_edge = (l, m) (u, v) = min_edge T.add_edge(u, v, G.weight(u, v))
def test_add_node_to_empty_graph(): graph = Graph() graph.add_node("Test") expected = {"Test": {}} output = graph.graph assert output == expected
def test_add_edge_node_does_node_exist(): graph = Graph() graph.add_edge(1, 2) expected = {} output = graph.graph assert output == expected
def test_dijkstra_simple(self): graph = Graph('test/netfiles/test1.net.xml', False) costs = {} for edge in graph.edges: costs[edge] = 1 graph.set_destination_and_costs(graph.edges[-1], costs) self.assertEqual(graph.dijkstra(graph.edges[1], costs), ['-25','5'])
def test_remove_edge_from_empty_graph(): graph = Graph() graph.remove_edge("A", "B") expected = {} output = graph.graph assert output == expected
def test_returns_array_of_vertices_for_graph_as_list(self): g = Graph() g.add_edge(1, 2, 1) g.add_edge(2, 3, 1) has_cycle, vertices = topological_sort(g) self.assertEqual(False, has_cycle) self.assertEqual([3, 2, 1], vertices)
def add_graph(self): self.graph = Graph(self.graph_field) self.graph.mpl_connect("button_press_event", self.on_press) self.graph.mpl_connect("button_release_event", self.on_release) self.graph.mpl_connect("motion_notify_event", self.on_move) self.graph.mpl_connect('scroll_event', self.on_scroll) self.gridLayout.addWidget(self.graph, 1, 0, 1, 5)
def test_add_users_to_a_graph(self): graph = Graph() user = User() user_id = user.get_id() graph.add_user(user) assert user_id in graph.users and graph.users[user_id] == user
def test_graph(): """Fixture for graph.""" from src.graph import Graph g = Graph(['A', 'B', 'C', 'D', 'E']) g1 = Graph(['A']) g0 = Graph() return g0, g1, g
def test_dijkstra_complex(self): graph = Graph('test/netfiles/test4.net.xml', False) costs = {} for edge in graph.edges: costs[edge] = 1 graph.set_destination_and_costs('30668', costs) self.assertEqual(graph.dijkstra('-31439', costs), ['-31439','-30057','-28887','28866','-23377','-22520','-21950','-17064','-16421','-15637','-3694','-3348','-158','144','-212','213','-370','420','-809','1807','-2481','2488','2556','-3837','3836','4158','4982','12338','-20947','-20171','20161','20824','-22781','-22135','22133','22780','27742','29467','30668'])
def create_graph(self): if not hasattr(self, 'graph') or self.graph is None: path_scraped = os.path.join(PATH_REPO, self.repo.get_id(), PATH_SCRAPED) first_file = os.listdir(path_scraped)[0] self.graph = Graph(os.path.join(path_scraped, first_file)) return self.graph
def test_set_edge_value_if_edge_exists(self): g = Graph(True) g.add_edge((1,2,10)) g.set_edge_value((1,2), 20) self.assertEqual(g.table[1][2], 20, 'should have updated the edge value')
def test_set_edge_value_works_for_undirected_graphs(self): g = Graph(False) g.add_edge((1,2,10)) g.set_edge_value((1,2), 30) self.assertEqual(g.table[1][2], 30, 'has updated the edge') self.assertEqual(g.table[2][1], 30, 'reverse edge was updated too')
def __init__(self, graph: Graph): number_of_vertices = graph.number_of_vertices() self.color: List[Color] = [Color.WHITE] * number_of_vertices self.dist_from_source: List = [None] * number_of_vertices self.parent_vertice: List = [None] * number_of_vertices for vertice in graph.get_vertices(): if self.color[vertice] != Color.BLACK: self.__run(graph, vertice)
def test_split_edge_with_value(self): edge = (1, 2, 3) g = Graph() (tail, head, value) = g.split_edge(edge) self.assertEqual(tail, 1) self.assertEqual(head, 2) self.assertEqual(value, 3)
def test_get_words(self): self.graph = Graph(NEWS) res = self.graph.get_words() assert set(res) == set(['hazzaaaa', 'President','took', 'sharp', 'verbal', 'shots', 'Speaker', 'Thursday', 'announced', 'billion', 'new', 'subsidies', 'farmers', 'ranchers', 'questioning', 'mental', 'faculties', 'powerful', 'woman'])
def test_remove_edge_one_not_in_graph(): graph = Graph() graph.graph['A'] = set([1, 2, 3]) graph.remove_edge('A', 6) expected = {'A': {1, 2, 3}} output = graph.graph assert output == expected
def test_split_edge_with_value(self): edge = (1,2,3) g = Graph() (tail, head, value) = g.split_edge(edge) self.assertEqual(tail, 1) self.assertEqual(head, 2) self.assertEqual(value, 3)
def test_add_same_node_twice(): graph = Graph() graph.add_node("Node_1") graph.add_node("Node_1") expected = {"Node_1": {}} output = graph.graph assert output == expected
def test_remove_node_does_not_exist(): graph = Graph() graph.graph["test_node"] = {} graph.remove_node("test") expected = {"test_node": {}} output = graph.graph assert output == expected
def dfs_residual(G: Graph, R: Graph, node: str, nodes: Set[str]): nodes.add(node) for neighbor in G.neighbors(node): capacity = G.capacity(node, neighbor) flow = G.flow(node, neighbor) R.add_edge(neighbor, node, capacity=flow, flow=0) if neighbor not in nodes: dfs_residual(G, R, neighbor, nodes)
def test_add_edge_node_to_itself(): graph = Graph() graph.graph["node_1"] = set() graph.add_edge("node_1", "node_1") expected = {"node_1": {"node_1"}} output = graph.graph assert output == expected
def test_incident_in_directed_graph(self): g = Graph(directed = True) g.add_edge((2,1)) g.add_edge((3,1)) actual = g.incident(1) expected = [2, 3] self.assertEqual(actual, expected, '1 has two incident vertexes')
def test_get_edge_value_in_directed_graph(self): g = Graph(True) g.add_edge((1,2,3)) self.assertEqual(g.get_edge_value((1,2)), 3, 'should have stored value') self.assertIsNone(g.get_edge_value((2,1)), 'should have no value for reverse edge')
def test_set_edge_value_if_graph_is_directed_and_inverse_edge_exists(self): g = Graph(True) g.add_edge((1,2,10)) g.add_edge((2,1,20)) g.set_edge_value((1,2), 30) self.assertEqual(g.table[1][2], 30, 'has updated the edge') self.assertEqual(g.table[2][1], 20, 'reverse edge remained the same')
def test_breadth_first_search_one_node_graph(capsys): graph = Graph() graph.graph['A'] = set() graph.breadth_first_search('A') expected = "A " output = capsys.readouterr().out assert output == expected
def test_incident_in_directed_graph(self): g = Graph(directed=True) g.add_edge((2, 1)) g.add_edge((3, 1)) actual = g.incident(1) expected = [2, 3] self.assertEqual(actual, expected, '1 has two incident vertexes')
def print_edges_with_weight(graph: Graph): if isinstance(graph.get_graph(), nx.MultiGraph): for e in graph.get_edges(): print(f"Edge : ({e[0]},{e[1]})") else: for e in graph.get_edges(): print( f"Edge : ({e[0]},{e[1]}) = {graph.get_edge_weight(e[0], e[1])}" )
def test_connect_users_in_a_graph(self): graph = Graph() user1 = User() user2 = User() graph.add_user(user1) graph.add_user(user2) graph.connect_users(user1.get_id(), user2.get_id()) assert user2 in user1.get_connections() and user1 in user2.get_connections()
def setUp(self): self.mockGraph = Graph() self.mockGraph.add_edge("A", "B", 1) self.mockGraph.add_edge("A", "C", 1) self.mockGraph.add_edge("A", "D", 8) self.mockGraph.add_edge("B", "D", 3) self.mockGraph.add_edge("C", "D", 1) self.mockGraph.start = "A" self.mockGraph.end = "D"
def test_add_edge_multiple_times_nothing_happens(self): g = Graph(True) g.add_edge((1,2,3)) g.add_edge((1,2,3)) g.add_edge((1,2,3)) g.add_edge((1,2,3)) self.assertIn(1, g.table, 'should have stored the tail in table') self.assertIn(2, g.table[1], 'should have stored the head in table')
def ordered_graph(self): # get ordered nodes and connections self.sort_nodes_connections() # self.set_next_nodes() self.net_graph = Graph(self.nodes, self.connections) self.computation_order, self.normal_ops = self.net_graph.get_computation_order( ) self.ready = True
def setUp(self): self.graph = Graph({ ("A", "B"): 3, ("A", "C"): 1, ("B", "C"): 7, ("B", "D"): 5, ("B", "E"): 1, ("C", "D"): 2, ("D", "E"): 7, })
def test_get_weights1(self): self.graph = Graph(["text edge graph edge"], 3) df = self.graph.get_weights() assert df.loc["text", "graph"] == 1 assert df.loc["graph", "text"] == 1 assert df.loc["text", "edge"] == 1 assert df.loc["edge", "text"] == 1 assert df.loc["edge", "graph"] == 3 assert df.loc["graph", "edge"] == 3
def __init__(self, lst_news, window_size=5): """Inits Graph Args: lst_news: list of string. list of news articles. windown_size: int. Size of the sliding window """ # call the ___init__ of the parent class Graph.__init__(self, lst_news, window_size) self.edges = self.__clean_edges(self.edges) self.edge_weights = self.__clean_weights(self.edge_weights)
def test_add_edge_for_directed_graph(self): g = Graph(True) g.add_edge((1,2,3)) self.assertIn(1, g.table, 'should have stored a key for tail vertex') self.assertIn(2, g.table[1], 'should have stored the edge') self.assertEqual(g.table[1][2], 3, 'should have stored the edge value') self.assertIn(2, g.table, 'should not have stored the node') self.assertNotIn(1, g.table[2], 'should not have stored the reverse edge')
def constructor(M, sigma, kind='log'): g = Graph() for i in range(len(M)): for j in range(len(M[i])): for p in range(len(M)): for q in range(len(M[i])): if p != i or q != j: g.add_edge(get_name(i, j), get_name(p, q), weight(M, [i, j], [p, q], kind, sigma)) g.normalize() return g
def test_set_weight(self): """ Test setting the weight of an edge between two nodes. """ g = Graph() g.add_node("A") g.add_node("B") g.add_edge("B", "A") self.assertEqual(g.get_weight("B", "A"), 0.0) g.set_weight("B", "A", 123.45) self.assertEqual(g.get_weight("B", "A"), 123.45)
def test_add_edge_for_undirected_graph(self): g = Graph(False) g.add_edge((1, 2, 3)) self.assertIn(1, g.table, 'should have stored a key for tail vertex') self.assertIn(2, g.table[1], 'should have stored the edge') self.assertEqual(g.table[1][2], 3, 'should have stored the edge value') self.assertIn(2, g.table, 'should have stored a key for head vertex') self.assertIn(1, g.table[2], 'should have stored the reversed edge') self.assertEqual(g.table[2][1], 3, 'should have stored the edge value')
def test_add_edge_for_undirected_graph(self): g = Graph(False) g.add_edge((1,2,3)) self.assertIn(1, g.table, 'should have stored a key for tail vertex') self.assertIn(2, g.table[1], 'should have stored the edge') self.assertEqual(g.table[1][2], 3, 'should have stored the edge value') self.assertIn(2, g.table, 'should have stored a key for head vertex') self.assertIn(1, g.table[2], 'should have stored the reversed edge') self.assertEqual(g.table[2][1], 3, 'should have stored the edge value')
def __init__(self, graph: Graph): self.color: List[Color] = [Color.WHITE] * graph.number_of_vertices() self.discovered_vertice_time: List = [None ] * graph.number_of_vertices() self.final_vertice_time: List = [None] * graph.number_of_vertices() self.predecessor: List = [None] * graph.number_of_vertices() self.count: int = 0 for vertice in graph.get_vertices(): if self.color[vertice] != Color.BLACK: self.run(graph, vertice)
def test_add_edge_for_directed_graph(self): g = Graph(True) g.add_edge((1, 2, 3)) self.assertIn(1, g.table, 'should have stored a key for tail vertex') self.assertIn(2, g.table[1], 'should have stored the edge') self.assertEqual(g.table[1][2], 3, 'should have stored the edge value') self.assertIn(2, g.table, 'should not have stored the node') self.assertNotIn(1, g.table[2], 'should not have stored the reverse edge')
def test_neighbours_in_directed_graph(self): g = Graph(True) g.add_edge((1,2)) g.add_edge((1,3)) expected = [2, 3] actual = g.neighbours(1) self.assertEqual(actual, expected, 'should find neighbours of 1') expected = [] actual = g.neighbours(2) self.assertEqual(actual, expected, '2 has no neighbours')
def __init__(self, graph: Graph, list_vertices: List[int] = None): num_vertices: int = graph.number_of_vertices() self.marked: List[bool] = [False] * num_vertices self.id: List = [None] * num_vertices self.count: int = 0 if not list_vertices: list_vertices = graph.get_vertices() for vertice in list_vertices: if not self.marked[vertice]: self.__dfs(graph, vertice) self.count += 1
def test_is_optimalization_needed(self): graph = Graph('test/netfiles/test1.net.xml', False) graph.edges = ['1', '2', '3', '4', '5'] graph.set_destination_and_costs('5', {'1':10, '2':10, '3':10, '4':10, '5':10}) self.assertTrue(graph.is_optimalization_needed(['1','3','5'], {'1':10, '2':10, '3':12, '4':10, '5':10}, 0.1)) self.assertTrue(graph.is_optimalization_needed(['1','3','5'], {'1':10, '2':8, '3':10, '4':10, '5':10}, 0.1)) self.assertFalse(graph.is_optimalization_needed(['1','3','5'], {'1':10, '2':10, '3':8, '4':10, '5':10}, 0.1)) self.assertFalse(graph.is_optimalization_needed(['1','3','5'], {'1':10, '2':12, '3':10, '4':10, '5':10}, 0.1))
def kruskal_union_find_mst(graph): """ Uses Kruskel's greedy algorithm to compute the MST of graph. Running time: O(m*log n) - where m is the number of edges and n is the number of vertices. Params: graph: object, instance of src.graph.Graph Returns: object, src.graph.Graph instance reperesenting the MST. """ mst_edges = [] edges = graph.get_edges() num_vertices = len(graph.get_vertices()) edges = graph.get_edges() edges.sort(key=lambda e: e[2]) union_find = UnionFind() index = 0 while index < num_vertices: edge = edges[index] [tail, head, value] = graph.split_edge(edge) index += 1 if union_find.find(head) == union_find.find(tail): continue else: union_find.union(head, tail) mst_edges.append(edge) mst = Graph.build(edges=mst_edges, directed=False) return mst
def setUp(self): self.graph = Graph() self.user1 = User() self.user2 = User() self.user3 = User() self.user4 = User() self.users = [self.user1, self.user2, self.user3, self.user4]
def test_bellman_ford_with_non_negative_cycle(self): """ Given the following graph from the lecture: -2 (a)-------->(b) ^| | | | 4\ -1/ \ / \(c)</ / \ 2/ \-3 v/ \v (x) (y) \^ /^ \ / 1\ /-4 \ / (z) And and a vertex (s) that is connected to all other vertices through edges of cost 0. """ g = Graph.build(edges=[('a', 'b', -2), ('c', 'a', 4), ('b', 'c', -1), ('c', 'x', 2), ('c', 'y', -3), ('z', 'x', 1), ('z', 'y', -4)], directed=True) g.add_vertex('s') for vertex in g.get_vertices(): g.add_edge(('s', vertex, 0)) (costs, __) = shortest_path(g, 's', return_paths=False) expected_costs = {'a': 0, 'c': -3, 'b': -2, 's': 0,'y': -6, 'x': -1,'z': 0} self.assertEqual(costs, expected_costs, 'should produce the correct costs')
def test_johnson(self): """ Given the following graph from the lecture: -2 (a)-------->(b) ^| | | | 4\ -1/ \ / \(c)</ / \ 2/ \-3 v/ \v (x) (y) \^ /^ \ / 1\ /-4 \ / (z) """ g = Graph.build(edges=[('a', 'b', -2), ('c', 'a', 4), ('b', 'c', -1), ('c', 'x', 2), ('c', 'y', -3), ('z', 'x', 1), ('z', 'y', -4)], directed=True) actual = johnson(g) expected = { 'a': {'a': 0, 'c': -3, 'b': -2, 'y': -6, 'x': -1, 'z': INF}, 'c': {'a': 4, 'c': 0, 'b': 2, 'y': -3, 'x': 2, 'z': INF}, 'b': {'a': 3, 'c': -1, 'b': 0, 'y': -4, 'x': 1, 'z': INF}, 'y': {'a': INF, 'c': INF, 'b': INF, 'y': 0, 'x': INF, 'z': INF}, 'x': {'a': INF, 'c': INF, 'b': INF, 'y': INF, 'x': 0, 'z': INF}, 'z': {'a': INF, 'c': INF, 'b': INF, 'y': -4, 'x': 1, 'z': 0} } self.assertEqual(actual, expected, 'should return correct all pairs shortest path distances')
def test_scc(self): """ Given the following graph it computes SCCs in it. />(2)---------->(8)----------v / | \ /->(10) (1) | v / | ^\ v /---->(9)<-\ v \(3)----->(4) \-(11) \ ^| \ /^ \ / | v / >(5) | (7)----/ ^\ | / \v v (6) """ g = Graph.build(edges=[(1,2), (3,2), (2,3), (3,4), (3,5), (5,4), (4,6), (4,7), (7,6), (6,5), (4,9), (7, 11), (11,9), (9,10), (10,11), (2,8), (8,9), (8,10)], directed=True) connected_components = scc(g) expected = [[8], [1], [2, 3], [9, 10, 11], [4, 5, 6, 7]] self.assertEqual(len(connected_components), len(expected), 'should return the same number of components') for component in connected_components: self.assertIn(component, expected, 'should detect strongly connected components')
def test_shortest_path_heap_case3(self): """ Compute a shortest path using the heap implementation. """ g = Graph.build(edges=[ ('a','b',1),('a','c',4),('a','d',4),('b','c',1),('c','d',1)], directed=True) shortest_path = shortest_path_heap(g, 'a') self.assertEqual(shortest_path['d'], 3)
def prims_heap_mst(graph): """ Computes minimal spanning tree using a heap data structure to store unexplored vertices. The difference is that it maintains the frontier of the explored MST in a heap, as such always computing the min vertex in O(logm), where m is the number of edges. The heap is used to store the vertices not the edges as in the previous implementation. The heap maintains two invariants: 1. elements in the heap are vertices not yet explored 2. keys under which each vertex is stored in the heap is the minimum weight of an edge incident on the vertex whose tail is already in the MST. Complexity: O(m*log n), m - number of edges, n - number of vertices Args: graph: object, data structure to hold the graph data. Returns: A Graph instance reperesenting the MST. """ mst_vertices = [] mst_edges = [] INF = float('inf') vertices = graph.get_vertices() num_vertices = len(vertices) frontier = VertexHeap.heapify([(v, INF) for v in vertices]) vertex = random.choice(graph.get_vertices()) frontier.remove(vertex) # This dict stores for each vertex the neighbour with the smallest edge, # and the edge cost. Format {vertex: (incident_vertex, edge_cost)} vertices = {} while vertex: mst_vertices.append(vertex) if len(mst_vertices) == num_vertices: break for edge in graph.egress(vertex): [__, head, cost] = graph.split_edge(edge) if head not in mst_vertices: [__, head_key] = frontier.remove(head) min_cost = min(cost, head_key) frontier.insert((head, min_cost)) if min_cost < head_key: vertices[head] = (vertex, cost) # Extract the vertex with min cost and compute it's associated min edge. (head, __) = frontier.extract_min() (tail, cost) = vertices[head] mst_edges.append((tail, head, cost)) vertex = head mst = Graph.build(edges=mst_edges, directed=False) return mst
def test_cluster_graph(self): """ The graph is specified in distances but it should look something like this: | *a | *e | *c | | | | | *d | *f | *b +---------------------------------------------> """ g = Graph.build(edges=[ ('a', 'e', 8), ('a', 'c', 7), ('a', 'd', 9), ('a', 'f', 10), ('a', 'b', 8), ('e', 'f', 6), ('e', 'd', 5), ('e', 'b', 10), ('e', 'c', 1), ('c', 'f', 5), ('c', 'd', 4), ('c', 'b', 9), ('d', 'f', 1), ('d', 'b', 7), ('f', 'b', 8) ], directed=False) (clusters, distances) = cluster_graph(g, 4) expectedClusters = { 'a': ['a'], 'c': ['c', 'e'], 'b': ['b'], 'd': ['d', 'f'] } expectedDistances = { ('b', 'c'): 9, ('c', 'd'): 4, ('a', 'd'): 9, ('a', 'b'): 8, ('a', 'c'): 7, ('b', 'd'): 7 } self.assertEqual(clusters, expectedClusters, 'should return correct clusters') self.assertEqual(distances, expectedDistances, 'should compute distances') (clusters, distances) = cluster_graph(g, 3) expectedClusters = { 'a': ['a'], 'b': ['b'], 'c': ['c', 'e', 'd', 'f'] } expectedDistances = { ('b', 'c'): 7, ('a', 'b'): 8, ('a', 'c'): 7 } self.assertEqual(clusters, expectedClusters, 'should return correct clusters') self.assertEqual(distances, expectedDistances, 'should compute distances')
class ReverseDelete(object): name = 'reversedelete' def __init__(self, save_all_edges=False): self.queue = PriorityQueue() self.graph = Graph() self.logging = False self.save_all_edges = save_all_edges self.all_edges = [] def set_logging(self, level): if level == 'debug': self.logging = True def add_edge(self, node1, node2, weight, n, n_nodes, n_edges): self.queue.put((-weight, (node1, node2))) if self.save_all_edges: self.all_edges.append((node1, node2, weight)) def init_from_file(self, f): self.graph.import_data(f, self.add_edge) def solve(self): res = [] while not self.queue.empty(): (weight, edge) = self.queue.get() self.graph.remove_edge(edge[0], edge[1]) if not self.graph.is_connected(): self.graph.add_edge(edge[0], edge[1], -weight) res.append((edge[0], edge[1], -weight)) continue return (self.graph.n_nodes, len(res), res)
def test_contract(self): g = Graph.build(edges=[(1,2), (2,3), (3,1)]) g = contract(g, (1,2)) self.assertIn('1_2', g.table, '1 and 2 have fused') self.assertIn(3, g.table['1_2'], '1 and 2 have fused') self.assertIn(3, g.table, '1 and 2 have fused') self.assertIn('1_2', g.table[3], '1 and 2 have fused') self.assertNotIn(2, g.get_vertices(), 'no more 2 vertex')
def test_get_sync_vertices(self): """ Given the graph below it should find 1 and 2 as sync vertices: (1) <- (3) / (2) <-/ """ g = Graph.build(edges=[(3,1), (3,2)], directed=True) actual = get_sync_vertices(g) expected = [1, 2] self.assertEqual(actual, expected, 'found sync vertices')
def construct_graph_of_count(count): graph = Graph() user1 = User() graph.add_user(user1) for i in range(0, count-1): user = User() graph.add_user(user) graph.connect_users(user1.get_id(), user.get_id()) return graph
def test_clone(self): g1 = Graph(False) g1.add_edge((1,2,10)) g1.add_edge((2,3,20)) g1.add_edge((3,1,30)) g2 = g1.clone() g2.set_edge_value((1,2), 100) self.assertEqual(g1.get_edge_value((1,2)), 10, 'should not have modified the value of the edge in g1') g2.add_vertex((3,4,40)) self.assertFalse(g1.adjacent(3,4), 'g1 should not have vertex 4')