Exemplo n.º 1
0
def draw(graph: Graph, components):
    """Draw the graph showing edge weight

    :param graph: graph object to draw
    :param components: tuple of sets, where each set represents a set of nodes
    """

    graph_nx = nx.Graph()
    graph_nx.add_weighted_edges_from(graph.weighted_edges)

    labels = nx.get_edge_attributes(graph_nx, 'weight')
    pos = nx.spring_layout(graph_nx)
    community_map = get_community_map(components)

    nx.draw_networkx(graph_nx,
                     pos=pos,
                     with_labels=False,
                     node_size=200,
                     node_shape="o",
                     node_color=list(community_map.values()))

    plt.get_cmap()
    plt.axis('off')
    plt.title(graph.name)
    plt.show()
Exemplo n.º 2
0
    def plot_graph(self, name, score):

        #Import matplotlib, a library used to produce graphic in python.
        import matplotlib.pyplot as plt
        from networkx import nx

        plt.figure(figsize=(7, 7))  # Adjust the window size
        plt.margins(.2, .2)  # Adjust margins
        #We determine the node position: https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.layout.spring_layout.html
        position = nx.spring_layout(self.graph)
        nx.draw_networkx(self.graph, with_labels=True, pos=position)
        plt.axis('off')  # Removing axis
        #Weights on edges : solution found on stackoverflow
        #https://stackoverflow.com/questions/28372127/add-edge-weights-to-plot-output-in-networkx

        labels = nx.get_edge_attributes(self.graph, 'weight')
        nx.draw_networkx_edge_labels(self.graph,
                                     pos=position,
                                     edge_labels=labels)
        plt.title(
            "fasta alignment graph according to a minimum alignment score of "
            + str(score))
        plt.savefig(
            name +
            ".png")  # Produce a png file with the graph annotated by default
        plt.show()

        nx.write_gexf(
            self.graph, name +
            ".gexf")  # Produce a gexf file that can be annotated with gephi.

        return None
Exemplo n.º 3
0
 def plot_dag(self, ax=None):
     """
     Plots DAG with networkx tools
     Args:
         ax: Matplotlib axis
     """
     if ax is None:
         fig, ax = plt.subplots()
     labels_dict = {i: self.var_names[i] for i in range(len(self.DAG))}
     nx.draw_networkx(self.DAG,
                      pos=nx.kamada_kawai_layout(self.DAG),
                      ax=ax,
                      labels=labels_dict,
                      node_color='white',
                      arrowsize=15,
                      edgecolors='b',
                      node_size=800)
Exemplo n.º 4
0
# G.add_edge(0, 3, weight=4)
for e in G.edges:
    a = e[0]
    b = e[1]

    w = randint(1, 1)
    G.add_edge(int(e[0]), int(e[1]), weight=w)
# print (a)

# Drawing the graph
node_pos = nx.spring_layout(G)

edge_weight = nx.get_edge_attributes(G, 'weight')

# Draw the nodes
nx.draw_networkx(G, node_pos, node_color='grey', node_size=100)

# Draw the edges
nx.draw_networkx_edges(G, node_pos, edge_color='black')

# Draw the edge labels
nx.draw_networkx_edge_labels(G,
                             node_pos,
                             edge_color='red',
                             edge_labels=edge_weight)

# write to a file
# nx.write_gml(G, "test_gml")
# json_graph.node_link_data(G)
# nx.write_edgelist(G,"test.edgeList")
Exemplo n.º 5
0
from networkx import nx
import matplotlib.pyplot as plt
import sys
import math
import operator
import random as ran
import numpy as np
import pandas as pd

fh = open("C:\Users\Kmutt_Wan\PycharmProjects\Book1.txt", "r")
#print file.read(fh)
G = nx.read_adjlist(fh)
nx.draw_networkx(G)
plt.savefig("AA.png")
plt.show()

#-------------------------------------------------------------------------------------------


#-------------------------------------------------------------------------------------------
#Degr = G.degree()
#Mdegree = sorted([d for n, d in G.degree()], reverse=True)
#Leanglumdub([won G.degree moveto d],krubdan)
#MDegree = max(Mdegree)#value maksud
#print (MDegree)
#print (Degr)
#-------------------------------------------------------------------------------------------
def dfs(graph, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
Exemplo n.º 6
0
        session_handle = ne.connect(username, password, session_config)

        if session_handle:
            topology = TopologyClass(ne, TopologyClass.TopologyType.CDP)
            graph = topology.get_graph()

            yield {key: graph.get_edge_list(Edge.EdgeType.UNDIRECTED)}

        else:
            print "Unable to connect to network element {} .".format(values["ip"])
            continue

        if ne.is_connected():
            try:
                ne.disconnect()
            except:
                print "Unable to disconnect from network element {}".format(values["ip"])


if __name__ == "__main__":

    Graph = nx.MultiGraph()

    for edges in get_data(nodes):
        edgelist = edges.values()[0]
        for edge in edgelist:
            Graph.add_node(edge.head_node.name)
            Graph.add_edge(edge.head_node.name, edge.tail_node.name)
    nx.draw_networkx(Graph)
    plt.savefig("graph.png")
def main():
    df = pd.read_csv('metrosp_stations.csv')
    df = df.drop(columns=['Unnamed: 0'])
    df.neigh = df.neigh.str[1:-1].str.split(',').tolist()
    df = df.neigh.apply(pd.Series) \
    .merge(df, left_index = True, right_index = True) \
    .drop(["neigh"], axis = 1) \
    .melt(id_vars = ['name','station','lat', 'lon', 'line'], value_name = "onlyNeigh") \
    .drop("variable", axis = 1) \
    .dropna()
    df.to_json('metroSP.json')

    with open('metroSPNotEdited.json') as json_file:
        dataNotEdited = json.load(json_file)

    with open('metroSP.json') as json_file:
        data = json.load(json_file)

    listaDeAdjacencia = {}
    listaEstacoes = []

    # Montando lista de adjacência
    for (key, estacao) in data['station'].items():
        if not listaDeAdjacencia.get(estacao):
            listaDeAdjacencia[estacao] = []
            listaEstacoes.append(estacao)

        listaDeAdjacencia[estacao].append(data['onlyNeigh'][key])

    # Salvando lista de adjacência
    with open('listaAdjacencia.json', 'w') as json_file:
        json.dump(listaDeAdjacencia, json_file)

    while True:
        os.system("clear")
        opcao = menuPrincipal()
        if opcao == '1':
            origem = input("Estação de Origem: ")
            destino = input("Estação de Destino: ")
            menor_caminho = BFS(listaDeAdjacencia, origem, destino)
            print('Esse é o menor caminho para chegar no seu destino:')
            for item in menor_caminho:
                print(
                    recupera_nome(dataNotEdited, item) + ' - ' +
                    recupera_linha(dataNotEdited, item))

            G = nx.Graph()
            labels = {}
            mapaDeCores = []

            for estacao, arestas in listaDeAdjacencia.items():

                corNo = recupera_linha(dataNotEdited, estacao)
                labels[estacao] = recupera_nome(dataNotEdited, estacao)
                G.add_node(estacao)
                # corNo = nx.get_node_attributes(G,'color')
                # corNo = recupera_linha(dataNotEdited, estacao)
                if corNo == '[lilas]':
                    mapaDeCores.append('#8B008B')
                elif corNo == '[verde]':
                    mapaDeCores.append('#006400')
                elif corNo == '[azul]':
                    mapaDeCores.append('#000080')
                elif corNo == '[vermelha]':
                    mapaDeCores.append('#FF0000')
                elif corNo == '[amarela]':
                    mapaDeCores.append('#FF8C00')
                elif corNo == '[prata]':
                    mapaDeCores.append('#1C1C1C')
                else:
                    mapaDeCores.append('#8B4513')

                for aresta in arestas:
                    G.add_edge(estacao, aresta)

            listaNos = G.nodes()
            listaNos = sorted((set(listaNos)))
            posicoes = get_posicoes()

            fig1 = plt.figure('Grafo Principal')
            nx.draw(G,
                    pos=posicoes,
                    nodelist=listaNos,
                    with_labels=True,
                    labels=labels,
                    node_color=mapaDeCores,
                    font_size=6,
                    font_color='white',
                    edge_color='#A0522D')
            fig1.set_facecolor("#00000F")

            fig2 = plt.figure('Subgrafo')
            fig2.set_facecolor("#00000F")
            ax = plt.gca()
            ax.set_facecolor('#00000F')
            subgraph = G.subgraph(menor_caminho)
            nx.draw_networkx(subgraph,
                             pos=posicoes,
                             font_size=8,
                             edge_color='#00CED1',
                             node_color='#00CED1',
                             font_color='white')

            plt.show()
        else:
            os.system("clear")
            print('Encerrando Programa!')
            break
Exemplo n.º 8
0
            pass
    return coops / len(neighbours)


def gompertz(f):
    #parameters (from paper)
    h = 0.34
    t = -150
    g = -10
    gomp = h * np.exp(t * np.exp(g * f))
    return gomp


def utilCoop(fc, R):
    E = ext(fc)
    uc = ec * ((cobbdoug(E, R) / E) - w)
    return uc


def utilDefec(fc, R):
    E = ext(fc)
    ud = ed * ((cobbdoug(E, R) / E) - w) - gompertz(fc) * (ed - ec) / ed
    return ud


nx.draw_networkx(G,
                 pos=None,
                 node_color=colours,
                 with_labels=True,
                 node_size=100)
plt.show()
if __name__ == "__main__":
    DataFile = ReadFileExcel('C:\Users\Kmutt_Wan\PycharmProjects\Sample1.xls')
    G = DataFileToGraph(DataFile)
    #GraphMe = nx.draw(G, edge_color='b', with_labels=True, edge_label=True)
    cycles = [[node] + path for node in G for path in dfs(G, node, node)]
    Result_dfs = dfs(G,node,node)
    print('All cycles =',len(cycles))
    list3 = []
    for node in cycles:
        if len(node) - 1 == 3:
            list3.append(node)
    tuple3 = tuple(list3)  #
    set3 = {frozenset(x) for x in tuple3}
    print('Sub cycles 3 node =',len(set3),set3)
    Graph_cycles = nx.draw_networkx(set3)
    plt.show()

#def SubcycleGraph(Sub_Cycle):
#    for n in Sub_Cycle.node:
#        count = len(n) - 1
#        for i in range(count):
#            Sub_Cycle.add_edge(n[i], n[i + 1])
#           if i == n - 1:
#               Sub_Cycle.add_edge(n[i + 1], n[0])