def _create_and_save_remixgroup(sg, remixgroup): # print ' ========================================= ' # add to list the subgraphs(connected components) with the extra data node_list = sg.nodes(data=True) # pp(node_list) # sort by date (holds all subgraph nodes sorted by date) # we need this since we go forward in time (source older than remix) node_list.sort( key=lambda x: x[1]['date']) # I think ['date'] is not necessary # print ' ========== SORTED NODE_LIST ========= ' # pp(node_list) # dict with key=sound_id, value=index, nodeName=original_filname # in the previous sorted by date list # FIXME: no need for all this data, can be simple dict, key=value container = dict((val[0], { 'index': idx, 'nodeName': val[1]['nodeName'] }) for (idx, val) in enumerate(node_list)) # print ' ========== CONTAINER ========= ' # pp(container) links = [] remixgroup.save() # need to save to have primary key before ManyToMany # FIXME: no idea why nx.weakly_connected_components(sg) return list in list... remixgroup.sounds = set(nx.weakly_connected_components(sg)[0]) remixgroup.group_size = len(node_list) # FIXME: seems like double work here, maybe convert container to list and sort? nodes = [{ 'id': val[0], 'username': val[1]['username'], 'nodeName': val[1]['nodeName'], 'sound_url_mp3': val[1]['sound_url_mp3'], 'sound_url_ogg': val[1]['sound_url_ogg'], 'waveform_url': val[1]['waveform_url'], 'group': 1 } for (idx, val) in enumerate(node_list)] for line in nx.generate_adjlist(sg): # print line if len(line.split()) > 1: for i, l in enumerate(line.strip().split(" ")): # index 0 is the source, which we already know if i > 0: link = { 'target': container[int(line.split(" ")[0])]['index'], 'source': container[int(l)]['index'] } links.append(link) #print link remixgroup.protovis_data = "{\"color\": \"#F1D9FF\"," \ "\"length\":" + str(len(node_list)) + "," \ "\"nodes\": " + json.dumps(nodes) + "," \ "\"links\": " + json.dumps(links) + "}" remixgroup.networkx_data = json.dumps( dict(nodes=sg.nodes(), edges=sg.edges())) remixgroup.save() print remixgroup.id print remixgroup.networkx_data
def load_graph(ifilename=None): """Load graph from file """ G = None # Testing mode if ifilename is None: n = 10 # 10 nodes m = 20 # 20 edges G = nx.gnm_random_graph(n, m) # 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) else: try: G = networkx.read_graphml(open(ifilename, 'r')) except Exception as ifile_err: print(f"Unable to load graph from {ifilename}: {ifile_err}") return G
def _create_and_save_remixgroup(sg, remixgroup): # print ' ========================================= ' # add to list the subgraphs(connected components) with the extra data node_list = sg.nodes(data=True) # pp(node_list) # sort by date (holds all subgraph nodes sorted by date) # we need this since we go forward in time (source older than remix) node_list.sort(key=lambda x: x[1]["date"]) # I think ['date'] is not necessary # print ' ========== SORTED NODE_LIST ========= ' # pp(node_list) # dict with key=sound_id, value=index, nodeName=original_filname # in the previous sorted by date list # FIXME: no need for all this data, can be simple dict, key=value container = dict((val[0], {"index": idx, "nodeName": val[1]["nodeName"]}) for (idx, val) in enumerate(node_list)) # print ' ========== CONTAINER ========= ' # pp(container) links = [] remixgroup.save() # need to save to have primary key before ManyToMany # FIXME: no idea why nx.weakly_connected_components(sg) return list in list... remixgroup.sounds = set(nx.weakly_connected_components(sg)[0]) remixgroup.group_size = len(node_list) # FIXME: seems like double work here, maybe convert container to list and sort? nodes = [ { "id": val[0], "username": val[1]["username"], "nodeName": val[1]["nodeName"], "sound_url_mp3": val[1]["sound_url_mp3"], "sound_url_ogg": val[1]["sound_url_ogg"], "waveform_url": val[1]["waveform_url"], "group": 1, } for (idx, val) in enumerate(node_list) ] for line in nx.generate_adjlist(sg): # print line if len(line.split()) > 1: for i, l in enumerate(line.strip().split(" ")): # index 0 is the source, which we already know if i > 0: link = {"target": container[int(line.split(" ")[0])]["index"], "source": container[int(l)]["index"]} links.append(link) remixgroup.protovis_data = ( '{"color": "#F1D9FF",' '"length":' + str(len(node_list)) + "," '"nodes": ' + json.dumps(nodes) + "," '"links": ' + json.dumps(links) + "}" ) remixgroup.networkx_data = json.dumps(dict(nodes=sg.nodes(), edges=sg.edges())) remixgroup.save()
def _create_and_save_remixgroup(sg, remixgroup): # print ' ========================================= ' # add to list the subgraphs(connected components) with the extra data node_list = sg.nodes(data=True) # pp(node_list) # sort by date (holds all subgraph nodes sorted by date) # we need this since we go forward in time (source older than remix) node_list.sort(key=lambda x: x[1]['date']) # I think ['date'] is not necessary # print ' ========== SORTED NODE_LIST ========= ' # pp(node_list) # dict with key=sound_id, value=index, nodeName=original_filname # in the previous sorted by date list # FIXME: no need for all this data, can be simple dict, key=value container = dict((val[0], {'index': idx, 'nodeName': val[1]['nodeName']}) for (idx, val) in enumerate(node_list)) # print ' ========== CONTAINER ========= ' # pp(container) links = [] remixgroup.save() # need to save to have primary key before ManyToMany # FIXME: no idea why nx.weakly_connected_components(sg) return list in list... remixgroup.sounds = set(nx.weakly_connected_components(sg)[0]) for sound in remixgroup.sounds.all(): sound.invalidate_template_caches() remixgroup.group_size = len(node_list) # FIXME: seems like double work here, maybe convert container to list and sort? nodes = [{'id': val[0], 'username': val[1]['username'], 'nodeName': val[1]['nodeName'], 'sound_url_mp3': val[1]['sound_url_mp3'], 'sound_url_ogg': val[1]['sound_url_ogg'], 'waveform_url': val[1]['waveform_url'], 'group': 1} for (idx, val) in enumerate(node_list)] for line in nx.generate_adjlist(sg): # print line if len(line.split()) > 1: for i, l in enumerate(line.strip().split(" ")): # index 0 is the source, which we already know if i > 0: link = {'target': container[int(line.split(" ")[0])]['index'], 'source': container[int(l)]['index']} links.append(link) remixgroup.protovis_data = "{\"color\": \"#F1D9FF\"," \ "\"length\":" + str(len(node_list)) + "," \ "\"nodes\": " + json.dumps(nodes) + "," \ "\"links\": " + json.dumps(links) + "}" remixgroup.networkx_data = json.dumps(dict(nodes=sg.nodes(), edges=sg.edges())) remixgroup.save()
import matplotlib.pyplot as plt from networkx import nx a, b, c, d, e, f = ('a', 'b', 'c', 'd', 'e', 'f') G = nx.Graph() G.add_edge(a, b) G.add_edge(b, c) G.add_edge(c, b) G.add_edge(c, a) G.add_edge(c, d) G.add_edge(d, e) G.add_edge(e, f) G.add_edge(f, d) for line in nx.generate_adjlist(G): print(line) nx.draw(G, with_labels=True) plt.show()
args = parser.parse_args() # realiza o parse 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__ = '*****@*****.**'
sometimes called the Erdős-Rényi graph. """ # Author: Aric Hagberg ([email protected]) # Copyright (C) 2004-2019 by # Aric Hagberg <*****@*****.**> # Dan Schult <*****@*****.**> # Pieter Swart <*****@*****.**> # All rights reserved. # BSD license. import matplotlib.pyplot as plt from networkx import nx n = 10 # 10 nodes m = 20 # 20 edges G = nx.gnm_random_graph(n, m) # some properties print("node degree clustering") for v in nx.nodes(G): print('%s %d %f' % (v, nx.degree(G, v), nx.clustering(G, v))) # print the adjacency list for line in nx.generate_adjlist(G): print(line) nx.draw(G) plt.show()