def __init__(self, state): """ Initializes your Player. You can set up persistent state, do analysis on the input graph, engage in whatever pre-computation you need. This function must take less than Settings.INIT_TIMEOUT seconds. --- Parameters --- state : State The initial state of the game. See state.py for more information. """ graph = state.get_graph() #e_dict = nx.eccentricity(graph) station = nx.center(graph)[0] if nx.center(graph) else graph.nodes()[len(graph.nodes()) / 2] #max(e_dict, key=lambda i: x[i]) self.stations.append(station)
def nodelist(network): """Returns a drawable nodelist. This is designed for the concentric circle-based drawing functions of networkx. """ # first off, find most largestly connected (hub) server for the center center = nx.center(network) center = center[0] # returns a list of centers, and we don't want that # and create the layers off that added_nodes = [ center, ] shells = [ (center, ), ] # holds recursive shells any_added = True while any_added: any_added = False new_shell = [] for node in shells[-1]: new_neighbors = nx.all_neighbors(network, node) for n in new_neighbors: if n not in added_nodes: new_shell.append(n) added_nodes.append(n) any_added = True if len(new_shell) > 0: new_shell = (new_shell) # make a tuple shells.append(new_shell) return shells
def Distance_measures(P, tipo, ruta): RUTA = ruta + '/NetWX/files/' path = Path(RUTA) path.mkdir(parents = True,exist_ok = True) P_center = [] P_diameter = [] P_extrema_bounding = [] P_periphery = [] P_radius = [] for i in range(len(P)): P_center.append(center(P[i])) P_diameter.append(diameter(P[i])) P_extrema_bounding.append(extrema_bounding(P[i])) P_periphery.append(periphery(P[i])) P_radius.append(radius(P[i])) P_center = DataFrame(P_center) P_diameter = DataFrame(P_diameter) P_extrema_bounding = DataFrame(P_extrema_bounding) P_periphery = DataFrame(P_periphery) P_radius = DataFrame(P_radius) P_center.to_csv(RUTA + tipo + " - center.txt", sep = '\t',header = None,index = False) P_diameter.to_csv(RUTA + tipo +" - diameter.txt", sep = '\t',header = None,index = False) P_extrema_bounding.to_csv(RUTA + tipo +" - extrema_bounding.txt", sep = '\t',header = None,index = False) P_periphery.to_csv(RUTA + tipo + " - periphery.txt", sep = '\t',header = None,index = False) P_radius.to_csv(RUTA + tipo + " - radius.txt", sep = '\t',header = None,index = False)
def twopi_layout(nx_graph, center=None): """ Render the twopi layout. Ported from C code available at https://github.com/ellson/graphviz/blob/master/lib/twopigen/circle.c :param networkx.MultiDiGraph nx_graph: the networkx graph :param str center: the centered node :return: """ if len(nx_graph.nodes()) == 0: return {} if len(nx_graph.nodes()) == 1: return {nx_graph.nodes()[0]: (0, 0)} #nx_graph = nx_graph.to_undirected() data = ExplorerScene._init_layout(nx_graph) if not center: center = networkx.center(nx_graph)[0] ExplorerScene._set_parent_nodes(nx_graph, data, center) ExplorerScene._set_subtree_size(nx_graph, data) data[center]['span'] = 2 * math.pi ExplorerScene._set_subtree_spans(nx_graph, data, center) data[center]['theta'] = 0.0 ExplorerScene._set_positions(nx_graph, data, center) distances = networkx.shortest_path_length(nx_graph.to_undirected(), center) nx_pos = {} for node in nx_graph.nodes(): hyp = distances[node] + 1 theta = data[node]['theta'] nx_pos[node] = (hyp * math.cos(theta) * 100, hyp * math.sin(theta) * 100) return nx_pos
def group_nodes(graph, size=3): root = nx.center(graph)[0] groups = [] group = [] for n in nx.dfs_preorder_nodes(graph, root): if graph.degree(n) < 2: continue # hit the terminal if len(group) >= 1 and not set(graph[n]).intersection(set(group)): groups.append(group) group = [] # size cut if len(group) >= size: groups.append(group) group = [] group.append(n) if group not in groups: groups.append(group) for i in range(len(groups)): # build sub-graph that includes degree = 1 elements group = groups[i] for n in group: for nn in graph[n]: if graph.degree(nn) == 1: group.append(nn) groups[i] = group return groups
def updateGraphStats(self, graph): origgraph = graph if nx.is_connected(graph): random = 0 else: connectedcomp = nx.connected_component_subgraphs(graph) graph = max(connectedcomp) if len(graph) > 1: pathlength = nx.average_shortest_path_length(graph) else: pathlength = 0 # print graph.nodes(), len(graph), nx.is_connected(graph) stats = { "radius": nx.radius(graph), "density": nx.density(graph), "nodecount": len(graph.nodes()), "center": nx.center(graph), "avgcluscoeff": nx.average_clustering(graph), "nodeconnectivity": nx.node_connectivity(graph), "components": nx.number_connected_components(graph), "avgpathlength": pathlength } # print "updated graph stats", stats return stats
def answer_twelve(): # Your Code Here G = answer_six() center = nx.center(G)[0] node = answer_eleven()[0] return len(nx.minimum_node_cut(G, center, node))
def get_nations_network_by_year(year): cursor = get_db().cursor() cursor.execute( """SELECT reporting, reporting_slug, partner, partner_slug, flow*Unit/ifnull(rate,1) as flow, expimp, reporting_continent, partner_continent,reporting_type,partner_type FROM flow_joined WHERE reporting NOT LIKE "Worl%%" AND partner NOT LIKE "Worl%%" AND partner_slug IS NOT "NA" AND partner_slug IS NOT "Unknown" AND flow is not NULL AND year = %s """ % (year)) table = [list(r) for r in cursor] json_sql_response = [] for row in table: json_sql_response.append({ "reporting": row[0], "reporting_id": row[1], "partner": row[2], "partner_id": row[3], "flow": row[4], "expimp": row[5], "reporting_continent": row[6], "partner_continent": row[7], "reporting_type": row[8], "partner_type": row[9] }) # Create a graph instance G = nx.Graph() nodes = [] for row in table: nodes.append(row[1]) nodes.append(row[3]) # add edge to the graph G.add_edge(row[1], row[3]) nodes = set(nodes) # add nodes to graph G.add_nodes_from(nodes) if len(G.nodes()) > 0: stats = { "average_clustering": nx.average_clustering(G), "center": nx.center(G), "diameter": nx.diameter(G), "eccentricity": nx.eccentricity(G) } else: stats = [] json_response = {} json_response["stats"] = stats json_response["network"] = json_sql_response return json.dumps(json_response, encoding="UTF8")
def answer_ten(): # Your Code Here G_sc = answer_six() center = nx.center(G_sc) return set(center) # Your Answer Here
def mkMatch(network, method): g_ = network if 'kclick' in method: # k-click communities # k_ = int(method.replace('kclick', '')) svs = [i for i in x.algorithms.community.k_clique_communities(g_, 10)] gg = x.Graph() for i, sv in enumerate(svs): gg.add_node(i, weight=len(sv), children=sv) elif method == 'lab': # label propagation svs = [ i for i in x.algorithms.community.label_propagation_communities(g_) ] gg = x.Graph() for i, sv in enumerate(svs): gg.add_node(i, weight=len(sv), children=sv) elif method == 'cp': sub = [i for i in x.connected_component_subgraphs(g_)] g = sub[0] per = set(x.periphery(g)) if len(sub) > 1: for per_ in sub[1:]: per.update(per_.nodes()) cen = set(x.center(g)) pc = per.union(cen) nodes = set(g.nodes()) inter = nodes.difference(pc) gg = x.Graph() gg.add_node(0, label='center', weight=len(cen), children=cen) gg.add_node(1, label='intermediary', weight=len(inter), children=inter) gg.add_node(2, label='periphery', weight=len(per), children=per) return gg # meta-network
def adjustUMI(umiList, dist=1): umi_count, umi_set_list = countList(umiList) # 1. compare all umis find singleton and creat Graph to get center umiG = nx.Graph() singleton_umi = deepcopy(umi_set_list) umi_map = {} for u1, u2 in combinations(umi_set_list, 2): if hDistance(u1, u2) <= 1: umiG.add_edges_from([(u1, u2)]) if u1 in singleton_umi: singleton_umi.remove(u1) if u2 in singleton_umi: singleton_umi.remove(u2) if singleton_umi: for eachSgl in singleton_umi: umi_map[eachSgl] = eachSgl if list(nx.connected_components(umiG)): for eachG in nx.connected_component_subgraphs(umiG): centerUmilist = nx.center(eachG) if len(centerUmilist) == 1: for rawUmi in list(nx.connected_components(eachG))[0]: umi_map[rawUmi] = centerUmilist[0] else: max_umiCount = 0 centerUmi = "" for cenUmi in centerUmilist: if umi_count[cenUmi] > max_umiCount: max_umiCount = umi_count[cenUmi] centerUmi = cenUmi for rawUmi in list(nx.connected_components(eachG))[0]: umi_map[rawUmi] = centerUmi return umi_map
def answer_twelve(): G_sc = answer_six() center = nx.center(G_sc)[0] mynode = answer_eleven()[0] return len(nx.minimum_node_cut(G_sc, center, mynode))
def info(graph): """Function that take the graph whose information is to be displayed Information includes - number of nodes - Total number of nodes number of edges - Total number of edges Average degree - Degree of nodes (Indegree+ Outdegree) radius - Minimum eccentricity diameter - Maximum eccentricity eccentricity - Eccentricity of a node v is the maximum distance from v to all other nodes in graph. center - Set of nodes with eccentricity equal to radius. periphery - Set of nodes with eccentricity equal to the diameter. Density """ try: print("-" * 10, "Node Attributes", "-" * 10) print(n.info(graph)) print("-" * 10, "Distance Measures", "-" * 10) print("radius: %d" % n.radius(graph)) print("diameter: %d" % n.diameter(graph)) print("eccentricity: %s" % n.eccentricity(graph)) print("center: %s" % n.center(graph)) print("periphery: %s" % n.periphery(graph)) print("density: %s" % n.density(graph)) except Exception as ex: print(ex) return graph
def SaveGraph(self, filename): logging.debug("From SVNFileNetwork.SaveGraph") print "saving the file network graph to %s" % filename plt.clf() #pos = NX.spring_layout(self, dim=2, iterations=20) logging.info("starting layout using pydot_layout") pos = NX.pydot_layout(self, prog='neato') print "finished layout" logging.info("finished layout using pydot_layout") plt.figure(figsize=(8.0, 8.0)) NX.draw_networkx_nodes(self, pos, node_size=10) NX.draw_networkx_edges(self, pos) # display revision nodes in different colors revnodes = self.getNodes(SVNNetworkRevisionNode) NX.draw_networkx_nodes( self, pos, revnodes, node_color='g', node_size=30) # display center nodes with larger size NX.draw_networkx_nodes( self, pos, NX.center(self), node_color='b', node_size=50) ax = plt.gca() plt.setp(ax.get_yticklabels(), visible=False) plt.setp(ax.get_xticklabels(), visible=False) plt.savefig(filename, dpi=100, format="png") self.PrintGraphStat() print "Saved ..."
def print_graph_info(graph): e = nx.eccentricity(graph) print 'graph with %u nodes, %u edges' % (len(graph.nodes()), len(graph.edges())) print 'radius: %s' % nx.radius(graph, e) # min e print 'diameter: %s' % nx.diameter(graph, e) # max e print 'len(center): %s' % len(nx.center(graph, e)) # e == radius print 'len(periphery): %s' % len(nx.periphery(graph, e)) # e == diameter
def SaveGraph(self, filename): logging.debug("From SVNFileNetwork.SaveGraph") print("saving the file network graph to %s" % filename) plt.clf() #pos = NX.spring_layout(self, dim=2, iterations=20) logging.info("starting layout using pydot_layout") pos = NX.pydot_layout(self, prog='neato') print("finished layout") logging.info("finished layout using pydot_layout") plt.figure(figsize=(8.0, 8.0)) NX.draw_networkx_nodes(self, pos, node_size=10) NX.draw_networkx_edges(self, pos) # display revision nodes in different colors revnodes = self.getNodes(SVNNetworkRevisionNode) NX.draw_networkx_nodes( self, pos, revnodes, node_color='g', node_size=30) # display center nodes with larger size NX.draw_networkx_nodes( self, pos, NX.center(self), node_color='b', node_size=50) ax = plt.gca() plt.setp(ax.get_yticklabels(), visible=False) plt.setp(ax.get_xticklabels(), visible=False) plt.savefig(filename, dpi=100, format="png") self.PrintGraphStat() print("Saved ...")
def basic_stats(self): #not decided on what level to deal with this yet: #either return error un not dealing with unconnected files, #or making it deal with unconnected files: the latter. #How about with dealing with each independently. # if not nx.is_connected(g): # conl= nx.connected_components(g) # for n in conl: # turn n into graph if it isnt # calculate ec, per, cnt # how and when to visualise the subgraphs? # iterate to next n if nx.is_connected(self.nx_graph): ec = nx.eccentricity(self.nx_graph) else: ec = 'NA - graph is not connected' per = nx.periphery(self.nx_graph) cnt = nx.center(self.nx_graph) result = { #"""fast betweenness algorithm""" 'bbc': nx.brandes_betweenness_centrality(self.nx_graph), 'tn': nx.triangles(self.nx_graph), # number of triangles 'ec': ec, 'per': per, 'cnt': cnt, 'Per': self.nx_graph.subgraph(per), 'Cnt': self.nx_graph.subgraph(cnt) } return result
def Properties(G, verbose=0): txt = '' pathlengths = [] for v in G.nodes(): spl = nx.single_source_shortest_path_length(G, v) #print('%s %s' % (v,spl),file=sys.stderr) for p in spl.values(): pathlengths.append(p) txt += "average shortest path length %s\n" % (sum(pathlengths) / len(pathlengths)) # histogram of path lengths dist = {} for p in pathlengths: if p in dist: dist[p] += 1 else: dist[p] = 1 txt += "length #paths" verts = dist.keys() for d in sorted(verts): txt += '%s %d\n' % (d, dist[d]) txt += 'radius: %d\n' % nx.radius(G) txt += 'diameter: %d\n' % nx.diameter(G) #txt+= 'eccentricity: %s\n' % nx.eccentricity(G) txt += 'center: %s\n' % nx.center(G) #txt+= 'periphery: %s\n' % nx.periphery(G) txt += 'density: %s\n' % nx.density(G) return txt
def extract_simple_features(self, graph): res = {} try: print('diameter: ', nx.diameter(graph)) print('eccentricity: ', nx.eccentricity(graph)) print('center: ', nx.center(graph)) print('periphery: ', nx.periphery(graph)) res['connected'] = True except Exception as e: print('Graph not connected') res['connected'] = False res['density'] = '{:.6f}'.format(nx.density(graph)) res['Avg_degree'] = '{:.6f}'.format( sum([i[1] for i in nx.degree(graph)]) / len(nx.degree(graph))) res['Avg_weight'] = '{:.6f}'.format( sum([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges]) / len([graph[edge[0]][edge[1]]['weight'] for edge in graph.edges])) res['edges'] = len(graph.edges) res['nodes'] = len(graph.nodes) res['self_loops'] = len(list(nx.nodes_with_selfloops(graph))) res['edge_to_node_ratio'] = '{:.6f}'.format( len(graph.nodes) / len(graph.edges)) res['negative_edges'] = nx.is_negatively_weighted(graph) return res
def parseCSVGraphAnalysis(G): global headers row = '' data = nx.info(G).split('\n') nameG = data[0].split(':')[1].strip() if saveGEXF: nx.write_gexf(G, nameG + '.gexf') if headers: row = 'Name' + separator + separator.join( val.split(':')[0] for val in data[2:]) row += (separator + 'Density') if selected[0] else '' row += (separator + 'Diameter') if selected[1] else '' row += (separator + 'Degrees') if selected[2] else '' row += (separator + 'Eccentricity') if selected[3] else '' row += (separator + 'Center') if selected[4] else '' row += (separator + 'Periphery') if selected[5] else '' row += '\n' headers = False row += nameG + separator + separator.join( val.split(':')[1].strip() for val in data[2:]) row += (separator + str(nx.density(G))) if selected[0] else '' row += (separator + str(nx.diameter(G))) if selected[1] else '' row += (separator + str(nx.degree(G))) if selected[2] else '' row += (separator + str(nx.eccentricity(G))) if selected[3] else '' row += (separator + str(nx.center(G))) if selected[4] else '' row += (separator + str(nx.periphery(G))) if selected[5] else '' return row
def nodelist(network): """Returns a drawable nodelist. This is designed for the concentric circle-based drawing functions of networkx. """ # first off, find most largestly connected (hub) server for the center center = nx.center(network) center = center[0] # returns a list of centers, and we don't want that # and create the layers off that added_nodes = [center, ] shells = [(center,), ] # holds recursive shells any_added = True while any_added: any_added = False new_shell = [] for node in shells[-1]: new_neighbors = nx.all_neighbors(network, node) for n in new_neighbors: if n not in added_nodes: new_shell.append(n) added_nodes.append(n) any_added = True if len(new_shell) > 0: new_shell = (new_shell) # make a tuple shells.append(new_shell) return shells
def analyze_distance(): center = nx.center(G) barycenter = nx.barycenter(G) diameter = nx.diameter(G) table = prettytable.PrettyTable(['center', 'barycenter', 'diameter']) table.add_row([center, barycenter, diameter]) print(table)
def make_graph(graph_object, color_map): """Makes the graph and returns variables needed for further visualization :return center: center node :return title: the label of the center node used for titling visualizations :return node_count: the number of nodes :return fig1: the graph """ fig1 = plt.figure() center = nx.center(graph_object)[0] title = graph_object.nodes[center]['label'] # degrees = nx.degree(graph_object) node_count = len(nx.nodes(graph_object)) # layout for display pos = nx.spring_layout(graph_object) # draw function nx.draw(graph_object, pos=pos, node_color=color_map, node_size=1000) # add node labels node_labels = nx.get_node_attributes(graph_object, 'label') nx.draw_networkx_labels(graph_object, pos=pos, labels=node_labels) # add edge labels edge_labels = nx.get_edge_attributes(graph_object, 'PARTICIPATION_TYPE') nx.draw_networkx_edge_labels(graph_object, pos, edge_labels) return center, title, node_count, fig1
def get_nations_network_by_year(year): cursor = get_db().cursor() cursor.execute("""SELECT reporting, reporting_slug, partner, partner_slug, Flow, expimp, reporting_continent, partner_continent,reporting_type,partner_type FROM flow_joined WHERE reporting NOT LIKE "Worl%%" AND partner NOT LIKE "Worl%%" AND Flow != "null" AND year = %s """%(year) ) table = [list(r) for r in cursor] json_sql_response=[] for row in table: json_sql_response.append({ "reporting": row[0], "reporting_id": row[1], "partner": row[2], "partner_id": row[3], "flow": row[4], "expimp": row[5], "reporting_continent": row[6], "partner_continent": row[7], "reporting_type": row[8], "partner_type": row[9] }) # Create a graph instance G=nx.Graph() nodes = [] for row in table: nodes.append(row[1]) nodes.append(row[3]) # add edge to the graph G.add_edge(row[1], row[3]) nodes = set(nodes) # add nodes to graph G.add_nodes_from(nodes) if len(G.nodes())>0: stats = { "average_clustering": nx.average_clustering(G), "center": nx.center(G), "diameter": nx.diameter(G), "eccentricity": nx.eccentricity(G) } else: stats=[] json_response = {} json_response["stats"] = stats json_response["network"] = json_sql_response return json.dumps(json_response,encoding="UTF8")
def verify_graph(nx_graph): g_gen = Graph() for edge in nx.edges(nx_graph): g_gen.add_edge(*edge) diameter, center = g_gen.diameter_center() assert (center in nx.center(nx_graph)) == True assert diameter == nx.diameter(nx_graph)
def answer_ten(): # Your Code Here # r = nx.radius(G_sc) # e = nx.eccentricity(G_sc) # n = [node for node in e.items() if node[1] == r] # set([node[0] for node in n]) return set(nx.center(G_sc)) # Your Answer Here
def find_central(G): try: cen = nx.center(G) except nx.exception.NetworkXError: print('Graph is not connected') cen = {} print('Central: ', cen) return cen
def point_to_new_cluster(clust): try: sub = self.collapsed_clusters[clust.cluster] return utilities.Cluster_Entry(sub, nx.center(self.clusters[sub])[0]) except KeyError: return clust
def answer_twelve(): # Your Code Here n = answer_eleven()[0] c = nx.center(G_sc)[0] # cut = nx.minimum_node_cut(G=G_sc, s=c, t=n) conn = nx.node_connectivity(G_sc, s=c, t=n) - 1 return conn # Your Answer Here
def print_graph_info(graph): e = nx.eccentricity(graph) print 'graph with %u nodes, %u edges' % (len( graph.nodes()), len(graph.edges())) print 'radius: %s' % nx.radius(graph, e) # min e print 'diameter: %s' % nx.diameter(graph, e) # max e print 'len(center): %s' % len(nx.center(graph, e)) # e == radius print 'len(periphery): %s' % len(nx.periphery(graph, e)) # e == diameter
def find_central(G): #set of nodes that have eccentricity equal to the radius try: cen = nx.center(G) except nx.exception.NetworkXError: print('Graph is not connected') cen = {} print('Central: ', cen) return cen
def get_graph_center(G): center= nx.center(G) non_center = [node for node in G.nodes if node not in center] G2 = G.copy() G2.remove_nodes_from(non_center) return center, G2
def answer_ten(): G = answer_six() # Manual calculate: # ec = nx.eccentricity(G) # radius = nx.radius(G) # return set([node for node, value in ec.items() if value==radius]) return set(nx.center(G))
def getDiffusionModelLabels(adjacency, repetitions=1000, threshold=0.5, patient0=None): import networkx as nx import ndlib.models.ModelConfig as mc from ndlib.models.epidemics.IndependentCascadesModel import IndependentCascadesModel if patient0 is None: patient0 = nx.center(nx.from_numpy_matrix(adjacency))[ 0] # A-4: 50, B-4: 71; A-6: 42, B-4: 26 A = adjacency.copy() g = nx.from_numpy_matrix(A) cfg = mc.Configuration() cfg.add_model_initial_configuration("Infected", set(list([patient0]))) if threshold is None: threshold = 0.5 for e in g.edges(): cfg.add_edge_configuration("threshold", e, threshold) model = IndependentCascadesModel(g) model.set_initial_status(cfg) if repetitions is None: repetitions = 1000 res_probs = np.zeros((A.shape[0], repetitions)) res_Probs = np.zeros(res_probs.shape) iteration_results = [] for rep in range(repetitions): model.reset() itr = 0 while True: itr += 1 iteration_result = model.iteration() iteration_results.append(iteration_result) for node, status in iteration_result['status'].items(): if status == 1: res_probs[node, rep] = itr if len(iteration_result['status']) == 0: break res_Probs[res_probs[:, rep] > 1, rep] = 1.0 / (res_probs[res_probs[:, rep] > 1, rep] - 1.) res_Prob = np.mean(res_Probs, 1) res_Prob[patient0] = np.mean(res_Prob[np.argwhere( adjacency[patient0, :])][:, 0]) # import matplotlib.pyplot as plt # plt.imshow(np.repeat(res_Prob.reshape((len(res_Prob),1)),10,axis=1)) return res_Prob
def jordanCenter(graph): if len(graph.nodes) == 1: return graph.nodes[0], 0 if not nx.is_connected(graph): conComp = max(nx.connected_components(graph), key=len) graph = graph.subraph(conComp) center = nx.center(graph)[0] radius = nx.radius(graph) return center, radius
def answer_twelve(): nodes_to_cut = set() G_sc = answer_six() target = answer_eleven()[0] sources = nx.center(G_sc) for source in sources: min_nodes_to_cut = nx.minimum_node_cut(G_sc, s=source, t=target) nodes_to_cut.update(min_nodes_to_cut) n_min_nodes_to_cut = len(nodes_to_cut) return n_min_nodes_to_cut
def answer_twelve(): # Your Code Here G_sc = answer_six() node_11 = answer_eleven()[0] center_nodes = nx.center(G_sc) no_cut_nodes = len( [nx.minimum_node_cut(G_sc, cn, node_11) for cn in center_nodes][0]) return no_cut_nodes
def f33(self): return "ND" start = 0 try: res = len(nx.center(self.G)) except nx.exception.NetworkXError: res = "ND" stop = 0 # self.feature_time.append(stop - start) return res
def _get_prototype_id(self): node_graph = nx.Graph() for i in range(self.total_instances): for j in range(i + 1, self.total_instances): node_graph.add_edge(i, j, weight = \ self.base_similarity_matrix[i, j]) T = nx.minimum_spanning_tree(node_graph) list_of_centers = nx.center(T) return list_of_centers[0]
def LeaderInCluster( graphObj, moldict ): leaderList = [] for eachSubGraph in nx.connected_component_subgraphs( graphObj ): centerlist = nx.center(eachSubGraph) if len(centerlist) < 1: raise "A subgraph with less than 1 center" leaderID = RandomPickFromList(centerlist) leaderList.append( leaderID ) graphSize = len(eachSubGraph) moldict[ leaderID ][ "size" ] = graphSize return leaderList
def test_center(testgraph): """ Testing center function for graphs. """ a, b = testgraph nx_center = nx.center(a) sg_center = sg.digraph_distance_measures.center(b, b.nodes()) nx_center = array(nx_center, dtype = uint32) nx_center.sort() sg_center.sort() assert_equal(nx_center, sg_center)
def __get_centroid(self, cluster=None): """Get the centroid of a cluster in the graph or the centroid of the graph. Parameters ---------- cluster : list Nodes list of a cluster. Returns ------- centroid_node : int Centroid node of a cluster. """ # centroid of a cluster if cluster: subgraph = self.graph.subgraph(cluster) centroid = nx.center(subgraph) # centroid of the graph else: centroid = nx.center(self.graph) # choose randomly if more than one centroid found centroid_node = choice(centroid) if len(centroid) > 1 else centroid return centroid_node
def connectivity(self): components = list(nx.connected_component_subgraphs(self.G)) print('Connected components number: ') print(len(components)) giant = components.pop(0) print('Giant component radius: ') print(nx.radius(giant)) print('Giant component diameter: ') print(nx.diameter(giant)) center = nx.center(giant) print('Giant component center: ') for i in xrange(len(center)): print(self.singer_dict[int(center[i])].split('|')[0]) inf = self.get_graph_info(giant) for i in xrange(len(inf)): print(inf[i])
def append_central_nodes(graph, table_data): """Append periphery nodes to table_data.""" # first, setup all values to false for node in graph.nodes(data=True): node_name = gen_username(node[1]['first_name'], node[1]['last_name'], node[0]) if node_name in table_data: table_data[node_name].append('') else: table_data[node_name] = [''] # second, update these values to True for periphery for uid in nx.center(graph): node_name = gen_username(graph.node[uid]['first_name'], graph.node[uid]['last_name'], uid) table_data[node_name][-1] = 'True'
def generateGraphFromFile(): g = nx.Graph() nodes = [] with open("File.txt") as f: for line in f: line = line.replace("\n","") lineArr = line.split(" ") dummy = tuple(lineArr[0:3]) nodes.append(dummy) g.add_weighted_edges_from(nodes) matrixPaths = nx.floyd_warshall_numpy(g,nodelist=None, weight='weight') #print matrixPaths listNodes = g.nodes() #print listNodes center = nx.center(g,e=None) #print center pos=nx.spring_layout(g) return (center, matrixPaths, listNodes,g,pos)
def report_components(g): components = nx.connected_component_subgraphs(g) print "Components: %d" % len(components) c_data = {} for i in range(len(components)): c = components[i] if len(c.nodes()) > 5: # Avoid reporting on many small components c_data["nodes"] = len(c.nodes()) c_data["edges"] = len(c.edges()) c_data["avg_clustering"] = nx.average_clustering(c) c_data["diameter"] = nx.diameter(c) c_data["radius"] = nx.radius(c) c_data["center"] = len(nx.center(c)) c_data["periphery"] = len(nx.periphery(c)) print "* Component %d:" % i for k in c_data: print "--- %s: %s" % (k, c_data[k]) return c_data
def SaveMST(self, filename): logging.debug("From SVNFileNetwork.SaveMST") mstGraph = self._getMSTGraph() print "saving MST of the file network graph to %s" % filename plt.clf() #pos = NX.spring_layout(self, dim=2, iterations=20) logging.info("starting layout using pydot_layout") pos = NX.pydot_layout(mstGraph, prog='neato') print "finished layout" logging.info("finished layout using pydot_layout") plt.figure(figsize=(8.0, 8.0)) NX.draw_networkx_nodes(mstGraph, pos, node_size=10) NX.draw_networkx_edges(mstGraph, pos) # display center nodes with larger size NX.draw_networkx_nodes( mstGraph, pos, NX.center(mstGraph), node_color='b', node_size=50) # create node labels label = dict() for node in mstGraph.nodes_iter(): dirname, fname = os.path.split(node.name()) label[node] = fname NX.draw_networkx_labels(mstGraph, pos, label, font_size=8) # disable X and Y tick labels ax = plt.gca() plt.setp(ax.get_yticklabels(), visible=False) plt.setp(ax.get_xticklabels(), visible=False) plt.savefig(filename, dpi=100, format="png") print "Saved MST..." print "saving MST treemap" jsfilename, ext = os.path.splitext(filename) jsfilename = jsfilename + '.js' print "treemap filename %s" % jsfilename outfile = open(jsfilename, "w") self.treemapNodeDict['Root'].writejson( outfile, 'closeness', 'betweenness') outfile.close()
# Define the equivalent NetworkX graph to test against gnx = nx.Graph() gnx.add_edge(0, 1) gnx.add_edge(1, 2) gnx.add_edge(1, 3) gnx.add_edge(4, 1) assert g.degree(0) == gnx.degree(0) assert g.degree(1) == gnx.degree(1) assert g.degree(4) == gnx.degree(4) diameter, center = g.diameter_center() assert (center in nx.center(gnx)) == True # Use network x to generate a random graph and replicate it as a custom graph. # Then check it returns the same value for some functions def verify_graph(nx_graph): g_gen = Graph() for edge in nx.edges(nx_graph): g_gen.add_edge(*edge) diameter, center = g_gen.diameter_center() assert (center in nx.center(nx_graph)) == True assert diameter == nx.diameter(nx_graph) verify_graph(nx.sedgewick_maze_graph())
def extended_stats(G, connectivity=False, anc=False, ecc=False, bc=False, cc=False): """ Calculate extended topological stats and metrics for a graph. Many of these algorithms have an inherently high time complexity. Global topological analysis of large complex networks is extremely time consuming and may exhaust computer memory. Consider using function arguments to not run metrics that require computation of a full matrix of paths if they will not be needed. Parameters ---------- G : networkx multidigraph connectivity : bool if True, calculate node and edge connectivity anc : bool if True, calculate average node connectivity ecc : bool if True, calculate shortest paths, eccentricity, and topological metrics that use eccentricity bc : bool if True, calculate node betweenness centrality cc : bool if True, calculate node closeness centrality Returns ------- stats : dict dictionary of network measures containing the following elements (some only calculated/returned optionally, based on passed parameters): - avg_neighbor_degree - avg_neighbor_degree_avg - avg_weighted_neighbor_degree - avg_weighted_neighbor_degree_avg - degree_centrality - degree_centrality_avg - clustering_coefficient - clustering_coefficient_avg - clustering_coefficient_weighted - clustering_coefficient_weighted_avg - pagerank - pagerank_max_node - pagerank_max - pagerank_min_node - pagerank_min - node_connectivity - node_connectivity_avg - edge_connectivity - eccentricity - diameter - radius - center - periphery - closeness_centrality - closeness_centrality_avg - betweenness_centrality - betweenness_centrality_avg """ stats = {} full_start_time = time.time() # create a DiGraph from the MultiDiGraph, for those metrics that require it G_dir = nx.DiGraph(G) # create an undirected Graph from the MultiDiGraph, for those metrics that # require it G_undir = nx.Graph(G) # get the largest strongly connected component, for those metrics that # require strongly connected graphs G_strong = get_largest_component(G, strongly=True) # average degree of the neighborhood of each node, and average for the graph avg_neighbor_degree = nx.average_neighbor_degree(G) stats['avg_neighbor_degree'] = avg_neighbor_degree stats['avg_neighbor_degree_avg'] = sum(avg_neighbor_degree.values())/len(avg_neighbor_degree) # average weighted degree of the neighborhood of each node, and average for # the graph avg_weighted_neighbor_degree = nx.average_neighbor_degree(G, weight='length') stats['avg_weighted_neighbor_degree'] = avg_weighted_neighbor_degree stats['avg_weighted_neighbor_degree_avg'] = sum(avg_weighted_neighbor_degree.values())/len(avg_weighted_neighbor_degree) # degree centrality for a node is the fraction of nodes it is connected to degree_centrality = nx.degree_centrality(G) stats['degree_centrality'] = degree_centrality stats['degree_centrality_avg'] = sum(degree_centrality.values())/len(degree_centrality) # calculate clustering coefficient for the nodes stats['clustering_coefficient'] = nx.clustering(G_undir) # average clustering coefficient for the graph stats['clustering_coefficient_avg'] = nx.average_clustering(G_undir) # calculate weighted clustering coefficient for the nodes stats['clustering_coefficient_weighted'] = nx.clustering(G_undir, weight='length') # average clustering coefficient (weighted) for the graph stats['clustering_coefficient_weighted_avg'] = nx.average_clustering(G_undir, weight='length') # pagerank: a ranking of the nodes in the graph based on the structure of # the incoming links pagerank = nx.pagerank(G_dir, weight='length') stats['pagerank'] = pagerank # node with the highest page rank, and its value pagerank_max_node = max(pagerank, key=lambda x: pagerank[x]) stats['pagerank_max_node'] = pagerank_max_node stats['pagerank_max'] = pagerank[pagerank_max_node] # node with the lowest page rank, and its value pagerank_min_node = min(pagerank, key=lambda x: pagerank[x]) stats['pagerank_min_node'] = pagerank_min_node stats['pagerank_min'] = pagerank[pagerank_min_node] # if True, calculate node and edge connectivity if connectivity: start_time = time.time() # node connectivity is the minimum number of nodes that must be removed # to disconnect G or render it trivial stats['node_connectivity'] = nx.node_connectivity(G_strong) # edge connectivity is equal to the minimum number of edges that must be # removed to disconnect G or render it trivial stats['edge_connectivity'] = nx.edge_connectivity(G_strong) log('Calculated node and edge connectivity in {:,.2f} seconds'.format(time.time() - start_time)) # if True, calculate average node connectivity if anc: # mean number of internally node-disjoint paths between each pair of # nodes in G, i.e., the expected number of nodes that must be removed to # disconnect a randomly selected pair of non-adjacent nodes start_time = time.time() stats['node_connectivity_avg'] = nx.average_node_connectivity(G) log('Calculated average node connectivity in {:,.2f} seconds'.format(time.time() - start_time)) # if True, calculate shortest paths, eccentricity, and topological metrics # that use eccentricity if ecc: # precompute shortest paths between all nodes for eccentricity-based # stats start_time = time.time() sp = {source:dict(nx.single_source_dijkstra_path_length(G_strong, source, weight='length')) for source in G_strong.nodes()} log('Calculated shortest path lengths in {:,.2f} seconds'.format(time.time() - start_time)) # eccentricity of a node v is the maximum distance from v to all other # nodes in G eccentricity = nx.eccentricity(G_strong, sp=sp) stats['eccentricity'] = eccentricity # diameter is the maximum eccentricity diameter = nx.diameter(G_strong, e=eccentricity) stats['diameter'] = diameter # radius is the minimum eccentricity radius = nx.radius(G_strong, e=eccentricity) stats['radius'] = radius # center is the set of nodes with eccentricity equal to radius center = nx.center(G_strong, e=eccentricity) stats['center'] = center # periphery is the set of nodes with eccentricity equal to the diameter periphery = nx.periphery(G_strong, e=eccentricity) stats['periphery'] = periphery # if True, calculate node closeness centrality if cc: # closeness centrality of a node is the reciprocal of the sum of the # shortest path distances from u to all other nodes start_time = time.time() closeness_centrality = nx.closeness_centrality(G, distance='length') stats['closeness_centrality'] = closeness_centrality stats['closeness_centrality_avg'] = sum(closeness_centrality.values())/len(closeness_centrality) log('Calculated closeness centrality in {:,.2f} seconds'.format(time.time() - start_time)) # if True, calculate node betweenness centrality if bc: # betweenness centrality of a node is the sum of the fraction of # all-pairs shortest paths that pass through node start_time = time.time() betweenness_centrality = nx.betweenness_centrality(G, weight='length') stats['betweenness_centrality'] = betweenness_centrality stats['betweenness_centrality_avg'] = sum(betweenness_centrality.values())/len(betweenness_centrality) log('Calculated betweenness centrality in {:,.2f} seconds'.format(time.time() - start_time)) log('Calculated extended stats in {:,.2f} seconds'.format(time.time()-full_start_time)) return stats
def test_center(self): assert_equal(set(networkx.center(self.G)),set([6, 7, 10, 11]))
rows and columns. We may also think of a submatrix as formed by deleting the remaining rows and columns from M. Given: An inconsistent character table C on at most 100 taxa. Return: A submatrix of C′ representing a consistent character table on the same taxa and formed by deleting a single row of C. (If multiple solutions exist, you may return any one.) ''' import numpy as np import networkx as nx def reverse_symbol(a): return (a == 0).astype(int) table = open('rosalind_cset.txt').read().split() mat = np.array([list(i.rstrip()) for i in table], dtype=int) n = len(table) G = nx.Graph() for i in range(n-1): for j in range(1, n): a = mat[i] + mat[j] b = mat[i] + reverse_symbol(mat[j]) if 0 in a and 2 in a and 0 in b and 2 in b: G.add_edge(i, j) table.pop(nx.center(G)[0]) open('rosalind_cset_sub.txt', 'wt').write('\n'.join(table))
def step(self, state): """ Determine actions based on the current state of the city. Called every time step. This function must take less than Settings.STEP_TIMEOUT seconds. --- Parameters --- state : State The state of the game. See state.py for more information. --- Returns --- commands : dict list Each command should be generated via self.send_command or self.build_command. The commands are evaluated in order. """ self.current_order_edges = set() graph = state.get_graph() commands = [] if not self.has_built_station: station = max([node for node in nx.center(graph)], key=graph.degree) commands.append(self.build_command(station)) self.stations.append(station) # this one can always be assumed to be built self.has_built_station = True # Check if new station was successfully built if self.new_station is not None and state.get_graph().node[self.new_station]["is_station"]: self.stations.append(self.new_station) self.new_station = None pending_orders = state.get_pending_orders() RATIO = 3 if len(self.stations) < self.max_stations: if len(pending_orders) > sum([graph.degree(station) for station in self.stations]) / RATIO: # New station available_nodes = [node for node in graph.nodes() if node not in self.stations] order_nodes = [o.get_node() for o in pending_orders] def heuristic(n): t = (graph.degree(n), min([nx.shortest_path_length(graph, n, s) for s in self.stations])) # geometric mean of these two # closest to orders return ( -sum([nx.shortest_path_length(graph, n, order_node) for order_node in order_nodes]), (t[0] * t[1]) ** (1 / 2), ) self.new_station = max(available_nodes, key=heuristic) commands.append(self.build_command(self.new_station)) # do not use it yet, check next turn if it was built if len(pending_orders) > 0: # Choose orders to fulfill chosen_orders = sorted(pending_orders, key=lambda k: state.money_from(k)) # Assign each order to closest station # Generate graph of free edges self.available_graph = state.get_graph() self.available_graph.remove_edges_from( [edge for edge in self.available_graph.edges() if self.available_graph.edge[edge[0]][edge[1]]["in_use"]] ) for order in chosen_orders: key = lambda x: Player.shortest_from_station(graph, x, order.get_node()) possible_stations = sorted(self.stations, key=key) # Check each station by order starting from closest for station in possible_stations: if station is None: # dummy, no path actually exists continue try: paths = list(nx.all_shortest_paths(self.available_graph, station, order.get_node())) except nx.NetworkXNoPath: continue # TODO: choose a good path, not just the first one in the list, closest to station/order is best? found = False for path in paths: if self.path_is_valid(state, path): commands.append(self.send_command(order, path)) self.current_order_edges |= set(path) found = True break if found: break return commands
def main (): """ main """ global options, args, pg # TODO: Do something more interesting here... pg = nx.read_gml('/home/cyn/FFHS/NA-15-ZH/PVA3/power.gml') print("Exercise 3:\n---------------------------------------------------") print("Nodes: "), pg.number_of_nodes() print("Edges: "), pg.number_of_edges() graph_degree = pg.degree() print("Degree of Nodes: "), graph_degree print("\nExercise 4:\n---------------------------------------------------") average_degree(pg) print("Degree_histogram list: "), nx.degree_histogram(pg) export_histogram() print("\nExercise 5:\n---------------------------------------------------") max_degree = find_highest_degree(pg) print("Highest degree: "), max_degree print("Node/s with highest degree: "), \ find_nodes_with_degree(pg,max_degree) cc = list(nx.connected_component_subgraphs(pg)) print("Number of CC in the Power-Grid: "), len(cc) print("\nExercise 6:\n---------------------------------------------------") print("Diameter: "), nx.diameter(pg) print("Center: "), nx.center(pg) print("\nExercise 7:\n---------------------------------------------------") subnodes = list() for x in range(10, max_degree+1): if len(find_nodes_with_degree(pg,x)) != 0: subnodes.extend(find_nodes_with_degree(pg,x)) sg = pg.subgraph(subnodes) scc = list(nx.connected_component_subgraphs(sg)) print("Number of CC in Subgraph: "), len(scc) max_cc = 0 largest_cc_id = 0 for x in range(0, len(scc)): if scc[x].number_of_nodes() > max_cc: max_cc = scc[x].number_of_nodes() largest_cc_id = x print("Largest component: "), max_cc nx.draw_spectral(scc[largest_cc_id]) plt.savefig('/home/cyn/FFHS/NA-15-ZH/PVA3/largest_connected_component.png') plt.close() print("\nExercise 8:\n---------------------------------------------------") lg = make_largest_diameter_graph(10) average_degree(lg) print("Center: "), nx.center(lg) nx.draw_spectral(lg) plt.savefig('/home/cyn/FFHS/NA-15-ZH/PVA3/largest_diameter_10.png') plt.close() sdg = make_smallest_diameter_graph(10) average_degree(sdg) print("Center: "), nx.center(sdg) nx.draw_circular(sdg) plt.savefig('/home/cyn/FFHS/NA-15-ZH/PVA3/smallest_diameter_10.png') plt.close()
def test_bound_center(self): assert_equal(set(networkx.center(self.G, usebounds=True)), set([6, 7, 10, 11]))
def find_optimal_tree_root(nx_tree_input): tree_root=nx.center(nx_tree_input) return tree_root[0]
final_graph = {} client = pymongo.MongoClient() db = client.final for val in db.collection_names(): final_graph[int(val)] = load_from_mongo('final', str(val))[0]['reciprocal_friends'] final_graph[24551258] = intersection # Start creating the graph peice by peice. G=nx.from_dict_of_lists(final_graph) pos=nx.spring_layout(G) # positions for all nodes nx.draw_networkx_nodes(G,pos,node_size=3) nx.draw_networkx_edges(G,pos,width=1) nx.draw_networkx_labels(G,pos,font_size=2,font_family='sans-serif') plt.show() print("the number of nodes of the network is " + str(G.size())) print("The diameter of the network is: " + str(nx.diameter(G))) print("The average distance of the network is " + str(nx.center(G)))
def center(net): return setSize(nx.center(net,e=eccentricity_list(net)), net.number_of_nodes(),'center')