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())
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
Exemple #3
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
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
Exemple #5
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)
Exemple #6
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
Exemple #7
0
def buildGraphMatrix(history):
    graphSize = len(history[0])
    historySize = len(history)
    graph = Graph(graphSize)
    matrix = graph.getAdjacencyMatrix()
    degrees_indexes = graph.getAllDegreesWithIndexes()

    for i in range(1, historySize):
        connections_amount = history[i][0]
        print("Ilość połączeń do dodania: ", connections_amount)
        print("Historia: ", history[i])
        graph.addVertex()
        for j in range(1, connections_amount + 1):
            searched_vertex_degree = history[i][j] - 1
            print("Szukany stopień: ", searched_vertex_degree)

            # get index of a first vertex of searched degree from a degrees_indexes dictionary
            vertex_index = list(degrees_indexes.keys())[list(degrees_indexes.values()).index(searched_vertex_degree)]
            last_vertex_index = graph.getLastVertexIndex()

            # add an edge between found vertex of a given degree and the last vertex
            graph.addEdge(vertex_index, last_vertex_index)
            degrees_indexes = graph.getAllDegreesWithIndexes()

    print("\nMacierz sąsiedztwa:")
    for row in matrix:
        for value in row:
            print('{0:5}'.format(value), end=' ')
        print()
    return graph.getAdjacencyMatrix()
Exemple #8
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
Exemple #9
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)
Exemple #10
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)
Exemple #11
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
Exemple #12
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()
Exemple #13
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)
Exemple #14
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
Exemple #15
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
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
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
Exemple #18
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)
Exemple #19
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)
Exemple #20
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)
Exemple #21
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
Exemple #22
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!")
Exemple #23
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
Exemple #24
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
Exemple #25
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
Exemple #26
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
Exemple #27
0
def get_copy_graph(graph):
    copy = Graph()

    for n in graph.nodes:
        node = Node(n.name, n.category)
        copy.add_node(node)
Exemple #28
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
Exemple #29
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)
Exemple #30
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)