def test_get_radius_unequal_display_ratio(self):
        """
		Test that when getting the radius, the correct radii are used even if the display ratio is not equal.
		"""

        viz = drawable.Drawable(plt.figure(figsize=(10, 5)))

        graph = Graph(viz)
        point = viz.scatter(0, 0, s=1000)
        viz.set_xlim((-1, 1))
        viz.set_ylim((-1, 1))

        bb = util.get_bb(viz.figure, viz.axes, point)
        self.assertEqual(round(bb.width / 2, 10),
                         round(graph._get_radius(point, s=1000)[0], 10))
        self.assertEqual(round(bb.height / 2, 10),
                         round(graph._get_radius(point, s=1000)[1], 10))

        viz = drawable.Drawable(plt.figure(figsize=(5, 10)))

        graph = Graph(viz)
        point = viz.scatter(0, 0, s=1000)
        viz.set_xlim((-1, 1))
        viz.set_ylim((-1, 1))

        bb = util.get_bb(viz.figure, viz.axes, point)
        self.assertEqual(round(bb.width / 2, 10),
                         round(graph._get_radius(point, s=1000)[0], 10))
        self.assertEqual(round(bb.height / 2, 10),
                         round(graph._get_radius(point, s=1000)[1], 10))
Exemple #2
0
 def setUp(self):
     country1 = '{[(5,3),(7,3),(5,5)],[(5,5),(7,7),(9,5),(7,3)]}' \
                ',{[(1,1),(4,1),(4,3),(1,3)],[(2,3),(2,5),(5,5)' \
                ',(5,3)],[(4,0),(7,0),(7,3),(4,3)]},{[(9,5),' \
                '(11,7),(9,9),(7,7)]},{[(8,4),(8,0),(7,0)]},' \
                '{[(4, 8),(4,5),(7,7),(6,9)]},' \
                '{[(9, 7),(12,9),(14,6),(11,5)]}'
     country2 = '{[(3,1),(9,2),(3,-6),(3,-5),(1,-5),(1,-2)],' \
                '[(7,4),(7,6),(9,6),(9,4)]},' \
                '{[(1,-2),(3,1),(2,3),(-6,0),(-5,-2),(-3,-4)]},' \
                '{[(1,-2),(-3,-4),(-5,-7),(-3,-10),' \
                '(3,-6),(3,-5),(1,-5),(1,-2)]},' \
                '{[(-3,-10),(-8,-12),(-7,-17),(-2,-14)]},' \
                '{[(12,-5),(14,-9),(11,-12),(8,-8)]},' \
                '{[(11,-12),(8,-8),(4,-12),(6,-16)]}'
     three1 = Parser(country1).get_tree()
     three2 = Parser(country2).get_tree()
     self.vertices1 = list()
     for country in three1:
         self.vertices1.append(CountryVertex(country))
     self.graph1 = Graph(self.vertices1)
     self.vertices2 = list()
     for country in three2:
         self.vertices2.append(CountryVertex(country))
     self.graph2 = Graph(self.vertices2)
Exemple #3
0
def test_add_edge_missing_vertex():
    g = Graph()
    h = Graph()
    apple = g.add_vertex('apple')
    banana = h.add_vertex('banana')
    g.add_edge(apple, banana, 4)
    for v in g.get_vertices():
        if v.value == 'apple':
            assert v.adjacencies == []
def cfpq(edges, gram):
    n = 0
    for edge in edges:
        n = max(n, edge[0], edge[2])

    i = 0
    gram_edges = set()
    starts = []
    ends = []
    eps_nterms = set()
    heads = {}
    for prod in gram.productions:
        if len(prod.body) > 0:
            starts.append(i)
            for var in prod.body:
                gram_edges.add((i, var.value, i + 1))
                i += 1
            ends.append(i)
            i += 1
            heads[(starts[-1], ends[-1])] = prod.head
        else:
            eps_nterms.add(prod.head)

    gram_graph = Graph(
        i + 1,
        edges=gram_edges,
        start_states=starts,
        final_states=ends,
    )

    for nterm in eps_nterms:
        for i in range(n + 1):
            edges.append((i, nterm.value, i))

    graph = Graph(
        n + 1,
        edges=edges,
    )

    changed = True
    while changed:
        changed = False
        intersection = gram_graph.intersection(graph)
        squashed_bool_ms = utils.squash_bool_ms(intersection.bool_ms)
        closure = utils.transitive_closure(squashed_bool_ms, 1)
        for i, j, _ in closure:
            i_outer, i_inner = utils.num_to_coord(i, graph.size)
            j_outer, j_inner = utils.num_to_coord(j, graph.size)
            if i_outer in starts and j_outer in ends:
                nterm = heads[(i_outer, j_outer)]
                if nterm not in graph.bool_ms:
                    graph.bool_ms[nterm] = pgb.Matrix.sparse(
                        pgb.BOOL, n + 1, n + 1)
                old_nvals = graph.bool_ms[nterm].nvals
                graph.bool_ms[nterm][(i_inner, j_inner)] = 1
                changed = changed or graph.bool_ms[nterm].nvals > old_nvals
    return graph.bool_ms[gram.start_symbol.value]
Exemple #5
0
    def setUp(self) -> None:
        self.first_one_edge_graph = Graph()
        self.first_one_edge_graph.add_edge("1", "2")

        self.second_multi_edge_graph = Graph()
        self.second_multi_edge_graph.add_edge("1", "2")
        self.second_multi_edge_graph.add_edge("1", "3")
        self.second_multi_edge_graph.add_edge("3", "4")
        self.second_multi_edge_graph.add_edge("4", "5")
        self.second_multi_edge_graph.add_edge("2", "6")
        self.second_multi_edge_graph.add_edge("6", "4")
    def test_constructor_undirected(self):
        g = Graph(directed=False)
        g.add_vertices(1, 2, 3)
        g.connect(1, 2)
        g.connect(2, 3)

        h = Graph({1, 2, 3}, {(1, 2), (2, 1), (2, 3), (3, 2)}, directed=False)

        self.assertEqual(g.Vertices, h.Vertices)
        self.assertEqual(g.Edges, h.Edges)
        self.assertEqual(g._successors, h._successors)
        self.assertEqual(g._antecessors, h._antecessors)
Exemple #7
0
def main():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--countries',
                       '-c',
                       default='',
                       help='Enter the counties.'
                       'Countries are separated of figure brackets.'
                       'Regions in countries are separated '
                       'of square brackets.'
                       'Points in regions are separated '
                       'of circle brackets.'
                       'MENU is menu of actions.'
                       'SAVE is to save map in file.'
                       'LOAD is to load map from file.'
                       'EDIT MAP is to edit map in two modes.'
                       'First mode is online.'
                       'Second mode is dynamic.'
                       'TOOLS is for choose color of pen.')
    group.add_argument('--generate',
                       '-g',
                       type=int,
                       default=0,
                       help='Enter the wanted count of colors.'
                       'Count should be positive.'
                       'Default is zero.')

    args = parser.parse_args()
    graph = Graph(list())
    vertices = list()
    scale = 1
    if args.generate < 0:
        raise ValueError('Count of generate should be positive')
    if args.countries != '':
        tree = Parser(args.countries).get_tree()
        for country in tree:
            if isinstance(country, list):
                vertices.append(CountryVertex(country[1], country[0]))
            else:
                vertices.append(CountryVertex(country))
        graph = Graph(vertices)
    if args.generate != 0:
        generator = Generator(int(args.generate))
        graph = generator.generate_map()
        scale = 6
    app = QApplication(sys.argv)
    window = MapWindow(graph)
    if args.countries != '' or args.generate != 0:
        window.draw_map()
    window.show()
    sys.exit(app.exec_())
def test_can_add_edge():
    graph = Graph()
    babies = graph.add_vertex('babies')
    goats = graph.add_vertex('goats')
    graph.add_edge(babies, goats, 10)
    assert goats in graph._adjacency_list[babies]
    assert graph._adjacency_list[babies][goats] == 10
def test_get_vertices():
    graph = Graph()
    vertex1 = graph.add_vertex('meat')
    vertex2 = graph.add_vertex('cheese')
    graph.add_edge(vertex1, vertex2, 11)
    output = graph.get_vertices()
    assert output == ['meat', 'cheese']
def test_graph():
    graph = Graph()

    graph.add_vertex('A')
    graph.add_vertex('B')
    graph.add_vertex('C')
    graph.add_vertex('D')

    graph.add_edge('A', 'B', 1)
    graph.add_edge('B', 'C', 2)
    graph.add_edge('C', 'D', 3)
    graph.add_edge('A', 'C', 4)
    graph.add_edge('B', 'D', 5)
    graph.add_edge('A', 'D', 6)

    actual1 = graph.size()
    expected1 = 4

    actual2 = graph.get_vertices()
    expected2 = ['A', 'B', 'C', 'D']

    actual3 = graph.get_neighbors('A')
    expected3 = [['B', 1], ['C', 4], ['D', 6]]

    assert actual1 == expected1
    assert actual2 == expected2
    assert actual3 == expected3
Exemple #11
0
def test_size_fail():
    graph = Graph()
    graph.add_node('a')
    graph.add_node('b')
    expected = 3
    actual = graph.size()
    assert actual != expected
Exemple #12
0
 def setUp(self):
     f = open('assets/data/map_data.json', 'r')
     decoded = json.loads(f.read())
     self.g = Graph()
     self.g.build_nodes(decoded['metros'])
     self.g.build_edges(decoded['routes'])
     self.utils = GraphUtils()
 def test_add_edge(self):
     graph = Graph(directed=True)
     graph.add_vertex(data='a')
     graph.add_vertex(data=123)
     graph.add_edge(data1='a', data2=123, weight=3)
     self.assertEqual(graph.adjacency_list['a'].adjacent[123], 3)
     self.assertEqual(graph.adjacency_list[123].adjacent, {})
def test_breadth_first_1():
    graph = Graph()
    node_1 = graph.add_node('1')
    actual = graph.breadth_first(node_1)
    expected = [node_1]

    assert actual == expected
Exemple #15
0
    def test_add_edge_directed(self):
        graph = Graph(directed=True)
        graph.add_node(1)
        graph.add_node(2)
        graph.add_edge(1, 2)

        self.assertEqual(graph.nodes, {1: [(2, 0)], 2: []})
Exemple #16
0
    def test_check_cycles(self):
        G = Graph()
        a, b, c, d, e, f, g = Node('A'), Node('B'), Node('C'), Node('D'), Node(
            'E'), Node('F'), Node('G')

        N = [a, b, c, d, e, f, g]

        for node in N:
            G.add_node(node)

        E = [
            Edge(a, b),
            Edge(b, c),
            Edge(c, d),
            Edge(a, d),
            Edge(d, e),
            Edge(e, a),
            Edge(e, f),
            Edge(f, g),
            Edge(g, f),
        ]

        for edge in E:
            G.add_edge(edge)

        self.assertEqual(Graph.check_cycles(G, True),
                         [[g, f], [e, d, c, b, a]])
        self.assertEqual(Graph.check_cycles(G, False), [[g, f]])
Exemple #17
0
def test_get_nodes():
    graph = Graph()
    graph.add_node("banana")
    graph.add_node("apple")
    expected = 2
    actual = len(graph.get_nodes())
    assert actual == expected
Exemple #18
0
def test_size_two():
    graph = Graph()
    graph.add_node("spam")
    graph.add_node("bacon")
    expected = 2
    actual = graph.size()
    assert actual == expected
def test_depth_first():
    graph = Graph()
    A = graph.add_node('A')
    B = graph.add_node('B')
    C = graph.add_node('C')
    D = graph.add_node('D')
    E = graph.add_node('E')
    F = graph.add_node('F')
    G = graph.add_node('G')
    H = graph.add_node('H')
    graph.add_edge(A,B)
    graph.add_edge(A,D)
    graph.add_edge(D,E)
    graph.add_edge(D,H)
    graph.add_edge(D,F)
    graph.add_edge(B,C)
    graph.add_edge(C,G)
    output = graph.depth_first(A)
    assert output[0] == A
    assert output[1] == B
    assert output[2] == C
    assert output[3] == G
    assert output[4] == D
    assert output[5] == E
    assert output[6] == H
    assert output[7] == F
def test_depth_first_1():
    graph = Graph()
    node_1 = graph.add_node('')
    actual = graph.depth_first(node_1)
    expected = [node_1]

    assert actual == expected
def test_8():
    graph = Graph()

    actual = graph.get_nodes()
    expected = None

    assert actual == expected
Exemple #22
0
    def test_add_node(self):
        graph = Graph()
        graph.add_node(1)
        graph.add_node(2)

        self.assertEqual(graph.nodes, {1: [], 2: []})
        self.assertRaises(Exception, Graph.add_node, 1)
 def test_add_vertex(self):
     graph = Graph(directed=True)
     graph.add_vertex(data='a')
     self.assertEqual(set(list(graph.adjacency_list.keys())), set(['a']))
     graph.add_vertex(data=123)
     self.assertEqual(
         set(list(graph.adjacency_list.keys())), set([123, 'a']))
def test_get_neighbors():
    graph = Graph()
    babies = graph.add_vertex('babies')
    goats = graph.add_vertex('goats')
    graph.add_edge(babies, goats, 10)
    neighbors = graph.get_neighbors(babies)
    assert goats in neighbors
Exemple #25
0
def algo(graph, regexp, closure_algo=1):
    print("Intersecting graphs...")
    intersection_bool_ms = graph.intersect_bool_ms(regexp)
    print("Squashing...")
    intersection_squashed = utils.squash_bool_ms(intersection_bool_ms)
    print("Calculating closure...")
    res = utils.transitive_closure(intersection_squashed, closure_algo)
    print("Starts and finals...")
    start_states, final_states = graph.intersect_starts_and_finals(regexp)
    size = regexp.size

    reachable = []

    print("Calculating reachables...")
    for i, j, _ in res:
        i_outer, _ = utils.num_to_coord(i, size)
        j_outer, _ = utils.num_to_coord(j, size)
        if i in start_states and j in final_states:
            reachable.append((i_outer, j_outer))

    print("Creating intersection")
    edges, inter_size = utils.bool_ms_to_edges(intersection_bool_ms)
    intersection = Graph(
        inter_size,
        edges=edges,
        start_states=start_states,
        final_states=final_states,
    )
    return intersection, reachable
Exemple #26
0
    def teste_kruskal_mst_algorithm(self):
        '''Kruskal's algorithm uses Disjoint Set under the hook'''
        edges = [
            ('a', 'b', 4),
            ('a', 'h', 8),
            ('h', 'b', 11),
            ('h', 'i', 7),
            ('h', 'g', 1),
            ('i', 'g', 6),
            ('i', 'c', 2),
            ('b', 'c', 8),
            ('c', 'f', 4),
            ('g', 'f', 2),
            ('d', 'f', 14),
            ('c', 'd', 7),
            ('d', 'e', 9),
            ('e', 'f', 10),
        ]

        graph = Graph()
        for v, u, w in edges:
            graph.add_edge(v, u, weight=w)

        tree = kruskal(graph)

        nro_edges = gg_edges_number(tree)
        cost = gg_total_weight(tree)

        self.assertEqual(nro_edges, 8)
        self.assertEqual(cost, 37)
        self.assertFalse(has_cycle(graph))
Exemple #27
0
def test_size():
    graph = Graph()
    graph.add_node('a')
    graph.add_node('b')
    expected = 2
    actual = graph.size()
    assert actual == expected
Exemple #28
0
def test_single_node_edge():
    graph = Graph()
    a = graph.add_node('a')
    graph.add_edge(a, a)
    actual = graph.get_neighbors(a)
    expected = [{'Value': 'a', 'Weight': 1}]
    assert actual == expected
Exemple #29
0
def test_get_nodes():
    graph = Graph()
    a = graph.add_node('a')
    b = graph.add_node('b')
    actual = graph.get_nodes()
    expected = ['a', 'b']
    assert actual == expected
def test_breadth_first_traversal():
    graph = Graph()

    pandora = graph.add_vertex('Pandora')
    arendelle = graph.add_vertex('Arendelle')
    metroville = graph.add_vertex('Metroville')
    monstroplolis = graph.add_vertex('Monstroplolis')
    narnia = graph.add_vertex('Narnia')
    naboo = graph.add_vertex('Naboo')

    graph.add_edge(pandora, arendelle)
    graph.add_edge(arendelle, metroville)
    graph.add_edge(arendelle, monstroplolis)
    graph.add_edge(monstroplolis, metroville)
    graph.add_edge(metroville, narnia)
    graph.add_edge(metroville, naboo)
    graph.add_edge(monstroplolis, naboo)
    graph.add_edge(naboo, narnia)

    babies = graph.traverse(pandora)

    assert babies == [
        'Pandora', 'Arendelle', 'Metroville', 'Monstroplolis', 'Naboo',
        'Narnia'
    ]