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 __init__(self, operationCount, peerCount, graphInput): print("Inside Simulation init") self._op_count = int(operationCount) self._peer_count = int(peerCount) plt.axis('off') graph = nx.read_weighted_edgelist(graphInput) print(graph) # some properties print("node degree clustering") for v in nx.nodes(graph): print('%s %d %f' % (v, nx.degree(graph, v), nx.clustering(graph, v))) # print the adjacency list to terminal try: nx.write_adjlist(graph, sys.stdout) except TypeError: nx.write_adjlist(graph, sys.stdout.buffer) # node_pos = nx.spring_layout(graph) # # edge_weight = nx.get_edge_attributes(graph, 'weight') # # Draw the nodes # nx.draw_networkx(graph, node_pos, node_color='grey', node_size=100) # # Draw the edges # nx.draw_networkx_edges(graph, node_pos, edge_color='black') # # Draw the edge labels # nx.draw_networkx_edge_labels(graph, node_pos, edge_color='red', edge_labels=edge_weight) # plt.show() paths_for_diameter = nx.shortest_path_length(graph, weight='weight') ecc = nx.eccentricity(graph, sp=dict(paths_for_diameter)) self._diameter = nx.diameter(graph, e=ecc) print('The graph diameter is ', self._diameter) self._height_of_cluster = math.ceil(math.log(self._diameter, 2)) + 1 if not os.path.exists(graphInput+'_network'): print("CREATING NEW NETWORK") self._network = Network(graph) self._setup_peers(graph) # self._build_clusters_exactly_logn_membership(graph) self._build_clusters_at_least_one_and_at_most_logn(graph) # self._build_clusters_no_overlapping(graph) self._build_tree(graph) self.save_network(graphInput + '_network') exit(0) else: print("LOADING NETWORK FROM INPUT FILE") # load network self.load_network(graphInput + '_network')
def ids_algorithm(graph, start, end, iterate): max_limit = 0 nodes_checked = 0 # assume maximum depth must be the number of nodes n in the graph (branching factor = 1) # then return failure if the depth limit surpass n while max_limit <= len(nx.nodes(graph.graph)): depth_changed = True limit = 0 solution = [] cost = [0] opened = [(start, 0, 0)] # search until limit reaches 0 while len(opened) > 0: cur = opened.pop(0) nodes_checked += 1 while len(solution) != cur[1]: solution.pop(len(solution) - 1) cost.pop(len(cost) - 1) solution.append(cur[0]) cost.append(cost[len(cost) - 1] + cur[2]) if iterate and len(solution) == max_limit: yield {'depth changed' : depth_changed, 'current path' : solution, 'opened' : opened, 'cost' : cost[1:len(cost)]} if limit > cur[1]: limit = cur[1] if limit == max_limit and cur[0] == end: # a solution is found return {'path' : solution, 'cost' : cost[len(cost) - 1], 'checked' : nodes_checked} elif limit < max_limit: if limit == cur[1]: limit += 1 elif limit > cur[1]: limit = cur[1] # get all child nodes tmp = [] for child in graph.graph.edges_iter(cur[0], data=True): tmp.append((child[1], limit, child[2]['cost'])) opened = tmp + opened depth_changed = False # increase depth limit max_limit += 1 return None
reverse=True))))): source_node = next( iter(sorted(nx.connected_components(G), key=len, reverse=True)[i])) dest_node = next( iter(sorted(nx.connected_components(G), key=len, reverse=True)[0])) print("SOURCE NODEE", source_node) print("DEST NODEE", dest_node) G.add_edge(int(source_node), int(dest_node), weight=randint(1, 1)) assert nx.is_connected(G) print(sorted(sorted(nx.connected_components(G), key=len, reverse=True))) # 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))) # 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')
# Copyright (C) 2004-2017 by # Aric Hagberg <*****@*****.**> # Dan Schult <*****@*****.**> # Pieter Swart <*****@*****.**> # All rights reserved. # BSD license. import sys 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 to terminal try: nx.write_adjlist(G, sys.stdout) except TypeError: # Python 3.x nx.write_adjlist(G, sys.stdout.buffer) nx.draw(G) plt.show()
import sys import matplotlib.pyplot as plt from networkx import nx, json_graph plt.axis('off') # graph = nx.read_gml("test_gml") graph = nx.read_weighted_edgelist("8_0.01diamter3_newtest.weighted.edgelist") # some properties print("node degree clustering") for v in nx.nodes(graph): print('%s %d %f' % (v, nx.degree(graph, v), nx.clustering(graph, v))) # print the adjacency list to terminal try: nx.write_adjlist(graph, sys.stdout) except TypeError: nx.write_adjlist(graph, sys.stdout.buffer) node_pos = nx.spring_layout(graph) edge_weight = nx.get_edge_attributes(graph, 'weight') # Draw the nodes nx.draw_networkx(graph, node_pos, node_color='grey', node_size=100) # Draw the edges nx.draw_networkx_edges(graph, node_pos, edge_color='black') # Draw the edge labels
def save_network_to_db(self, data): # add node attributes to the dataset idMap = {} # map netgen created node id to original id nx = self.network.networkx_graph network = self.network for node in data[ 'nodeData']: # go through returned node data. False ones are removed later idMap[node['id']] = node[ '__originalId__'] if '__originalId__' in node else node['id'] nodeData = nx.node.get(idMap[node['id']], None) # get node data in network # make sure the node exists in the network if nodeData is None: print "ALGO ERROR : NODE NOT FOUND IN NETWORK. REJECTING NODE" continue nodeData['_remove_node'] = False for attrId, val in node.iteritems(): if attrId != 'id' and attrId != '__originalId__' and attrId != 'dataPointId': if val is not None and val != 'null': # see if attribute is node position if attrId == 'posX' or attrId == 'posY': nodeData[attrId.replace('pos', "Original")] = float(val) elif attrId == 'size': nodeData["OriginalSize"] = float(val) else: # see if attribute is already in dataset and add if its not if network.get_node_attr_with_id(attrId) is None: network.add_node_attr_desc( attrId, getAttrType(val)) # add value to node, convert to string if it isn't already if not isinstance(val, basestring): val = json.dumps(val) nodeData[attrId] = val # remove nodes which we don't want in the network for n in nx.nodes(): if nx.node[n].get('_remove_node', True): print "node id: %s marked for Removal: %s" % (n, nx.node[n]) nx.remove_node(n) # add edge attributes and edges to the dataset self.setProgress("Adding " + str(len(data['linkData'])) + " Links", 80) for edge in data['linkData']: # go through returned edge data linkData = {} # copy attrs for attrId, val in edge.iteritems(): if attrId != 'id1' and attrId != 'id2' and attrId != 'i' and attrId != 'j': if val != None and val != 'null': # see if attribute is already in dataset and add if its not if network.get_link_attr_with_id(attrId) == None: network.add_link_attr_desc(attrId, getAttrType(val)) # add value to edge attributes, convert to string if it isn't already if not isinstance(val, basestring): val = json.dumps(val) linkData[attrId] = val network.add_link(idMap[edge['id1']], idMap[edge['id2']], attribMap=linkData) if 'clusterInfo' in data: network.clusterInfo = data['clusterInfo'] else: print("No clusterInfo")