def test_get_links(self):
        """
        a - b - c
        -----
        A - A - A
              /
        B - B
          \
            C
        """
        v_aA = Vertex(domain='a')
        v_aB = Vertex(domain='a')
        v_bA = Vertex(domain='b')
        v_bB = Vertex(domain='b')
        v_bC = Vertex(domain='b')
        v_cA = Vertex(domain='c')

        e_aA_bA = Edge(v_aA, v_bA)
        e_aB_bB = Edge(v_aB, v_bB)
        e_aB_bC = Edge(v_aB, v_bC)
        e_bA_cA = Edge(v_bA, v_cA)
        e_bB_cA = Edge(v_bB, v_cA)

        g = Graph([v_aA, v_aB, v_bA, v_bB, v_bC, v_cA],
                  [e_aA_bA, e_aB_bB, e_bA_cA, e_bB_cA, e_aB_bC])
        g.prepare()
        self.assertItemsEqual(g.get_link(('b', 'c')),
                              [e_bA_cA, e_bB_cA])
        self.assertItemsEqual(g.get_link(('a', 'b')),
                              [e_aA_bA, e_aB_bB, e_aB_bC])
Пример #2
0
def functionalRobustness(transposeAdj, stack, adj):
    visited = [False] * len(adj)
    largestSCC = []

    while len(stack) > 0:
        i = stack.pop()
        if visited[i] == False:
            tempSCC = dfsSCCRecurse(transposeAdj, i, visited)
            if len(tempSCC) > len(largestSCC):
                largestSCC = tempSCC

    # Create new graph with just the largest SCC
    newAdj = []
    newEdges = 0
    for i in largestSCC:
        tmpArr = []
        for j in largestSCC:
            if i == j:
                tmpArr.append(0)
            else:
                tmpArr.append(adj[i][j])
                newEdges += adj[i][j]
        newAdj.append(tmpArr)

    newG = Graph(len(newAdj), newEdges, True, False)
    newG.adj = newAdj
    return efficiency(newG)
 def test_preset_neighborhood(self):
     v_a = Vertex(domain='a')
     v_b = Vertex(domain='b')
     v_c = Vertex(domain='c')
     e = Edge(v_a, v_b)
     g = Graph([v_a, v_b, v_c], e, [('a', 'b')])
     self.assertItemsEqual(g.get_neighboring_domains(), [('a', 'b')])
Пример #4
0
    def __init__(self, default, argv):
        Graph.__init__(self, default, argv)

        self.debug("alert", "__init__")

        self.calc_data = {}
        self.market_data = {}
 def test_get_domains(self):
     v_aA = Vertex('A', None, 'a')
     v_aB = Vertex('B', None, 'a')
     v_bA = Vertex('A', None, 'b')
     v_bB = Vertex('B', None, 'b')
     v_bC = Vertex('C', None, 'b')
     g = Graph([v_aA, v_aB, v_bA, v_bB, v_bC], Edge(v_aA, v_bB))
     self.assertItemsEqual(g.get_domains(), ['a', 'b'])
Пример #6
0
def line(n):
    g = Graph(n, n - 1, True, False)
    for i in range(g.n):
        if i != g.n - 1:
            g.adj[i][i+1] = 1
            g.adj[i+1][i] = 1

    return g
    def new(cls, bot, update, args):

        param1 = args[0]
        # param2 = args[1]
        # user = User(chat=update.message.chat_id, screen_name='{}'.format(text),
        #             friends='', tweet_id='')

        api = cls.auth()

        user_info1 = api.GetUser(screen_name=param1)
        # user_info2 = api.GetUser(screen_name=param2)
        friends1 = api.GetFriends(screen_name=param1)
        # friends2 = api.GetFriends(screen_name=param2)
        # print([s.text for s in statuses])

        graph = Graph()
        graph2 = Graph()
        # db.session.add(user)
        # db.session.commit()

        user_ids = []
        for s in islice(friends1, 5):
            current_friend_id = s.AsDict().get('id')
            print(current_friend_id)

            graph.add_vertex(current_friend_id)
            graph.add_edge({user_info1.AsDict().get('id'), current_friend_id})

            # friends_of_current_friend = api.GetFriends(screen_name=s.AsDict().get('screen_name'))
            # for s in friends_of_current_friend:
            #     graph.add_edge({
            #         current_friend_id,
            #         s.AsDict().get('id')
            #     })
            # user_id = s.AsDict().get('id')
            # user_ids.append(user_id)

        # for s in friends2:
        #     graph.add_vertex(s.AsDict().get('id'))
        #     graph2.add_edge({
        #             user_info2.AsDict().get('id'),
        #             s.AsDict().get('id')
        #         })
        # user_id = s.AsDict().get('id')
        # user_ids.append(user_id)

        # for user_id in user_ids:
        #     current = api.GetUser(user_id=user_id)

        print(graph.edges())
        print(
            '\n ---------------------------------------------------------------------------------------- \n'
        )
        print(graph2.edges())

        bot.send_message(chat_id=update.message.chat_id,
                         text="abigo stoaki:" + str())
Пример #8
0
 def __init__(self, default, argv):
     Standard.__init__(self, default, argv)
     self.report = Report(default, argv)
     self.scraping = Scraping(default, argv)
     self.market = Market(default, argv)
     self.graph = Graph(default, argv)
     self.alert = Alert(default, argv)
     if self.conf['load_file']: self.market.data = self.report.get()
     if self.conf['print_file']: self.report.display_file_list()
 def test_get_domain_tuple(self):
     v_aA = Vertex('A', None, (0,1))
     v_aB = Vertex('B', None, (0,1))
     v_bA = Vertex('A', None, (0,2))
     v_cA = Vertex('A', None, (1,1))
     v_cB = Vertex('B', None, (1,1))
     g = Graph([v_aA, v_aB, v_bA, v_cA, v_cB], Edge(v_aA, v_bA))
     self.assertItemsEqual(g.get_domain((0,1)), [v_aA, v_aB])
     self.assertItemsEqual(g.get_domain((0,2)), [v_bA])
     self.assertItemsEqual(g.get_domain((1,1)), [v_cA, v_cB])
Пример #10
0
def generate(n, e, pool, needConnected, weighted, directed):
    """Generates graph given number of nodes, edges, pool, connectedness, weights, and directed or not """
    graphs = []

    for i in range(pool):
        g = Graph(n, e, needConnected,
                  weighted)  # calls classes/graph.py to initialize a graph
        randomizeEdge(g, directed, needConnected)
        while needConnected and not isConnected(g.adj):
            g.resetEdges()
            randomizeEdge(g, directed, needConnected)
        graphs.append(g)

    return graphs
Пример #11
0
def get_graph_letter(letter):
    global count
    graph = Graph()

    node1 = Node(count, 'initial')
    count += 1
    node2 = Node(count, 'final')
    count += 1

    node1.add_edge(Edge(node1, node2, letter))

    graph.add_node(node1)
    graph.add_node(node2)

    return get_initial_final(graph)
Пример #12
0
def getGraphLetter(letter):
    global count
    graph = Graph()

    node1 = Node(count, 'initial')
    count += 1
    node2 = Node(count, 'final')
    count += 1

    node1.addEdge(Edge(node1, node2, letter))

    graph.addNode(node1)
    graph.addNode(node2)

    return getInitialFinal(graph)
def searchCycle(matrix):
    size = len(matrix)
    graph = Graph(size)
    graph.buildFromMatrix(matrix)
    min_graph_degree = graph.findMinGraphDegree()

    if min_graph_degree < 2:
        print("Za niski minimalny stopień grafu")
        return
    else:
        vertexes = []
        cycle = DFS(matrix, 0, vertexes, min_graph_degree)

    print("Cykl: ", cycle)
    return
Пример #14
0
def calculate(posfixa):
    x = Graph()
    s = Stack(len(posfixa))

    for c in posfixa:
        if ('A' <= c <= 'Z') or ('a' <= c <= 'z'):
            x = get_graph_letter(c)
            s.push(x)
        else:
            if c == '+':
                x = s.pop()
                s.push(get_plus(x))
            elif c == '.':
                y = s.pop()
                x = s.pop()
                s.push(get_point(x, y))
            elif c == '*':
                x = s.pop()
                s.push(get_cline(x))
            elif c == '|':
                y = s.pop()
                x = s.pop()
                s.push(get_or(x, y))

    return x
Пример #15
0
def calculate(posfixa):
    x = Graph()
    s = Stack(len(posfixa))

    for c in posfixa:
        if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')):
            x = getGraphLetter(c)
            s.Push(x)
        else:
            if (c == '+'):
                x = s.Pop()
                s.Push(getPlus(x))
            elif (c == '.'):
                y = s.Pop()
                x = s.Pop()
                s.Push(getPoint(x, y))
            elif (c == '*'):
                x = s.Pop()
                s.Push(getCline(x))
            elif (c == '|'):
                y = s.Pop()
                x = s.Pop()
                s.Push(getOr(x, y))

    return x
def findJordanCenter(matrix):

    if not isTree(matrix):
        print("Nie jest to drzewo")
        return

    tree_size = len(matrix)

    if tree_size < 3:
        vertexes = [i for i in range(tree_size)]
        return vertexes

    tree = Graph(tree_size)
    tree.buildFromMatrix(matrix)
    vertexes = [i for i in range(tree_size)]

    vertexes_left_size = len(vertexes)
    # max length of the center is 2
    while vertexes_left_size > 2:
        for vertex in list(vertexes):
            degree = tree.findVertexDegree(vertex)
            print("Wierzchołek: ", vertex, "  Stopien: ", degree)
            if degree == 1:
                print("Liśc: ", vertex)
                tree.removeEdgesAssociatedToVertex(vertex)
                # removing leaves
                vertexes.remove(vertex)
        vertexes_left_size = len(vertexes)

    print("Centrum Jordana: ", vertexes)
    return vertexes
Пример #17
0
def crossover(g1, g2, directed):
    if g1.n != g2.n:  # The dimensions of the graphs don't match
        raise AttributeError('Dimensions of graphs do not match')

    # Randomly pick which graph is the base to be added upon
    base = g2
    addendum = g1
    if (randint(0, 1) == 1):
        base = g1
        addendum = g2

    child = Graph(base.n, base.e, base.connected, base.weighted)
    childEdges = 0
    rect = generateRectangle(base.n)

    if directed:  # Directed graph
        for r in range(base.n):
            for c in range(base.n):
                # If r, c indices not in the subrectangle
                if r < rect['top'] or r > rect['bottom'] or c < rect[
                        'left'] or c > rect['right']:
                    child.adj[r][c] = base.adj[r][c]
                else:
                    child.adj[r][c] = addendum.adj[r][c]

                if child.adj[r][c] == 1:
                    childEdges += 1
        child.e = childEdges  # Properly update the edge count
    else:  # Undirected graph
        # Generate a rectangle that contains elements in the upper right triangle
        while (rect['bottom'] < rect['right'] and rect['top'] < rect['left']):
            rect = generateRectangle(base.n)

        for r in range(base.n):
            for c in range(base.n):
                if c < r:
                    child.adj[r][c] = child.adj[c][r]
                elif c > r:
                    # If r, c indices not in the subrectangle
                    if r < rect['top'] or r > rect['bottom'] or c < rect[
                            'left'] or c > rect['right']:
                        child.adj[r][c] = base.adj[r][c]
                    else:
                        child.adj[r][c] = addendum.adj[r][c]

                    if child.adj[r][c] == 1:
                        childEdges += 1
        child.e = childEdges  # Properly update the edge count

    return child
Пример #18
0
    def test_shortest_path(self):
        graph = Graph()
        verticies = ["1", "2", "3", "4", "5"]
        edges = [
            ("1", "2"),
            ("1", "4"),
            ("2", "3"),
            ("2", "4"),
            ("2", "5"),
            ("3", "5"),
        ]

        # add verticies to path
        for vertex in verticies:
            graph.add_vertex(vertex)

        # add edges to graph
        for tuple_edge in edges:
            graph.add_edge(tuple_edge[0], tuple_edge[1])

        from_vertex = "1"
        to_vertex = "5"

        output = graph.breadth_first_search(from_vertex, to_vertex)
        expected_output = {'2': '1', '4': '1', '3': '2', '5': '2'}

        # output is used to calculate the shortest path
        self.assertEqual(output, expected_output)
Пример #19
0
def perfect(n):
    half = int(n/2)
    if n % 2 == 0:
        half -= 1

    g = Graph(n, n, True, False)
    for i in range(g.n):
        # print(i)
        if i + 1 < half:
            g.adj[i][i+1] = 1
            g.adj[i+1][i] = 1
            g.adj[i][i + half] = 1
            g.adj[i + half][i] = 1
        elif i == half:
            g.adj[i][0] = 1
            g.adj[0][i] = 1
            g.adj[i][i + half] = 1
            g.adj[i + half][i] = 1

    return g
Пример #20
0
def knightGraph(boardSize):
    """Create a graph


    Arguments:
        boardSize {int} -- table size

    Returns:
        Graph -- graph created from provided board size
    """
    ktGraph = Graph()

    for row in range(boardSize):
        for col in range(boardSize):
            nodeId = posToNodeId(row, col, boardSize)
            moves = legalMoves(row, col, boardSize)
            for move in moves:
                posibleNodeId = posToNodeId(move[0], move[1], boardSize)
                ktGraph.addEdge(nodeId, posibleNodeId)

    return ktGraph
Пример #21
0
def build_graph_from_file(path):
    file = open(path, "r")
    lines = [line.rstrip('\n') for line in file]
    file.close()

    graph_size = int(lines[0])
    edges_size = int(lines[1])
    edges = lines[2:]

    if len(edges) != edges_size:
        print("Podano niewłaściwą liczbę krawędzi - %d" % len(edges))
        return

    graph = Graph(graph_size)

    for edge in edges:
        edge = edge.split()
        if len(edge) != 2:
            print("\n\nNie utworzono grafu")
            print("Nieprawidłowa linijka: ", edge)
            return
        vertex_from = int(edge[0]) - 1
        vertex_to = int(edge[1]) - 1
        graph.addEdge(vertex_from, vertex_to)

    graph.toString()
    return graph
    def test_prepare(self):
        start = Vertex('start')
        finish = Vertex('finish')

        a = Vertex('a')
        b = Vertex('b')
        c = Vertex('c')

        start_a = Edge(start, a, SemiringMinPlusElement(5))
        a_b = Edge(a, b, SemiringMinPlusElement(1))
        a_c = Edge(a, c, SemiringMinPlusElement(5))
        b_c = Edge(b, c, SemiringMinPlusElement(3))
        c_finish = Edge(c, finish, SemiringMinPlusElement(9))

        g = Graph([start, finish, a, b, c],
                  [start_a, a_b, b_c, a_c, c_finish])

        g.prepare(SemiringMinPlusElement)
        self.assertItemsEqual(a.get_outputs(), [a_b, a_c])
        self.assertItemsEqual(b.get_inputs(), [a_b])
        self.assertItemsEqual(b.get_outputs(), [b_c])
        self.assertItemsEqual(c.get_inputs(), [b_c, a_c])
 def test_deep_copy(self):
     v_a = Vertex()
     v_b = Vertex()
     e = Edge(v_a, v_b)
     g = Graph([v_a, v_b], [e])
     g_copy = deepcopy(g)
     self.assertIsNot(g, g_copy)
     e = g.get_edges().pop()
     e_copy = g_copy.E.pop()
     self.assertIsNot(e, e_copy)
     self.assertEqual(e.get_value(), e_copy.get_value())
     self.assertIsNot(e.get_vertices(), e_copy.get_vertices())
     self.assertEqual([v.get_value() for v in e.get_vertices()],
                      [v.get_value() for v in e_copy.get_vertices()])
     [v.set_value(1) for v in e.get_vertices()]
     [v.set_value(2) for v in e_copy.get_vertices()]
     self.assertNotEqual([v.get_value() for v in e.get_vertices()],
                      [v.get_value() for v in e_copy.get_vertices()])
     e.set_value(1)
     e_copy.set_value(2)
     self.assertEqual(e.get_value(), 1)
     self.assertEqual(e_copy.get_value(), 2)
     self.assertEqual(len(g.get_vertices().intersection(g_copy.V)), 0)
Пример #24
0
def buildGraphFromFile(path):
    file = open(path, "r")
    lines = [line.rstrip('\n') for line in file]
    file.close()

    graph_size = int(lines[0])
    edges_size = int(lines[1])
    edges = lines[2:]

    if len(edges) != edges_size:
        print("Podano niewłaściwą liczbę krawędzi - %d" % len(edges))
        return

    graph = Graph(graph_size)

    for edge in edges:
        edge = edge.split()
        vertex_from = int(edge[0])
        vertex_to = int(edge[1])
        graph.addEdge(vertex_from, vertex_to)

    print(graph.getAdjacencyMatrix())
    return graph
Пример #25
0
 def test_add_vertex(self):
     vertex_a = "A"
     graph = Graph()
     graph.add_vertex(vertex_a)
     self.assertEqual(len(graph.vert_dict), 1)
     self.assertEqual(graph.num_vertices, 1)
     vertex_b = "B"
     graph.add_vertex(vertex_b)
     self.assertEqual(len(graph.vert_dict), 2)
     self.assertEqual(graph.num_vertices, 2)
Пример #26
0
def circle(n):
    g = Graph(n, n, True, False)
    for i in range(g.n):
        if i == g.n - 1:
            g.adj[i][0] = 1
            g.adj[0][i] = 1
        else:
            g.adj[i][i+1] = 1
            g.adj[i+1][i] = 1

    return g
Пример #27
0
def perfect(n):
    half = int(n / 2)
    # if n % 2 == 0:
    #     half -= 1

    g = Graph(n, n, True, False)
    for i in range(half):
        g.adj[i][i + half] = 1
        g.adj[i + half][i] = 1

    g.adj[0][14] = 1
    g.adj[14][0] = 1
    for i in range(half):
        if i + 1 < half:
            g.adj[i][i + 1] = 1
            g.adj[i + 1][i] = 1

            # g.adj[i][i + half] = 1
            # g.adj[i + half][i] = 1

    return g
    def test_delete_edge(self):
        """
        a - b
        -----
        B
          \
            C
        """
        v_aB = Vertex(domain='a')
        v_bC = Vertex(domain='b')

        e_aB_bC = Edge(v_aB, v_bC)

        g = Graph([v_aB, v_bC],
                  [e_aB_bC])
        g.prepare()
        g.delete_edge(e_aB_bC)
        self.assertItemsEqual(g.get_edges(), [])
        self.assertItemsEqual(g.get_vertices(), [])
        self.assertTrue(g.is_neighborhood_corrupted())
        """
Пример #29
0
def graph_from_file(filepath):
	""" 
		Opens a text file and returns:
			graph: graph instance
			verticies: list 
			edges: list of tuples
	"""

	with open(filepath) as f:
		lines = f.read().splitlines()
		g_type, verticies, edges = lines[0], lines[1].split(','), lines[2:]
	
		if g_type == "G":
			graph = Graph()
			return graph, verticies, edges
		elif g_type == "D":
			graph = Digraph()
			return graph, verticies, edges
		else:
			raise ValueError("Graph type is not specified!")
Пример #30
0
    def test_add_edge(self):
        vertex_a = "A"
        vertex_b = "B"

        graph = Graph()
        graph.add_vertex(vertex_a)
        graph.add_vertex(vertex_b)
        graph.add_edge(vertex_a, vertex_b)
        self.assertEqual(graph.num_edges, 1)

        vertex_a_obj = graph.vert_dict[vertex_a]
        vertex_b_obj = graph.vert_dict[vertex_b]

        # check if vertex_a & vertex_b are neighbours of each other.
        self.assertIn(vertex_a_obj, vertex_b_obj.neighbours)
        self.assertIn(vertex_b_obj, vertex_a_obj.neighbours)
    def test_delete_corrupted(self):
        """
            a    b
             ___
            / / \
        1  A,B   C
           |/    |
        2  D --- E
        """
        A = Vertex(domain=(1,'a'))
        B = Vertex(domain=(1,'a'))
        D = Vertex(domain=(2,'a'))
        C = Vertex(domain=(1,'b'))
        E = Vertex(domain=(2,'b'))

        AD = Edge(A, D)
        AC = Edge(A, C)
        BC = Edge(B, C)
        BD = Edge(B, D)
        DE = Edge(D, E)
        CE = Edge(C, E)

        g = Graph([A, B, C, D, E], [AD, AC, BC, BD, DE, CE])
        g.prepare()
        self.assertItemsEqual(g.get_vertices(), [A, B, C, D, E])
        self.assertItemsEqual(g.get_edges(), [AD, AC, BC, BD, DE, CE])

        g.delete_edge(BD, True)
        g.delete_corrupted()

        self.assertItemsEqual(g.get_vertices(), [A, C, D, E])
        self.assertItemsEqual(g.get_edges(), [AD, AC, DE, CE])

        self.assertFalse(g.is_neighborhood_corrupted())
Пример #32
0
 def test_get_vertex(self):
     vertex_a = "A"
     graph = Graph()
     graph.add_vertex(vertex_a)
     output_obj = graph.get_vertex(vertex_a)
     self.assertIsInstance(output_obj, Vertex)
Пример #33
0
def pent(n): # Pentahub
    g = Graph(n, n, True, False)
    first = int(n/5)
    second = int(2 * n/5)
    third = int(3 * n/5)
    fourth = int(4 * n/5)
    fifth = n

    for i in range(g.n):
        if i != 0 and i < first:
            g.adj[i][0] = 1
            g.adj[0][i] = 1
        elif i != first and i < second:
            g.adj[i][first] = 1
            g.adj[first][i] = 1
        elif i != second and i < third:
            g.adj[i][second] = 1
            g.adj[second][i] = 1
        elif i != third and i < fourth:
            g.adj[i][third] = 1
            g.adj[third][i] = 1
        elif i != fourth and i < fifth:
            g.adj[i][fourth] = 1
            g.adj[fourth][i] = 1

        g.adj[0][first] = 1
        g.adj[first][0] = 1

        g.adj[first][second] = 1
        g.adj[second][first] = 1

        g.adj[second][third] = 1
        g.adj[third][second] = 1

        g.adj[third][fourth] = 1
        g.adj[fourth][third] = 1

        g.adj[fourth][0] = 1
        g.adj[0][fourth] = 1

    return g
Пример #34
0
def tri(n): # TriHub
    g = Graph(n, n, True, False)
    first = int(n/3)
    second = int(2 * n/3)
    third = n

    for i in range(g.n):
        if i != 0 and i < first:
            g.adj[i][0] = 1
            g.adj[0][i] = 1
        elif i != first and i < second:
            g.adj[i][first] = 1
            g.adj[first][i] = 1
        elif i != second and i < third:
            g.adj[i][second] = 1
            g.adj[second][i] = 1

        g.adj[0][first] = 1
        g.adj[first][0] = 1

        g.adj[first][second] = 1
        g.adj[second][first] = 1

        g.adj[second][0] = 1
        g.adj[0][second] = 1

    return g
Пример #35
0
def star(n):
    g = Graph(n, n-1, True, False)
    for i in range(1, g.n):
        g.adj[i][0] = 1
        g.adj[0][i] = 1
    return g
Пример #36
0
class App(Standard):
    def __init__(self, default, argv):
        Standard.__init__(self, default, argv)
        self.report = Report(default, argv)
        self.scraping = Scraping(default, argv)
        self.market = Market(default, argv)
        self.graph = Graph(default, argv)
        self.alert = Alert(default, argv)
        if self.conf['load_file']: self.market.data = self.report.get()
        if self.conf['print_file']: self.report.display_file_list()

    def collector(self):
        self.debug("app","collector")

        try:
            while True:
                self.conf['time_done_collector'] = time.time() + self.conf['loop_timer_collector']

                scraping_data = self.scraping.get(self.scraping.get_html(), self.conf['row_limit'])
                self.report.save(scraping_data)
                market_data = self.market.data_mapping(scraping_data)

                self.timer(self.conf['time_done_collector'])
        except KeyboardInterrupt:
            print('Manual break by user')

    def display(self):
        self.debug("app","display")

        if self.conf['print_graph']: self.graph.init()

        try:
            while True:
                self.conf['time_done_display'] = time.time() + self.conf['loop_timer_display']

                if self.conf['print_scraping']: self.scraping.display()
                if self.conf['print_report']: self.report.display()
                if self.conf['print_market']: self.market.display()
                if self.conf['print_graph']: self.graph.trace(self.market.data)
                # if self.conf.get('print_graph'): self.graph.display_file(self.report.file, self.scraping.data)

                self.timer(self.conf['time_done_display'])
        except KeyboardInterrupt:
            print('Manually stopped')

    def alerting(self):
        self.debug("app","alerting")

        if self.conf['print_alert_graph']: self.alert.init()

        try:
            while True:
                self.conf['time_done_alert'] = time.time() + self.conf['loop_timer_alert']

                self.alert.calc(self.market.data)
                if self.conf['print_alert']: self.alert.display_calc()
                if self.conf['print_alert_graph']: self.alert.trace(self.alert.market_data)

                self.timer(self.conf['time_done_alert'])
        except KeyboardInterrupt:
            print('Manually stopped')
    def test_delete_vertex(self):
        """
        a - b - c
        -----
        A - A - A
              /
        B - B
          \
            C
        """
        v_aA = Vertex(domain='a')
        v_aB = Vertex(domain='a')
        v_bA = Vertex(domain='b')
        v_bB = Vertex(domain='b')
        v_bC = Vertex(domain='b')
        v_cA = Vertex(domain='c')

        e_aA_bA = Edge(v_aA, v_bA)
        e_aB_bB = Edge(v_aB, v_bB)
        e_aB_bC = Edge(v_aB, v_bC)
        e_bA_cA = Edge(v_bA, v_cA)
        e_bB_cA = Edge(v_bB, v_cA)

        g = Graph([v_aA, v_aB, v_bA, v_bB, v_bC, v_cA],
                  [e_aA_bA, e_aB_bB, e_bA_cA, e_bB_cA, e_aB_bC])
        g.prepare()

        self.assertItemsEqual(g.get_edges(), [e_aA_bA, e_aB_bB, e_aB_bC,
                                              e_bA_cA, e_bB_cA])
        self.assertItemsEqual(g.get_vertices(), [v_aA, v_aB, v_bA,
                                                 v_bB, v_bC, v_cA])
        self.assertFalse(g.is_neighborhood_corrupted())

        """
        a - b - c
        -----
        X   x   A
              /
        B - B
          \
            C
        """
        g.delete_vertex(v_aA)
        self.assertItemsEqual(g.get_edges(), [e_aB_bB, e_aB_bC, e_bB_cA])
        self.assertItemsEqual(g.get_vertices(), [v_aB, v_bB, v_bC, v_cA])
        self.assertFalse(g.is_neighborhood_corrupted())
        self.assertItemsEqual(g.get_domain('b'), [v_bB, v_bC])

        """
        a - b - c
        -----
                x

        B   X
          \
            C
        """
        g.delete_vertex(v_bB)
        self.assertItemsEqual(g.get_edges(), [e_aB_bC])
        self.assertItemsEqual(g.get_vertices(), [v_aB, v_bC])
        self.assertTrue(g.is_neighborhood_corrupted())
        self.assertItemsEqual(g.get_domain('a'), [v_aB])
        self.assertItemsEqual(g.get_domain('b'), [v_bC])

        """
        a - b - c
        -----
        x

            X
        """
        g.delete_vertex(v_bC)
        self.assertEqual(g.get_edges(), set())
        self.assertEqual(g.get_vertices(), set())
        self.assertTrue(g.is_neighborhood_corrupted())

        g.restore()
        self.assertItemsEqual(g.get_edges(), [e_aA_bA, e_aB_bB, e_aB_bC,
                                              e_bA_cA, e_bB_cA])
        self.assertItemsEqual(g.get_vertices(), [v_aA, v_aB, v_bA,
                                                 v_bB, v_bC, v_cA])
        self.assertFalse(g.is_neighborhood_corrupted())
Пример #38
0
    def test_eulerian(self):
        """
            Creates an undirected graph thatdoes contain a Eulerian
            cycle.  
        """

        vertex_a = "A"
        vertex_b = "B"
        vertex_c = "C"
        vertex_d = "D"
        vertex_e = "E"

        graph = Graph()
        graph.add_vertex(vertex_a)
        graph.add_vertex(vertex_b)
        graph.add_vertex(vertex_c)
        graph.add_vertex(vertex_d)
        graph.add_vertex(vertex_e)
        graph.add_edge(vertex_a, vertex_b)
        graph.add_edge(vertex_a, vertex_e)
        graph.add_edge(vertex_b, vertex_c)
        graph.add_edge(vertex_c, vertex_d)
        graph.add_edge(vertex_d, vertex_e)

        self.assertEqual(graph.is_eulerian(), True)
Пример #39
0
__author__ = 'FAMILY'

import time
import pickle

from classes.graph import Graph
from functions.generate import generate
from functions.clean import clean

e=pickle.load(open("matrix_list_fixed.p", "rb"))
for i in clean(e):
    print(i)
maxtime = 0
avg_time = 0
count = 0
g = Graph(10, 10, [4, 4, 0], "squared")
for i in generate("squared", 4, 2, 2, 2, 2, 2):
    count += 1
    start = time.clock()
    g.draw_layers(*i)
    end = time.clock()
    if (end - start > maxtime):
        maxtime = end - start

    avg_time = (avg_time * count + (end - start)) / (count + 1)
    if (count % 10000 == 0):
        print("count: ", count)
        print("time: ", time.clock())
        print("found: ", g.found)
        print("average: ", avg_time)
        print("max: ", maxtime)
Пример #40
0
 def test_init(self):
     graph = Graph()
     self.assertEqual(len(graph.vert_dict), 0)
     self.assertEqual(graph.num_vertices, 0)
     self.assertEqual(graph.num_edges, 0)