def test_wrong_node_for_edgenode(): v1 = Vertex() v2 = Vertex(a=1, b=2) v3 = Vertex() e = Edge(v1, v2, weight=1, c=3, d=4) with pytest.raises(Exception): Edgenode(head=v3, edge=e)
def test_edgenode_with_extra_args(): v1 = Vertex() v2 = Vertex() e = Edge(v1, v2, a=1, b=2) edgenode = Edgenode(head=v1, edge=e) assert edgenode.tail is v2 assert (edgenode.a, edgenode.b) == (1, 2)
def test_add_vertex(self): vert0 = Vertex(0) vert1 = Vertex(1) self.graph.add_vertex(vert0) self.graph.add_vertex(vert1) self.assertDictEqual(self.graph.vertices, {vert0: set(), vert1: set()})
def test_find_path_direct_connection(): a = Vertex("A13") b = Vertex("A14") a.add_edge(Edge(b)) assert find_path(a, b) == [a, b] # Path is only in one direction assert find_path(b, a) == []
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]
def test_hash(self): key = 15 value = 20 u = Vertex(key, value) v = Vertex(key, value) self.assertEqual(hash(u), hash(v))
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))
def main(): # initialize and prepare screen name = "path.txt" pygame.init() screen = pygame.display.set_mode(WINSIZE) pygame.display.set_caption('Rapidly Exploring Random Trees') white = 255, 240, 200 black = 20, 20, 40 RED = (255, 0, 0) screen.fill(black) pygame.draw.circle(screen, white, (300, 0), 98, 1) pygame.draw.circle(screen, white, (300, 200), 98, 1) pygame.display.update() graph = Graph(Vertex(-2, -0.5)) rrt(graph, Vertex(-2, -0.5), 300, screen, RED) done = 0 while not done: for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE): print("\nLeaving because you said so\n") done = 1 break
def construct_kg_walker(onto_file, walker_type, walk_depth): g = rdflib.Graph() if onto_file.endswith('ttl') or onto_file.endswith('TTL'): g.parse(onto_file, format='turtle') else: g.parse(onto_file) kg = KnowledgeGraph() for (s, p, o) in g: s_v, o_v = Vertex(str(s)), Vertex(str(o)) p_v = Vertex(str(p), predicate=True, _from=s_v, _to=o_v) kg.add_vertex(s_v) kg.add_vertex(p_v) kg.add_vertex(o_v) kg.add_edge(s_v, p_v) kg.add_edge(p_v, o_v) if walker_type.lower() == 'random': walker = RandomWalker(depth=walk_depth, walks_per_graph=float('inf')) elif walker_type.lower() == 'wl': walker = WeisfeilerLehmanWalker(depth=walk_depth, walks_per_graph=float('inf')) else: print('walker %s not implemented' % walker_type) sys.exit() return kg, walker
def test_add_edge(self): vert0 = Vertex(0) vert1 = Vertex(1) # Bi-directional test self.graph.add_vertex(vert0) self.graph.add_vertex(vert1) self.graph.add_edge(vert0, vert1) self.assertDictEqual(self.graph.vertices, { vert0: {vert1}, vert1: {vert0} }) # Directional test vert2 = Vertex(2) vert3 = Vertex(3) self.graph.add_vertex(vert2) self.graph.add_vertex(vert3) self.graph.add_edge(vert2, vert3, False) self.assertDictEqual(self.graph.vertices, { vert0: {vert1}, vert1: {vert0}, vert2: {vert3}, vert3: set() })
def test_valid_with_weights(): name1 = Vertex._make_test_vertex() name2 = Vertex._make_test_vertex() s = StringIO("2\n{0}\n{1}\n{0}|{1}|5\n{1}|{0}|2".format(name1, name2)) g = graph_from_file(s) assert g.size() == 2 assert g.is_connected()
def test_bfs_ssp(self): graph = Graph() a = Vertex(1) b = Vertex(2) c = Vertex(3) d = Vertex(4) e = Vertex(5) graph.add_vertex(a) graph.add_vertex(b) graph.add_vertex(c) graph.add_vertex(d) graph.add_vertex(e) graph.add_edge(a, b) graph.add_edge(a, d) graph.add_edge(b, c) graph.add_edge(b, e) graph.add_edge(c, e) assert graph.bfs_ssp(a, e) == [1, 2, 5] # (1,2) # (1,4) # (2,3) # (2,4) # (2,5) # (3,5)
def test_find_min_path(self): """ Metoda testująca znajdowanie minimalnej ścieżki za pośrednictwem metody zdefiniowanej na obiekcie grafu.""" min_cost, min_path = self.graph.find_min_path(Vertex("a"), Vertex("f")) self.assertEqual(min_cost, 9) self.assertEqual(min_path, ["a", "b", "c", "d", "f"])
def test_no_edges(): name1 = Vertex._make_test_vertex() name2 = Vertex._make_test_vertex() s = StringIO("2\n{}\n{}".format(name1, name2)) g = graph_from_file(s) assert g.size() == 2 assert not g.is_connected()
def relax(self, u : _g.Vertex, v : _g.Vertex, weight): ''' 一步松弛操作 ''' if v.d > u.d + weight: v.d = u.d + weight v.pi = u
def test_add_edge_normal(): a = Vertex("A5") b = Vertex("A6") c = Edge(b) a.add_edge(c) assert len(a.edges) == 1 assert c in a.edges
def testCopy(self): a = Vertex(1) b = Vertex(2) c = Vertex(3) G1 = Graph([a, b, c], [(a, b), (a, c)]) G2 = G1.copy() self.assertEqual(G1, G2)
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_extra_pipes(): name1 = Vertex._make_test_vertex() name2 = Vertex._make_test_vertex() s = StringIO("2\n{0}\n{1}\n{0}|{1}|5|2\n{1}|{0}|2|5".format(name1, name2)) g = graph_from_file(s) assert g.size() == 2 assert g.is_connected()
def main(): graph = Graph() # Instantiate your graph vl = [ Vertex('0', (2, 5)), Vertex('1', (5, 2)), Vertex('2', (2, 8)), Vertex('3', (8, 2)), ] for v in vl: graph.add_vertex(v) graph.add_edge(vl[0], vl[1]) graph.add_edge(vl[0], vl[3]) print(graph.vertices) # a_graph = BokehGraph(graph) # print('start vertex:', a_graph.graph.vertices['0'].edges) # print('bfs result:', a_graph.color_connections(a_graph.graph)) # a_graph.show() b_graph = RandomGraph() # print("b_graph vertices:", b_graph.graph.vertices) # print('start vertex:', b_graph.graph.vertices[0].edges) b_graph.show()
def test_equality(self): key = 15 value = 20 u = Vertex(key, value) v = Vertex(key, value) self.assertTrue(u == v) self.assertEqual(u, v)
def test_fail_set_and_get_nodelist(): vertices = [Vertex() for i in range(4)] nodelist = NodeList(vertices) v = Vertex() with pytest.raises(KeyError): nodelist[v] = 3 with pytest.raises(KeyError): nodelist[v]
def test_vertex_valid_edges(): """Test Vertex creation with a list of already-existing Edges.""" b = Vertex(Vertex._make_test_vertex()) c = Vertex(Vertex._make_test_vertex()) d = Edge(b) e = Edge(c) a = Vertex(Vertex._make_test_vertex(), [d, e]) assert a.edges == [d, e]
def test_add_neighbor(self): egon_vertex = Vertex('Egon') yurac_vertex = Vertex('Yurac') # Make to check the main values in both Vertex print("Egon Vertex: ", egon_vertex.id) print(egon_vertex.add_neighbor(yurac_vertex)) assert egon_vertex.add_neighbor(yurac_vertex) assert egon_vertex.neighbors == {yurac_vertex: 'yurac_vertex'}
def calculate(self, base_edges): self.iterations = 0 while True: self.iterations += 1 #calc potentials edges_queue = self.get_base_edges_queue(base_edges) initial_edge = edges_queue.popleft() initial_vertex = Vertex(number=initial_edge.start, potential=0) linked_vertex = Vertex(number=initial_edge.end, potential=-initial_edge.price) vertexes = [initial_vertex, linked_vertex] while len(edges_queue) != 0: edge = edges_queue.popleft() if filter(lambda x: x.number == edge.start, vertexes): potential = filter(lambda x: x.number == edge.start, vertexes)[0].potential vertexes.append(Vertex(number=edge.end, potential=potential - edge.price)) elif filter(lambda x: x.number == edge.end, vertexes): potential = filter(lambda x: x.number == edge.end, vertexes)[0].potential vertexes.append(Vertex(number=edge.start, potential=potential + edge.price)) else: edges_queue.append(edge) non_base_edges = filter(lambda x: not filter(lambda y: y.start == x.start and y.end == x.end, base_edges),self.graph.edges) delta_edge = filter(lambda x: self.get_delta(vertexes, x) > 0, non_base_edges) if not delta_edge: return base_edges delta_edge = delta_edge[0] base_edges.append(delta_edge) #get cycle temp_graph = Graph(self.graph.vertex_count, base_edges) cycle = temp_graph.get_cycle() forward_going_edges = self.get_forward_going_edge(cycle, delta_edge) backward_going_edges = cycle if len(backward_going_edges) == 0: raise Exception("Flow isn't bounded from bottom") delta = sorted(backward_going_edges, cmp=lambda x, y: x.capacity < y.capacity)[0].capacity replacement_edge = filter(lambda x: x.capacity == delta, backward_going_edges)[0] print('replacing {} -> {} with {} -> {}'.format(replacement_edge.start, replacement_edge.end,delta_edge.start,delta_edge.end)) for item in forward_going_edges: base_edge = filter(lambda x: x.equals(item), base_edges)[0] base_edge.capacity += delta for item in backward_going_edges: base_edge = filter(lambda x: x.equals(item), base_edges)[0] base_edge.capacity -= delta base_edges.remove(filter(lambda x: x.equals(replacement_edge), base_edges)[0])
def create_graph(filename): """ Reads file and creates a grid from the first line of text Rows then columns. Assigns prisoner and exit vertex. :param filename: File being parsed :return: returns graph, prisoner vertex, and vertex exit """ prison_graph = Graph() prisoner_vertex = None exit_vertex = None vertices = {} cameras = set() with open(filename, 'r') as graph_file: row, col = map(int, graph_file.readline().split()) print(f'Graph Size... Rows: {row} Columns: {col}') for line in graph_file: line = line.strip() cam_x, cam_y = map(int, line.split()) cameras.add((cam_x, cam_y)) print(f'Camera at: {cam_x},{cam_y}') for i in range(row): # iterate over rows for j in range(col): # iterate over columns vert = Vertex(f'{i},{j}') vertices[(i, j)] = vert if vert in cameras: vert.has_camera = True prison_graph.add_vertex(vert) # determine if there is a bordering cell without a camera and create # an undirected edge for i in range(row): for j in range(col): source_vertex = vertices[(i, j)] # if nothing up & no camera destination_vertex = (i - 1, j) if destination_vertex in vertices: prison_graph.add_undirected_edge(source_vertex, destination_vertex) # if nothing down & no camera # if nothing right & no camera # if nothing left & no camera for x in vertices: print(x, getattr(vertices[x], 'label')) # for key, values in prison_graph.adjacency_list.items(): # print(f'{getattr(key, "label")} : {values}') # The following line is here as a placeholder. Replace # this line with the real return values once you # load them from the prison data file. return prison_graph, prisoner_vertex, exit_vertex
def test_get_edge_weight(self): ramon = Vertex('Ramon Geronimo') jessie = Vertex('Jessie Pichardo') joel = Vertex('Joel Pichardo') ramon.add_neighbor(jessie, 10) ramon.add_neighbor(joel, 5) assert ramon.get_edge_weight(jessie) == 10 assert ramon.get_edge_weight(joel) == 5
def test_initialization(self): u = Vertex(15, 20) v = Vertex(1, 2) w = 10 edge = Edge(u, v, w) self.assertIsInstance(edge, Edge) self.assertIs(edge.u, u) self.assertIs(edge.v, v) self.assertEqual(edge.weight, w)
def __init__(self, atomType=None, radicalElectrons=None, spinMultiplicity=None, charge=None, label=''): Vertex.__init__(self) self.atomType = atomType or [] for index in range(len(self.atomType)): if isinstance(self.atomType[index], str): self.atomType[index] = atomTypes[self.atomType[index]] self.radicalElectrons = radicalElectrons or [] self.spinMultiplicity = spinMultiplicity or [] self.charge = charge or [] self.label = label
def test_get_edge_weight(self): v1 = Vertex(1) v2 = Vertex(2) v3 = Vertex(3) # Test default weight variable v2.add_neighbor(v1) assert v2.get_edge_weight(v1) == 1 # Test passed in weight variable v2.add_neighbor(v3, 3) assert v2.get_edge_weight(v3) == 3
def test_add_neighbor(self): label = "Sugar" vertex = Vertex(label) vertex.add_neighbor("Kevin", weight = 0) # Should tell us that Sugar has a neighbor assert any(vertex.neighbors) is True # Should tell us that Sugar's neighbor is Kevin assert vertex.neighbors == {"Kevin": 0}
def test_add_edge_duplicate(): a = Vertex("A7") b = Vertex("A8") c = Edge(b) d = Edge(b) a.add_edge(d) a.add_edge(c) assert len(a.edges) == 2 assert d in a.edges assert c in a.edges
def testKruskal(self): a = Vertex('a') b = Vertex('b') c = Vertex('c') d = Vertex('d') e = Vertex('e') f = Vertex('f') g = Vertex('g') h = Vertex('h') i = Vertex('i') vertices = [a, b, c, d, e, f, g, h, i] edges = [ (a, b), (a, h), (b, a), (b, c), (b, h), (c, b), (c, i), (c, f), (c, d), (d, c), (d, e), (d, f), (e, d), (e, f), (f, d), (f, e), (f, c), (f, g), (g, f), (g, h), (g, i), (h, a), (h, b), (h, i), (h, g), (i, c), (i, h), (i, g) ] G = Graph(vertices, edges) weight = [ 4, 8, 4, 8, 11, 8, 2, 4, 7, 7, 9, 14, 9, 10, 14, 10, 4, 2, 2, 1, 6, 8, 11, 7, 1, 2, 7, 6 ] z = dict() for x, y in zip(edges, weight): z[x] = y print("{}: {}".format(x, y)) def w(x, y): return z[(x, y)] ls = G.Kruskal(w) print(ls)
def testBfs(self): s = Vertex('s') r = Vertex('r') v = Vertex('v') w = Vertex('w') t = Vertex('t') x = Vertex('x') u = Vertex('u') y = Vertex('y') z = Vertex('z') vertices = [v, r, s, w, t, x, u, y, z] edges = [(s, r), (s, w), (r, v), (r, s), (v, r), (w, s), (w, t), (w, x), (t, w), (t, x), (t, u), (u, t), (u, x), (u, y), (x, w), (x, t), (x, u), (x, y), (y, x), (y, u)] g = Graph(vertices, edges) # g.print(AllEdges()) # for i in g.vertices: # i.print(Edge()) # print() g.bfs(s) # g.print(Vertices()) self.assertEqual(s.d, 0) self.assertEqual(r.d, 1) self.assertEqual(v.d, 2) self.assertEqual(w.d, 1) self.assertEqual(t.d, 2) self.assertEqual(x.d, 2) self.assertEqual(u.d, 3) self.assertEqual(y.d, 3)
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 testBfs(self): s = Vertex('s') r = Vertex('r') v = Vertex('v') w = Vertex('w') t = Vertex('t') x = Vertex('x') u = Vertex('u') y = Vertex('y') z = Vertex('z') vertices = [v, r, s, w, t, x, u, y, z] edges = [(s, r), (s, w), (r, s), (r, v), (v, r), (w, s), (w, t), (w, x), (t, w), (t, x), (t, u), (x, w), (x, t), (x, u), (x, y), (u, t), (u, x), (u, y), (y, x), (y, u)] # for i in r,w: # s.addEdge(i) # for i in s,v: # r.addEdge(i) # v.addEdge(r) # for i in s,t, x: # w.addEdge(i) # for i in w, x, u: # t.addEdge(i) # for i in w, t, u, y: # x.addEdge(i) # for i in t, x, y: # u.addEdge(i) # for i in x, u: # y.addEdge(i) # g = Graph([v,r,s,w,t,x,u,y,z]) g = Graph(vertices, edges) print wrestlers(g)
def testCut(self): a = Vertex('a') b = Vertex('b') c = Vertex('c') d = Vertex('d') e = Vertex('e') f = Vertex('f') g = Vertex('g') h = Vertex('h') i = Vertex('i') vertices = [a, b, c, d, e, f, g, h, i] edges = [(a, b), (b, c), (b, h), (c, i), (d, c), (e, d), (f, d), (f, e), (f, c), (g, f), (g, h), (g, i), (h, a), (h, i)] G = Graph(vertices, edges, directed=False) # weight = [4, 8, 11, 2, 7, 9, 14, 10, 4, 2, 2, 1, 8, 7] weight = [4, 8, 11, 2, 7, 9, 14, 10, 4, 2, 1, 6, 8, 7] z = dict() for x, y in zip(edges, weight): z[x] = y z[(x[1], x[0])] = y def w(x, y): return z[(x, y)] G.cut(a, h, w) r1 = set() r2 = set() for u in G.vertices: if u.root == a: r1.add(u) else: r2.add(u) self.assertEqual(r1, set([a, b])) self.assertEqual(r2, set([h, i, g, c, f, d, e]))
def testPrim(self): a = Vertex('a') b = Vertex('b') c = Vertex('c') d = Vertex('d') e = Vertex('e') f = Vertex('f') g = Vertex('g') h = Vertex('h') i = Vertex('i') vertices = [a, b, c, d, e, f, g, h, i] # edges = [(a, b), (a, h), (b, a), (b, c), (b, h), (c, b), (c, i), # (c, f), (c, d), (d, c), (d, e), (d, f), (e, d), (e, f), (f, d), # (f, e), (f, c), (f, g), (g, f), (g, h), (g, i), (h, a), (h, b), # (h, i), (h, g), (i, c), (i, h), (i, g)] # weight = [4, 8, 4, 8, 11, 8, 2, 4, 7, 7, 9, 14, 9, 10, 14, 10, 4, 2, # 2, 1, 6, 8, 11, 7, 1, 2, 7, 6] edges = [(a, b), (b, c), (b, h), (c, i), (d, c), (e, d), (f, d), (f, e), (f, c), (g, f), (g, h), (g, i), (h, a), (h, i)] weight = [4, 8, 11, 2, 7, 9, 14, 10, 4, 2, 1, 6, 8, 7] G = Graph(vertices, edges, False) z = dict() for x, y in zip(edges, weight): z[x] = y z[(x[1], x[0])] = y # print( "Prim edges: {}, weight: {}".format(x, y)) def w(x, y): return z[(x, y)] G.Prim(w, i) s = set() for u in G.vertices: s.add((u.p, u))
def test_top_sort_chain(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) c = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(b)) b.add_edge(Edge(c)) g = Graph([a, b, c]) assert g.top_sort() == [a, b, c]
def __init__(self, element=None, coord=np.array([0.0, 0.0, 0.0]), radicalElectrons=0, spinMultiplicity=1, implicitHydrogens=0, charge=0, label=''): Vertex.__init__(self) if isinstance(element, str): self.element = elements.__dict__[element] else: self.element = element self.coord = coord self.radicalElectrons = radicalElectrons self.spinMultiplicity = spinMultiplicity self.implicitHydrogens = implicitHydrogens self.charge = charge self.label = label self.atomType = None
def test_has_cycle_two_vertices_linked(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(b)) b.add_edge(Edge(a)) g = Graph([a, b]) assert g.has_cycle()
def test_is_connected_two_doubly_connected(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(b)) b.add_edge(Edge(a)) g = Graph([a, b]) assert g.is_connected()
def test_top_sort_cycle(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(b)) b.add_edge(Edge(a)) g = Graph([a, b]) assert_raises(ValueError, g.top_sort)
def TestDagShortestPathsModified(self): u = Vertex('u') v = Vertex('v') w = Vertex('w') z = Vertex('z') u.weight = 1 v.weight = 2 w.weight = 3 z.weight = 4 vertices = [u, v, w, z] edges = [(u, v), (v, w), (v, z)] G = Graph(vertices, edges) self.assertEquals(dag_shortest_paths_modified(G, u), [u, v, z])
def test_find_path_chain(): a = Vertex("A15") b = Vertex("A16") c = Vertex("A17") a.add_edge(Edge(b)) b.add_edge(Edge(c)) assert find_path(a, c) == [a, b, c]
def test_dfs_chain(): a = Vertex("A23") b = Vertex("A24") c = Vertex("A25") a.add_edge(Edge(b)) b.add_edge(Edge(c)) assert dfs(a, c)
def test_dfs_cycle(): a = Vertex("A30") b = Vertex("A31") c = Vertex("A32") a.add_edge(Edge(b)) b.add_edge(Edge(a)) b.add_edge(Edge(c)) assert dfs(a, c)
def test_find_path_cycle(): a = Vertex("A33") b = Vertex("A34") c = Vertex("A35") a.add_edge(Edge(b)) b.add_edge(Edge(a)) b.add_edge(Edge(c)) assert find_path(a, c) == [a, b, c]
class vertexTest(unittest.TestCase): def setUp(self): self.vex = Vertex('vex', ['vex0', 'vex1']) def tearDown(self): self.vex = None def test_eq(self): self.assertTrue(self.vex == 'vex') self.assertTrue(self.vex == Vertex('vex', ['vex1', 'vex2'], [10, 11])) def test_addAdj(self): for i in range(2): self.vex.addAdj('vex' + str(i+2)) self.assertTrue(str(self.vex) == "[vex, ['vex0', 'vex1', 'vex2', 'vex3'], [1, 1, 1, 1]]") self.assertTrue(len(self.vex) == 4) def test_iter(self): for ind, v in enumerate(self.vex): self.assertTrue(v[0] == 'vex' + str(ind)) self.assertTrue(v[1] == 1) def test_getitem(self): self.assertTrue(self.vex[1] == ('vex1', 1)) def test_value(self): self.assertTrue(self.vex.value == 'vex') self.vex.value = 'haha' self.assertTrue(self.vex.value == 'haha') def test_delAdj(self): self.vex.delAdj('vex0') self.assertTrue(str(self.vex) == "[vex, ['vex1'], [1]]") self.assertTrue(len(self.vex) == 1)
def test_make_test_vertex(): s = Vertex._make_test_vertex() a = Vertex(s) assert a.name == s
def test_size(): g = Graph([Vertex(Vertex._make_test_vertex())]) assert g.size() == len(g.vertices)
def test_add_edge_self_loop(): a = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(a)) assert len(a.edges) == 1 assert a in [e.vertex for e in a.edges]
def test_find_path_ignores_weights(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(b, 1)) c = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(c, 100)) b.add_edge(Edge(c, 1)) assert find_path(a, c) == [a, c]
def test_dfs_direct_connection(): a = Vertex("A19") b = Vertex("A20") a.add_edge(Edge(b)) assert dfs(a, b)
def test_vertex_repr(): s = Vertex._make_test_vertex() a = Vertex(s) assert a.__repr__() == "Vertex: {}".format(s)
def test_dfs_multiple_paths(): a = Vertex("A26") b = Vertex("A27") c = Vertex("A28") d = Vertex("A29") a.add_edge(Edge(b)) b.add_edge(Edge(c)) c.add_edge(Edge(d)) a.add_edge(Edge(d)) assert dfs(a, d)
def test_edge_weight(): a = Vertex(Vertex._make_test_vertex()) b = Edge(a, 10) assert b.weight == 10
def test_edge_invalid_weight(): a = Vertex(Vertex._make_test_vertex()) assert_raises(ValueError, Edge, a, "test")
def test_top_sort_two_single_vertices(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) g = Graph([a, b]) assert g.top_sort() in [[a, b], [b, a]]
def test_top_sort_two_linked_vertices(): a = Vertex(Vertex._make_test_vertex()) b = Vertex(Vertex._make_test_vertex()) a.add_edge(Edge(b)) g = Graph([a, b]) assert g.top_sort() == [a, b]