示例#1
0
def run_test(n, m, seed):
    G = nx.gnm_random_graph(n, m, seed=seed)
    matrix = nx.to_numpy_matrix(G)
    GS = []
    for v in G.nodes:
        GS.append(set(G.adj[v].keys()))
    T = set(G.nodes())
    start_time = timer()
    ind_set, comb = colorize_numpy(GS, T)
    numpy_time = timer() - start_time
    start_time = timer()
    J = alg_try.Colorize(matrix)
    print(J)
    alg_time = timer() - start_time
    print("numpy time: %.4f,\t alg time: %.4f" % (numpy_time, alg_time))
    print("alr res: {} \nnumpy res: {}".format(len(J), sum(comb)))
    colors = [
        1,
    ] * n
    for idx, ind in enumerate(ind_set):
        if comb[idx] == 1:
            print(ind_set[idx])
            for i in ind_set[idx]:
                colors[i] = idx
    nx.draw(G,
            node_color=colors,
            pos=nx.drawing.layout.kamada_kawai_layout(G),
            with_labels=True,
            node_size=1000,
            cmap='Paired')
    #nx.draw(G, node_color=colors, pos=nx.drawing.layout.spiral_layout(G), with_labels=True, node_size=1000, cmap='Paired')
    #nx.draw(G, node_color=colors, pos=nx.drawing.layout.spring_layout(G, seed=3), with_labels=True, node_size=1000, cmap='Paired')
    plt.show()
示例#2
0
 def plot(self, filename=None, with_capacity=False, dpi=300):
     """Plot network topology."""
     pos = nx.spring_layout(self.graph)
     labels = nx.get_edge_attributes(self.graph, "capacity")
     nx.draw(self.graph, pos, with_labels=True)
     if with_capacity:
         nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=labels)
     if filename:
         plt.savefig(filename, dpi=dpi)
示例#3
0
文件: plot.py 项目: eze210/tda1
	def plot(self):
		drawableGraph = nx.DiGraph()
		drawableGraph.add_nodes_from(self.graph.vertices)
		for v in self.graph.vertices:
			adjs = self.graph.edges[v]
			for a in adjs:
				drawableGraph.add_edge(v, a)

		plt.subplot(111)
		nx.draw(drawableGraph, with_labels=True, node_color='blue', node_size=50, width=1)
		plt.show()
示例#4
0
def showGraph(G, W=None):
    n = len(G)
    E = [(i, j) for i in range(n) for j in G[i]]
    nxG = nx.Graph(E)
    pos = nx.spring_layout(nxG)
    nx.draw(nxG, pos, with_labels=True, node_color='yellow', node_size=500)
    if W is not None:
        labels = [W[i][k] for i in range(n) for k in range(len(G[i]))]
        for (i, j), w in zip(E, labels):
            nxG[i][j]['weight'] = w
        labels = nx.get_edge_attributes(nxG, 'weight')
        nx.draw_networkx_edge_labels(nxG, pos, edge_labels=labels)
    plt.show()
    return
示例#5
0
def visualize(environment):
    G = nx.from_numpy_matrix(environment.state_space)
    print(G.edges(data=True))

    color_map = []
    for node in G.nodes():

        if node in environment.fire_locations:
            color_map.append('red')
        elif node in environment.terminal_states:
            color_map.append('green')
        else:
            color_map.append('cyan')

    nx.draw(G,
            with_labels=True,
            node_color=color_map,
            node_size=[100 for v in G.nodes()],
            layout=nx.spring_layout(G, scale=1000))
    plt.savefig(os.path.join(dir_path, "environment_graph.pdf"))
    plt.savefig(os.path.join(dir_path, "environment_graph.png"))
def get_concept_network(search_regex_string: str,
                        min_count: int = 1,
                        highlight_regex_string: str = "",
                        nearest_neighbor_count: int = 0) -> str:
    """Extracts a network of words from vector data in an AI model."""
    graph: Graph = Graph()
    w2v: Word2Vec = Word2Vec.load(Config.PANEGYRICI_LATINI_MODEL_PATH)
    search_regex: Pattern[str] = re.compile(search_regex_string)
    keys: List[str] = [x for x in w2v.wv.vocab if search_regex.match(x)]
    if not nearest_neighbor_count:
        # adjust the graph size depending on the given parameters to prevent bloating
        nearest_neighbor_count: int = max(
            int(100 * (min_count**2) / (1 + len(keys))), 2)
    keys = [
        x for x in keys
        if all(y.isalpha() for y in x) and w2v.wv.vocab[x].count >= min_count
    ]
    edge_color: Tuple[float, float, float] = (0.6, 0.6, 0.6)
    add_edges(keys, w2v, nearest_neighbor_count, min_count, graph)
    pos: dict = nx.spring_layout(graph, k=0.7, iterations=100)
    pyplot.clf()
    pyplot.subplot()
    nx.draw(graph, pos, node_size=25, with_labels=True, alpha=1)
    colors: List[Tuple[float, float, float]] = []
    highlight_regex: Pattern[str] = re.compile(highlight_regex_string)
    for edge in graph.edges:
        if highlight_regex_string and any(
                highlight_regex.match(x)
                for x in edge) and any(search_regex.match(x) for x in edge):
            colors.append((1, 0, 0))
        else:
            colors.append(edge_color)
    nx.draw_networkx_edges(graph, pos, alpha=1, edge_color=colors)
    pyplot.savefig(fname=Config.NETWORK_GRAPH_TMP_PATH,
                   format="svg",
                   bbox_inches="tight")
    xml_string: str = open(Config.NETWORK_GRAPH_TMP_PATH).read()
    os.remove(Config.NETWORK_GRAPH_TMP_PATH)
    svg_string: str = re.findall(r"<svg[\s\S]*?svg>", xml_string)[0]
    return svg_string
示例#7
0
def draw_small_graph(graph):
    """Draw the graph showing edge weight
    :param graph: graph object to draw
    """

    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)
    nx.draw_networkx_edge_labels(graph_nx, pos=pos, edge_labels=labels)

    nx.draw(graph_nx,
            pos=pos,
            with_labels=True,
            node_size=10,
            node_color="skyblue",
            node_shape="o",
            alpha=0.5,
            linewidths=30)

    plt.title(graph.name)
    plt.show()
def Plot_network(G, colors):
    ## Plot graph
    fig, ax = plt.subplots(figsize = (10,5))
    
    nx.draw(G, node_size=50, node_color=colors, width = 0.2, pos=nx.spring_layout(G, k=0.25, iterations=50), alpha = 0.8)
    plt.show()
    
    degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
    degreeCount = collections.Counter(degree_sequence)
    deg, cnt = zip(*degreeCount.items())
    
    fig, ax = plt.subplots(figsize = (10,5))
    plt.bar(deg, cnt, width=0.80, color='b')
    
    plt.title("Degree Histogram")
    plt.ylabel("Count")
    plt.xlabel("Degree")
    deg_2 = []
    for ind, d in enumerate(deg):
        if ind % 2== 0:
            deg_2.append(d)    
    ax.set_xticks([d for d in deg_2])
    ax.set_xticklabels(deg_2, rotation = 90)
示例#9
0
    for p in spl:
        pathlengths.append(spl[p])

print('')
print("average shortest path length %s" %
      (sum(pathlengths) / len(pathlengths)))

# histogram of path lengths
dist = {}
for p in pathlengths:
    if p in dist:
        dist[p] += 1
    else:
        dist[p] = 1

print('')
print("length #paths")
verts = dist.keys()
for d in sorted(verts):
    print('%s %d' % (d, dist[d]))

print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

nx.draw(G, with_labels=True)
plt.show()
示例#10
0
    connections[i] = {value for value in temp}
    for k in temp:
        temp2 = []
        for p in range(len(data["Address Sender"])):
            if data["Address Sender"][p] == k:
                temp2.append(data["Address Receiver"][p])
                num.append([
                    k, data["Address Receiver"][p],
                    data["Transaction_value"][p]
                ])
        connections[k] = {value for value in temp2}

print("Building Succeeds!")

G = nx.Graph(connections)
pos = nx.spring_layout(G)

colormap = []
for node in G:
    for k in num:
        if k[1] == i:
            if k[2] < 1:
                colormap.append('blue')
            elif k[2] > 20:
                colormap.append('red')
            else:
                colormap.append('green')

nx.draw(G, node_color=colormap, with_labels=True)
plt.show()
示例#11
0
#    print("Source : %s / Destination : %s" % (u, v))

print(list(G.nodes()))

#for u, v, action in G.edges(data='action'):
#    if action is not None:
#        print("(%s) [%s] (%s)" % (u, action, v))

color_map = []

for n in G.nodes():
    if G.nodes[n]['parti'] == 'author':
        color_map.append('red')
    else:
        color_map.append('blue')

options = {
    'node_color': color_map,
    'node_size': 50,
    'line_color': 'grey',
    'linewidths': 0,
    'width': 0.1,
}

pos = nx.spring_layout(G)
nx.draw(G, pos, font_size=16, with_labels=False, **options)
for p in pos:  # raise text positions
    pos[p][1] += 0.07
nx.draw_networkx_labels(G, pos)
plt.show()
print ("### Gerando Topologia Genérica com %s switches e  %s links ###" %
       (args.s, args.l))
switches = args.s  # é a quantidade de switches
# é quantidade de enlaces ou o dobro de switches
links = args.l if args.l else 2*switches
output = args.output  # arquivo de saida
view = args.view  # indica se quer visualizar a rede

# manipulando o grafo
G = nx.gnm_random_graph(switches, links)  # grapho aleatório

edges = []  # lista de arestas

for line in nx.generate_adjlist(G):  # para cada linha das adjascentes
    nodes = line.split()  # quebra por espaços
    first = int(nodes[0])  # pega o primeiro
    for node in nodes[1:]:  # para cada node restante
        edges.append([first, int(node)])  # adiciona na lista o parte de node

# manipulando arquivo
with open(output, "w") as f:  # abre o arquivo para escrita
    dump(edges, f)  # escreve o arquivo

if view:
    nx.draw(G, with_labels=True, font_weight='bold')
    plt.show()

__author__ = 'Andrei Bastos'
__email__ = '*****@*****.**'
    for j in range(no_of_cities):
        if i != j and distances[i][j] == 0:
            distances[i][j] = randint(1, 20)
            distances[j][i] = distances[i][j]

# plot graph

graph = networkx.from_numpy_matrix(numpy.array(distances))
print(distances)
pos = nx.shell_layout(graph)
nx.draw_networkx_nodes(graph, pos, node_size=80)
nx.draw_networkx_labels(graph, pos, font_size=13, font_family='sans-serif')
labels = nx.get_edge_attributes(graph, 'weight')
nx.draw_networkx_edge_labels(graph, pos, edge_labels=labels, label_pos=0.61)

nx.draw(graph, pos)
plt.axis('off')
plt.show()
print()

# assign ants to cities

for i in range(no_of_ants):
    ants[i].visitedCitiesSet.append(ants[i].currentCity)

# start process

alphaBeta = [[0.5, 1.2], [2, 0.4], [1, 4], [1, 1]]

d = 0
while d < 4:
示例#14
0
#    
#
#
#
#    clustering = nx.clustering(goarn_network)
#
#    spamwriter.writerow('L')
#    for each in clustering.items():
#        print 'Clustering Coefficient per Node: ', each[0], each[1]
#        spamwriter.writerow([each[0], each[1]])
#    csvfile.close()



import matplotlib.pyplot as plt 
nx.draw(goarn_network)
plt.show()

#
#def most_important(G):
# """ returns a copy of G with
#     the most important nodes
#     according to the pagerank """ 
# ranking = nx.betweenness_centrality(G).items()
# print ranking
# r = [x[1] for x in ranking]
# m = sum(r)/len(r) # mean centrality
# t = m*3 # threshold, we keep only the nodes with 3 times the mean
# Gt = G.copy()
# for k, v in ranking:
#  if v < t:
示例#15
0
    for p in spl:
        pathlengths.append(spl[p])

print()
print(f"average shortest path length {sum(pathlengths) / len(pathlengths)}")

# histogram of path lengths
dist = {}
for p in pathlengths:
    if p in dist:
        dist[p] += 1
    else:
        dist[p] = 1

print()
print("length #paths")
verts = dist.keys()
for d in sorted(verts):
    print(f"{d} {dist[d]}")

print(f"radius: {nx.radius(G)}")
print(f"diameter: {nx.diameter(G)}")
print(f"eccentricity: {nx.eccentricity(G)}")
print(f"center: {nx.center(G)}")
print(f"periphery: {nx.periphery(G)}")
print(f"density: {nx.density(G)}")

pos = nx.spring_layout(G, seed=3068)  # Seed layout for reproducibility
nx.draw(G, pos=pos, with_labels=True)
plt.show()
示例#16
0
noeuds_poids = []
noeuds_noms = []

for n, v in d.items() :
    noeuds_poids.append(v)
    noeuds_noms.append(n)

articles_noms = []
auteurs_noms = []
#pattern = 'tr/'
#for n in noeuds_noms :
#        result = re.match(pattern, n)
#        articles_noms.append(n)
#        if result :
#        else :
#            auteurs_noms.append(n)

#Afficher la liste des publications de chaque auteur
for n in auteurs_noms :
    print("Voisins de {} : {}".format(n, list(G.neighbors(n))))



pos = nx.spring_layout(G)
#nx.draw(G, pos, font_size=16, with_labels=False,**options)
nx.draw(G, pos, nodelist=noeuds_noms, node_size=[v * 100 for v in noeuds_poids], **options)
for p in pos:  # raise text positions
    pos[p][1] += 0.07
nx.draw_networkx_labels(G, pos)
plt.show()
示例#17
0
show()

print(pca.explained_variance_ratio_)
print(1 - sum(pca.explained_variance_ratio_))
data_inv = pca.inverse_transform(pcad)
print(abs(sum(sum(data - data_inv))))

for i in range(1, 5):
    pca = PCA(n_components=i)
    pca.fit(data)
    print(sum(pca.explained_variance_ratio_) * 100, '%')

# Network Mining
G = nx.read_gml('lesmiserables.gml')
pos = nx.spring_layout(G)
nx.draw(G, pos, node_size=0, edge_color='b', alpha=.2)
nx.draw_networkx_labels(G, pos, edge_color='b', alpha=.2, font_size=10)
show()
'''
Gt = G.copy()

dn = nx.degree(Gt)

for n in Gt.nodes():
    if dn[n] <= 10:
        Gt.remove_node(n)

pos = nx.spring_layout(Gt)
nx.draw(Gt, pos, node_size=0, edge_color='b', alpha=.2)
nx.draw_networkx_labels(Gt, pos, edge_color='b', alpha=.2, font_size=10)
show()
示例#18
0
#codigo em python 3

#pacote para fazer graficos
import matplotlib.pyplot as plt
#pacote para caracterizacao de redes
from networkx import nx

M = 100  # numero de vertices
p = 0.01 # probabilidade de conexao em um par aleatorio

#geracao da rede de Erdos Renyi, tambem chamada de binomial
grafo = nx.binomial_graph(M, p)

#escreve na tela informacoes gerais do grafo
print(nx.info(grafo))

#cria uma visualizacao do grafo
nx.draw(grafo,nodesize = 0.5)
#salva a visualizacao em um arquivo
plt.savefig('fig_erdos_renyi_v1a.png',dpi = 300, bbox_inches='tight') 

#calcula o numero de componentes
nc = nx.number_connected_components(grafo)
print(nc) #escreve na tela

#calcula o tamanho (numero de vertices) da maior componente
largest_cc = max(nx.connected_components(grafo), key=len)
sc = len(largest_cc)
print(sc) #escreve na tela
                   rota,
                   weight=recupera_distancia(searchData, aeroporto, rota))

# print("Nodes in G: ", G.nodes(data=True))
# print("Edges in G: ", G.edges(data=True))
# print('Tamanho do grafo', G.number_of_nodes())

prim, custo, pesos = executa_prim(G, 'ATL')
print("Árvore Geradora Mínima pelo algoritmo de Prim")
print(prim)
print("\n\n")
print("Custo Total da MST: ")
print(custo)
print("\n\n")
print("Custo individual das arestas da MST: ")
print(pesos)

posicoesNo = {}
x = 0
y = 0
for no in G.nodes():
    y += 1
    if y > 20:
        y = 1
        x += 4
    posicoesNo.update({no: (x, y)})

fig1 = plt.figure('Árvore Geradora Miníma')
nx.draw(G, labels=labels, pos=posicoesNo, edgelist=prim)
plt.show()
示例#20
0
    spl = dict(nx.single_source_shortest_path_length(G, v))
    print('{} {} '.format(v, spl))
    for p in spl:
        pathlengths.append(spl[p])

print('')
print("average shortest path length %s" % (sum(pathlengths) / len(pathlengths)))

# histogram of path lengths
dist = {}
for p in pathlengths:
    if p in dist:
        dist[p] += 1
    else:
        dist[p] = 1

print('')
print("length #paths")
verts = dist.keys()
for d in sorted(verts):
    print('%s %d' % (d, dist[d]))

print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

nx.draw(G, with_labels=False)
plt.show()
示例#21
0
            tfc[tfc < th * mul] = 0
            tfc[tfc >= th * mul] = 1
            pfc = np.copy(predFC[i])
            pfc[pfc < th] = 0
            pfc[pfc >= th] = 1

            plt.figure(figsize=(10, 3))
            graph = nx.grid_2d_graph(1, 3)  # 4x4 grid

            # plt.figure(figsize=(w, h))
            plt.subplot(131)
            g = nx.from_numpy_array(allSC[i])
            nx.draw(g,
                    pos,
                    node_color='g',
                    node_size=100,
                    font_size=10,
                    edge_color='k',
                    width=0.25,
                    with_labels=True)
            # plt.title('Source graph: '+str(i))
            plt.title('Source graph')
            # plt.show()

            # plt.figure(figsize=(w, h))
            plt.subplot(132)
            g = nx.from_numpy_array(tfc)
            nx.draw(g,
                    pos,
                    node_color='g',
                    node_size=100,
                    font_size=10,
示例#22
0
and report some properties.

This graph is sometimes called the Erdős-Rényi graph
but is different from G{n,p} or binomial_graph which is also
sometimes called the Erdős-Rényi graph.
"""

import matplotlib.pyplot as plt
from networkx import nx

n = 10  # 10 nodes
m = 20  # 20 edges
seed = 20160  # seed random number generators for reproducibility

# Use seed for reproducibility
G = nx.gnm_random_graph(n, m, seed=seed)

# some properties
print("node degree clustering")
for v in nx.nodes(G):
    print(f"{v} {nx.degree(G, v)} {nx.clustering(G, v)}")

print()
print("the adjacency list")
for line in nx.generate_adjlist(G):
    print(line)

pos = nx.spring_layout(G, seed=seed)  # Seed for reproducible layout
nx.draw(G, pos=pos)
plt.show()
示例#23
0
#    Copyright (C) 2004-2018 by
#    Aric Hagberg <*****@*****.**>
#    Dan Schult <*****@*****.**>
#    Pieter Swart <*****@*****.**>
#    All rights reserved.
#    BSD license.

import matplotlib.pyplot as plt
from networkx import nx

z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
print(nx.is_graphical(z))

print("Configuration model")
G = nx.configuration_model(z)  # configuration model
degree_sequence = [d for n, d in G.degree()]  # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist = {}
for d in degree_sequence:
    if d in hist:
        hist[d] += 1
    else:
        hist[d] = 1
print("degree #nodes")
for d in hist:
    print('%d %d' % (d, hist[d]))

nx.draw(G)
plt.show()
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
示例#25
0
import matplotlib.pyplot as plt

reseau_social = nx.Graph()

reseau_social.add_node('laurent')
reseau_social.add_node('pierre')
reseau_social.add_node('lucie')
reseau_social.add_node('sophie')
reseau_social.add_node('martin')
reseau_social.add_node('jacques')

reseau_social.add_edge('laurent', 'pierre')
reseau_social.add_edge('lucie', 'pierre')
#reseau_social.add_edge('laurent','lucie')
reseau_social.add_edge('sophie', 'lucie')
reseau_social.add_edge('sophie', 'pierre')
reseau_social.add_edge('sophie', 'martin')
reseau_social.add_edge('martin', 'laurent')
reseau_social.add_edge('jacques', 'martin')
reseau_social.add_edge('jacques', 'laurent')

nx.draw(reseau_social, with_labels=True)
plt.draw()
plt.show()

print("nombre de sommets=", reseau_social.number_of_nodes())
print("nombre de arêtes=", reseau_social.number_of_edges())
print("Diamètre=", diameter(reseau_social))
print("Rayon=", radius(reseau_social))
print("Centre=", center(reseau_social))
示例#26
0
print("length #paths")
verts = dist.keys()
for d in sorted(verts):
    print('%s %d' % (d, dist[d]))

print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

nx.draw(
    G,
    with_labels=True,
    cmap=cm.Blues,
    node_color=np.arange(len(G)) / len(G),
    node_size=400,
    alpha=0.7,
)
plt.show()
"""Draw the graph G using Matplotlib.

Draw the graph with Matplotlib with options for node positions,
labeling, titles, and many other drawing features.
See draw() for simple drawing without labels or axes.

Parameters
----------
G : graph
   A networkx graph
            #print ' The last edge is ' + str(edge)
            print "Move from " + str(edge[0][0]) + " to " + str(edge[0][1])
            copy.remove_edge(edge[0][0],edge[0][1])
            circuit.add_edge(edge[0][0],edge[0][1])
            return circuit
    return circuit        
        
    #remove the corresponding edge from graph
    #check if the remaining graph is connected. If not, move to another neighbour
    #repeat previous 3 steps until the copy of graph becomes empty     
    
final = eulerian(G)
if type(final)==str:
    print final
else:
    nx.draw(final)    
 
    
    
    
    
    
    
    
    
    
    
    
    
    
    
示例#28
0
# %matplotlib inline
from networkx import nx
"""setup"""

G = nx.lollipop_graph(4, 6)

pathlengths = []

for v in G.nodes():
    spl = dict(nx.single_source_shortest_path_length(G, v))
    for p in spl:
        pathlengths.append(spl[p])
"""draw"""

nx.draw(G, with_labels=True)
"""fancy draw"""

nx.draw(
    G,
    with_labels=True,
    node_size=1500,
    node_color="skyblue",
    node_shape="s",
    alpha=0.5,
    linewidths=40
)
示例#29
0
    print('{} {} '.format(v, spl))
    for p in spl:
        pathlengths.append(spl[p])

print('')
print("average shortest path length %s" % (sum(pathlengths) / len(pathlengths)))

# histogram of path lengths
dist = {}
for p in pathlengths:
    if p in dist:
        dist[p] += 1
    else:
        dist[p] = 1

print('')
print("length #paths")
verts = dist.keys()
for d in sorted(verts):
    print('%s %d' % (d, dist[d]))

print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

nx.draw(G, with_labels=True)
plt.show()
示例#30
0
        # if(diff<30):
        # if pearson[i]>0.73:
        if pearson[i] > 0.70:
            # if True:
            print(i, pearson[i])

            plt.figure(figsize=(16, 6))
            graph = nx.grid_2d_graph(1, 3)  # 4x4 grid

            # plt.figure(figsize=(w, h))
            plt.subplot(131, aspect=1.0)
            g = nx.from_numpy_array(sc)
            nx.draw(g,
                    pos,
                    node_color='g',
                    node_size=100,
                    font_size=10,
                    edge_color='k',
                    width=1,
                    with_labels=True)
            # plt.title('Source graph: '+str(i))
            plt.title('Subject {}:  SC'.format(i))
            # plt.show()

            # plt.figure(figsize=(w, h))
            plt.subplot(132, aspect=1.0)
            g = nx.from_numpy_array(tfc)
            edges, weights = zip(*nx.get_edge_attributes(g, 'weight').items())
            # weights[weights>=0] = 1
            # weights[weights<=0] = -1
            nx.draw(g,
                    pos,
示例#31
0
from networkx import nx

z = [
    98, 95, 95, 94, 92, 89, 89, 89, 87, 87, 86, 85, 85, 84, 83, 81, 80, 79, 77,
    75, 71, 70, 70, 70, 69, 68, 68, 67, 65, 64, 63, 62, 61, 59, 58, 55, 54, 54,
    53, 53, 53, 53, 51, 49, 47, 46, 45, 45, 45, 43, 42, 42, 41, 39, 38, 38, 37,
    36, 35, 35, 35, 35, 35, 34, 33, 30, 30, 29, 28, 28, 27, 25, 23, 22, 22, 21,
    19, 19, 19, 18, 17, 15, 15, 15, 13, 13, 12, 12, 12, 11, 11, 10, 10, 5, 5,
    4, 4, 2, 1, 1
]

print(nx.is_graphical(z))

print("Configuration model")
G = nx.configuration_model(z)  # configuration model
print(G)
degree_sequence = [d for n, d in G.degree()]  # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist = {}
for d in degree_sequence:
    if d in hist:
        hist[d] += 1
    else:
        hist[d] = 1
print("degree #nodes")
for d in hist:
    print('%d %d' % (d, hist[d]))

nx.draw(G)
plt.show()
                   color='#FF8000')  # orange

    elif row['similarity'] < 0:
        G.add_edge(row['user_1'],
                   row['user_2'],
                   weight=row['similarity'],
                   color='r')  # red

G.size(100)
pos = nx.spring_layout(G)
edges = G.edges()
colors = [G[u][v]['color'] for u, v in edges]
weights = [G[u][v]['weight'] * 10 for u, v in edges]

plt.figure(3, figsize=(12, 12))
nx.draw(G, pos, edges=edges, edge_color=colors, width=weights)
nx.draw_networkx_labels(G, pos)
plt.show()

#  แสดงรูปตาราง movie title ที่ rating สูงสุด ที่ควรแนะนำของคนที่มีความชอบคล้ายกันที่สุด ที่ควรแนะนำให้ดู
pearson_sim = random_mt.T.corr(method='pearson')
np.fill_diagonal(pearson_sim.values, np.nan)

# Find similar user
user_sim_df = pd.DataFrame(pearson_sim.stack())
user_sim_df.columns = ['similarity']
user_sim_df.index.names = ['user_1', 'user_2']
user_sim_df = user_sim_df.groupby(level=0).idxmax()

# Create NaN table
user_mv_rate_df = pd.DataFrame(