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 main():
    # Two sources and single distination
    v_in = Vertex("x")  # one source
    v1_w = Vertex("w1", value=np.random.rand(10, 5))
    v1 = Affine(name="e1")(v1_w, v_in)
    v2_w = Vertex("w2", value=np.random.rand(5, 1))
    v2 = Affine(name="e2")(v2_w, v1)
    y = Vertex("y")  # second source
    v_out = SquareLoss(name="square-loss")(v2, 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(100, 10)
    v_in.forward(inputs)
    v1_w.forward()
    v2_w.forward()
    labels = np.random.rand(100, 1)
    y.forward(labels)
    print v2.value

    print "----- Compute Loss -----"
    v_out.backward(1)
    v2_w.grad
Example #4
0
def create_vertices():
    v1 = Vertex([12, 23], '')
    v1.words = 'Mike Pence'
    v1.set_range((10, 11))
    # v1.ori_val = copy.deepcopy(v1.val)
    v1.r_map = list(range(10, 12))

    v2 = Vertex([18, 50, 79, 28], '')
    v2.words = 'First Lady Melane Trump'
    v2.set_range((18, 21))
    # v2.ori_val = copy.deepcopy(v2.val)
    v2.r_map = list(range(18, 22))

    v3 = Vertex([1, 2, 3, 4], '')
    v3.words = 'He bought her flowers'
    v3.set_range((50, 53))
    # v3.ori_val = copy.deepcopy(v3.val)
    v3.r_map = list(range(50, 54))

    v4 = Vertex([101, 95, 81, 27, 58, 66, 71], '')
    v4.words = 'but this was seen by donald trump'
    v4.set_range((201, 207))
    # v4.ori_val = copy.deepcopy(v3.val)
    v4.r_map = list(range(201, 208))

    return v1, v2, v3, v4
 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_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 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
Example #8
0
    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"])
Example #10
0
 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)
Example #11
0
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()
Example #12
0
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
Example #13
0
    def test_hash(self):
        key = 15
        value = 20
        u = Vertex(key, value)
        v = Vertex(key, value)

        self.assertEqual(hash(u), hash(v))
Example #14
0
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
Example #15
0
    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()})
Example #16
0
    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 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
Example #18
0
    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]
Example #20
0
 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'}
Example #21
0
    def test_get_id(self):
        ramon = Vertex('Ramon Geronimo')
        jessie = Vertex('Jessie Pichardo')
        joel = Vertex('Joel Pichardo')

        assert ramon.get_id() == 'Ramon Geronimo'
        assert jessie.get_id() == 'Jessie Pichardo'
        assert joel.get_id() == 'Joel Pichardo'
Example #22
0
    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])
Example #23
0
 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)
Example #24
0
    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_add_edge(self):
     graph = Graph()
     a = Vertex('A')
     b = Vertex('B')
     graph.add_vertex(a)
     graph.add_vertex(b)
     graph.add_edge(a, b)
     a.add_neighbor(b)
     assert b in a.get_neighbors() 
Example #26
0
    def test_get_neighbors(self):
        ramon = Vertex('Ramon Geronimo')
        jessie = Vertex('Jessie Pichardo')
        joel = Vertex('Joel Pichardo')

        ramon.add_neighbor(jessie)
        ramon.add_neighbor(joel)

        self.assertCountEqual(ramon.get_neighbors(), [jessie, joel])
        self.assertCountEqual(jessie.get_neighbors(), [])
Example #27
0
 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
Example #28
0
 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)
Example #29
0
    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))
Example #30
0
    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)