def neighbor_bound(G, v, w, radius): g1 = nx.ego_graph(G, v, radius=radius, undirected=False) g2 = nx.ego_graph(G, w, radius=radius, undirected=False) if len(set(g1.edges()) & set(g2.edges())) > 0: return True else: return False
def node_clique_number(G, nodes=None, cliques=None): """ Returns the size of the largest maximal clique containing each given node. Returns a single or list depending on input nodes. Optional list of cliques can be input if already computed. """ if cliques is None: if nodes is not None: # Use ego_graph to decrease size of graph if isinstance(nodes, list): d = {} for n in nodes: H = nx.ego_graph(G, n) d[n] = max((len(c) for c in find_cliques(H))) else: H = nx.ego_graph(G, nodes) d = max((len(c) for c in find_cliques(H))) return d # nodes is None--find all cliques cliques = list(find_cliques(G)) if nodes is None: nodes = list(G.nodes()) # none, get entire graph if not isinstance(nodes, list): # check for a list v = nodes # assume it is a single value d = max([len(c) for c in cliques if v in c]) else: d = {} for v in nodes: d[v] = max([len(c) for c in cliques if v in c]) return d
def build_activity_graph(activity_uri, activity_id): G = nx.DiGraph() q_activity_to_resource = render_template('activity_to_resource.q', activity_uri = activity_uri) G = build_graph(G, activity_uri, "activity", "concept", q_activity_to_resource) q_resource_to_activity = render_template('resource_to_activity.q', activity_uri = activity_uri) G = build_graph(G, activity_uri, "concept", "activity", q_resource_to_activity) print activity_uri, activity_id # origin_node_id = "{}".format(activity_id.lower()) origin_node_id = activity_id G.node[origin_node_id]['type'] = 'origin' names = {} for n, nd in G.nodes(data=True): if nd['type'] == 'activity' or nd['type'] == 'origin': label = nd['label'].replace('Activity','').upper() names[n] = label else : names[n] = nd['label'] nx.set_node_attributes(G,'label', names) deg = nx.degree(G) nx.set_node_attributes(G,'degree',deg) outG = nx.ego_graph(G,origin_node_id,50) inG = nx.ego_graph(G.reverse(),origin_node_id,50) inG = inG.reverse() sG = nx.compose(outG,inG) assign_weights(sG, []) print sG.edges(data=True) g_json = json_graph.node_link_data(sG) # node-link format to serialize return g_json
def test_ego_distance(self): G=nx.Graph() G.add_edge(0,1,weight=2,distance=1) G.add_edge(1,2,weight=2,distance=2) G.add_edge(2,3,weight=2,distance=1) assert_equal(sorted(nx.ego_graph(G,0,radius=3).nodes()),[0,1,2,3]) eg=nx.ego_graph(G,0,radius=3,distance='weight') assert_equal(sorted(eg.nodes()),[0,1]) eg=nx.ego_graph(G,0,radius=3,distance='distance') assert_equal(sorted(eg.nodes()),[0,1,2])
def neighbor_bound(G, v, w, radius): """ test if the node v and the node w are connected within a radius in graph G """ g1 = nx.ego_graph(G, v, radius=radius, undirected=False) g2 = nx.ego_graph(G, w, radius=radius, undirected=False) if len(set(g1.edges()) & set(g2.edges())) > 0: return True else: return False
def subgraph(G, node_list, radius=0): _graph = nx.ego_graph(G,node_list[0],radius=radius) for node in node_list[1:]: if G.has_node(node): _graph = nx.compose(_graph, nx.ego_graph(G, node, radius=radius)) return _graph
def test_ego(self): G=nx.star_graph(3) H=nx.ego_graph(G,0) assert_true(nx.is_isomorphic(G,H)) G.add_edge(1,11) G.add_edge(2,22) G.add_edge(3,33) H=nx.ego_graph(G,0) assert_true(nx.is_isomorphic(nx.star_graph(3),H)) G=nx.path_graph(3) H=nx.ego_graph(G,0) assert_equal(H.edges(), [(0, 1)])
def extract_ego_graph(G, activity_uri): sG = None inG = None outG = None app.logger.debug(u"Extracting ego graph (forward) {}".format(activity_uri)) outG = nx.ego_graph(G,activity_uri,50) app.logger.debug(u"Extracting ego graph (backward) {}".format(activity_uri)) inG = nx.ego_graph(G.reverse(),activity_uri,50) app.logger.debug(u"Reversing backward ego graph {}".format(activity_uri)) inG = inG.reverse() app.logger.debug(u"Joining ego graphs {}".format(activity_uri)) sG = nx.compose(outG,inG) return sG
def drawGraph(spammers): for i in range(1, ver + 1): if i in spammers: spamTag.append('r') else: spamTag.append('b') nodes = [] for t in range(1, ver + 1): nodes.append(t); G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edges) #G=nx.generators.barabasi_albert_graph(len(nodes),len(edges) # find node with largest degree node_and_degree = G.degree() (largest_hub, degree) = sorted(node_and_degree.items(), key=itemgetter(1))[-1] # Create ego graph of main hub hub_ego = nx.ego_graph(G, largest_hub) # Draw graph pos = nx.spring_layout(hub_ego) nx.draw(hub_ego, pos, node_color=spamTag, node_size=50, with_labels=False) # Draw ego as large and red nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='r') plt.savefig(name+"/"+ name+'_MCLGraph.png') plt.show()
def numCommunitiesEgoCentricNetwork(G, ego): ego_net = nx.ego_graph(G,n) ego_net.remove_node(ego) if len(ego_net.edges()) == 0: return len(ego_net.nodes()) else: return findCommunities(ego_net)
def Similarity(G,asin,amazonBooks,maxnumber): simitems=[] neighbors=(G.neighbors(asin)) #egoNetwork: get_ego_network(coPurchaseGraph, asin, radius = 1) #threshold = median(weights of edges in egoNetwork) ego = networkx.ego_graph(G, asin, radius=1) mediansimilarity =statistics.median([ego[x][asin]['weight'] for x in neighbors ]) similaritydict={} threshold = mediansimilarity # islandGraph: A graph, initialized to null gIslands = networkx.Graph() #create islandGraph with the threshold for f,t,e in ego.edges(data = True): if(e['weight'] > threshold): gIslands.add_edge(f,t,e) nodelist=gIslands.nodes(data = False) for n in nodelist: if(n != asin): if(ego[n][asin]['weight'] == 0): print("error: edge weight is zero") similaritydict[n]=maxnumber else: # Rank the nodes with the Sales Rank as follows # Rank[node] = salesRank/weight similaritydict[n]=(amazonBooks[n]['SalesRank'])/(ego[n][asin]['weight']) #simItems = Sort(Rank) sortedsim=(sorted(similaritydict.items(), key = lambda x:x[1])[:100]) simitems = [x[0] for x in sortedsim] return simitems
def get_weighted_ego_graph(graph, character, hops=1): # Graph and Position ego = nx.ego_graph(graph, character, hops) pos = nx.spring_layout(ego) plt.figure(figsize=(12,12)) plt.axis('off') # Coloration and Configuration ego.node[character]["TYPE"] = "center" valmap = { "hero": 0.0, "center": 1.0 } types = nx.get_node_attributes(ego, "TYPE") values = [valmap.get(types[node], 0.25) for node in ego.nodes()] char_edges = ego.edges(data=True, nbunch=[character,]) nonchar_edges = ego.edges(nbunch=[n for n in ego.nodes() if n != character]) elarge=[(u,v) for (u,v,d) in char_edges if d['weight'] >=0.12] esmall=[(u,v) for (u,v,d) in char_edges if d['weight'] < 0.12] print set([d['weight'] for (u,v,d) in char_edges]) # Draw nx.draw_networkx_nodes(ego, pos, node_size=200, node_color=values, cmap=plt.cm.Paired, with_labels=False) nx.draw_networkx_edges(ego,pos,edgelist=elarge, width=1.5, edge_color='b') nx.draw_networkx_edges(ego,pos,edgelist=esmall, width=1,alpha=0.5,edge_color='b',style='dashed') nx.draw_networkx_edges(ego,pos,edgelist=nonchar_edges, width=0.5,alpha=0.2,style='dashed') plt.show()
def get_ego_graph(graph, character): """ Expecting a graph_from_gdf """ # Graph and Position ego = nx.ego_graph(graph, character, 3) pos = nx.spring_layout(ego) plt.figure(figsize=(12,12)) plt.axis('off') # Coloration and Configuration ego.node[character]["TYPE"] = "center" valmap = { "comic": 0.25, "hero": 0.54, "center": 0.87 } types = nx.get_node_attributes(ego, "TYPE") values = [valmap.get(types[node], 0.25) for node in ego.nodes()] # Draw nx.draw_networkx_edges(ego, pos, alpha=0.4) nx.draw_networkx_nodes(ego, pos, node_size=80, node_color=values, cmap=plt.cm.hot, with_labels=False) #plt.show() plt.savefig("figure/longbow_ego_2hop.png")
def test_ego(self): G = nx.star_graph(3) H = nx.ego_graph(G, 0) assert_true(nx.is_isomorphic(G, H)) G.add_edge(1, 11) G.add_edge(2, 22) G.add_edge(3, 33) H = nx.ego_graph(G, 0) assert_true(nx.is_isomorphic(nx.star_graph(3), H)) G = nx.path_graph(3) H = nx.ego_graph(G, 0) assert_edges_equal(H.edges(), [(0, 1)]) H = nx.ego_graph(G, 0, undirected=True) assert_edges_equal(H.edges(), [(0, 1)]) H = nx.ego_graph(G, 0, center=False) assert_edges_equal(H.edges(), [])
def ego_graph(self, radius=1, types=None, min_degree=None): '''Generate an undirected ego graph around the current entity. :param radius: radius or degree of the ego graph; defaults to 1 :param types: node types to be included in the graph (e.g., restrict to people and organizations only) :param min_degree: optionally filter nodes in the generated ego graph by minimum degree ''' network = network_data() undirected_net = network.to_undirected() # filter network *before* generating ego graph # so we don't get disconnected nodes if types is not None: for n in undirected_net.nodes(): if 'type' not in undirected_net.node[n] or \ undirected_net.node[n]['type'] not in types: undirected_net.remove_node(n) # converted multidigraph to undirected # to make it possible to find all neighbors, # not just outbound connections # (should be a way to get this from a digraph...) eg = nx.ego_graph(undirected_net, self.nx_node_id, radius=radius) if min_degree is not None: return filter_graph(eg, min_degree=min_degree) return eg
def get_triadic_recommendations(self, commid, userid, k): """ Given a graph give neighbor of neighbor recommendations """ # get the ego network of the user 2 step G = self.community_data[commid]['graph'] EG = nx.ego_graph(G, userid, 2) nbrs = [] for n in EG.neighbors(userid): if n != userid: for non in G.neighbors(n): if non != userid and non in self.tsusers: nbrs.append(n) #print "neighbors of neighbors on", nbrs # get neighbors and neighbors of neighbors # that is not you # neighbors = set(EG.neighbors) - set([userid]) #nons = set(neighbors_of_neighbors)-set([userid]) # for reccos = [] for n in nbrs: reason = "neighbor who likes a townsquare member" reccos.append((n, reason)) if len(reccos) >= k: return reccos[0:k] return reccos
def execute(self): """ Execute Demon algorithm """ for n in self.g.nodes(): self.g.node[n]['communities'] = [n] all_communities = {} for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format='Exec: {l_bar}{bar}'): ego_minus_ego = nx.ego_graph(self.g, ego, 1, False) community_to_nodes = self.__overlapping_label_propagation(ego_minus_ego, ego) # merging phase for c in community_to_nodes.keys(): if len(community_to_nodes[c]) > self.min_community_size: actual_community = community_to_nodes[c] all_communities = self.__merge_communities(all_communities, actual_community) # write output on file if self.file_output: with open(self.file_output, "w") as out_file_com: for idc, c in enumerate(all_communities.keys()): out_file_com.write("%d\t%s\n" % (idc, str(sorted(c)))) return list(all_communities.keys())
def get_center_ego(graph): bt = nx.betweenness_centrality(graph) print(bt) for (node, betweenness) in sorted(bt.items(), key=lambda x: x[1], reverse=True): nodes = nx.ego_graph(graph, node).nodes() print(nodes) return nodes
def get_ego_graph(g, name, radius=2): """ retuns ego graph to given radius for given node this is useful for getting similar artists to a given artist that someboy really likes """ return net.ego_graph(g, name, radius)
def ego(keyid): logging.info('Getting ego network for {}'.format(keyid)) ego = nx.ego_graph(G, keyid, undirected=True, radius=2) logging.info('Computing layout') layout = nx.spring_layout(ego) data = json_graph.node_link_data(ego) data['layout'] = [x.tolist() for x in layout.values()] return Response(json.dumps(data), mimetype='application/json')
def visualize_node(graph, node): if type(graph) is not nx.Graph: graph = create_network(graph) hub_ego = nx.ego_graph(graph, node) pos = nx.spring_layout(hub_ego) nx.draw(hub_ego, pos, node_color='b', node_size=900) nx.draw_networkx_nodes(hub_ego, pos, nodelist=[node], node_size=600, node_color='r') plt.show()
def largest_hub_in_graph(G): # find node with largest degree node_and_degree = G.degree() (largest_hub, degree) = sorted(node_and_degree.items(), key=itemgetter(1))[-1] # Create ego graph of main hub hub_ego = nx.ego_graph(G, largest_hub) hub_degree = nx.degree(G, largest_hub) print "largest hub ID: " + str(largest_hub) + "\t" + "largest hub degree: " + str(hub_degree)
def get_ones_net(sn,core_name): try: ones_net=networkx.ego_graph(sn,core_name) print '%s的交往圈有%d人,社交网络为:'%(core_name,len(ones_net)) for node in ones_net.nodes(): print node except Exception as err: print err
def __init__(self, view, controller, use_ego_betw=False, **kwargs): super(CacheLessForMore, self).__init__(view, controller) topology = view.topology() if use_ego_betw: self.betw = dict((v, nx.betweenness_centrality(nx.ego_graph(topology, v))[v]) for v in topology.nodes_iter()) else: self.betw = nx.betweenness_centrality(topology)
def ego_plot(self, radius, name): inter_graph = nx.ego_graph(self.graph_without_self, name, radius = radius) colors = self._color_distance_self(inter_graph, radius, name) figsize(20, 20) nx.draw(inter_graph, node_color = [plt.cm.RdBu(color) for color in colors], alpha = 0.5, edge_color='lightgrey', font_size=10) self._add_legend_self(radius, colors, name) title(name + ' ego graph', size = 20, weight = 'bold') return plt.show()
def DrawRec(secondlist,G,asin): ego = networkx.ego_graph(G, asin, radius=1) pos=networkx.spring_layout(ego) matplotlib.pyplot.figure(figsize=(15,15)) networkx.draw_networkx_nodes(ego,pos,node_color='g',node_size=600,alpha=0.8) networkx.draw_networkx_nodes(ego,pos,nodelist=[asin],node_color='r',node_size=600) networkx.draw_networkx_edges(ego,pos) networkx.draw_networkx_nodes(ego,pos,nodelist=secondlist,node_color='b',node_size=600)
def effective_size(G,n): # This treats directed graphs as undirected # Could be modified to handle directed graphs differently # Ignores weights ndeg=float(G.degree(n)) # number of neighbors (alters) E=nx.ego_graph(G,n,center=False,undirected=True) deg=E.degree() # degree of neighbors not including n # degree of n - average deg of nbrs return ndeg-sum(deg.values())/(ndeg-1.0)
def ego(): ''' This node is deceptively connected because it's from the index (page 750 of volume2.pdf). ''' g_9_56_090 = nx.ego_graph(g, '9.56.090') nx.draw_spring(g_9_56_090) plt.savefig("9.56.090.png") print nodes['9.56.090']
def citeseer_ego(): _, _, G = data.Graph_load(dataset='citeseer') G = max(nx.connected_component_subgraphs(G), key=len) G = nx.convert_node_labels_to_integers(G) graphs = [] for i in range(G.number_of_nodes()): G_ego = nx.ego_graph(G, i, radius=3) if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400): graphs.append(G_ego) return graphs
def create_egonet_features(g): egoNetList = [] for n in nx.nodes_iter(g): resultObj = Result() resultObj.egoNetGraph = nx.ego_graph(g, n, radius=1, center=True, undirected=False, distance=None) resultObj.egoNetDegree = nx.number_of_nodes(resultObj.egoNetGraph) resultObj.nofEdges = nx.number_of_edges(resultObj.egoNetGraph) egoNetList.append(resultObj) # print resultObj return egoNetList
def get_community(G: nx.Graph, n, hops: int, max, maxCore: bool, visited={}, more_metrics=True): e = nx.ego_graph(G, n['id'], hops) # filter here before k-core # # here we filter out the nodes that doesn't # meet the domination requirements # currently we select nodes that have dom > 0 # but this can change to a pruning function community = [ x for x, y in e.nodes(data=True) if (y['dom'] > 0 and y['id'] not in visited) ] community = G.subgraph(community) k_core = nx.k_core(community) max_k_core = min(k_core.degree(), key=lambda x: x[1])[1] if maxCore: res = k_core else: res = community # mark nodes as visited # res = [x for x,y in res.nodes(data=True) if y['id'] not in visited ] # mod = nx_comm.modularity(G, community) data1 = json_graph.node_link_data(res, {"link": "edges"}) data1['stats'] = get_graph_stats(res, max['dom'], max_k_core, more_metrics) data1['stats']['init'] = n['id'] return (data1, res)
def getMaxInOutEdges(G): nodes = G.nodes() max_in = 1 max_out = 1 max_ego = 1 max_ego_out = 1 for node_id in nodes: max_in = max(max_in, G.degree(node_id)) max_out = max(max_out, G.out_degree(node_id)) ego_net = nx.ego_graph(G, node_id) ego_edges = ego_net.number_of_edges() max_ego = max(max_ego, ego_edges) nbrs = nx.neighbors(G, node_id) nbrs_total_edges = 0 for nbr in nbrs: nbrs_total_edges += G.out_degree(nbr) nbrs_total_edges += G.degree(nbr) max_ego_out = max(max_ego_out, nbrs_total_edges - ego_edges) return max_in, max_out, max_ego, max_ego_out
def scan_statistic(mygs, i): """ Computes scan statistic-i on a set of graphs Required Parameters: mygs: - Dictionary of graphs i: - which scan statistic to compute """ ss = OrderedDict() for key in mygs.keys(): g = mygs[key] tmp = np.array(()) for n in g.nodes(): sg = nx.ego_graph(g, n, radius=i) tmp = np.append( tmp, np.sum([ sg.get_edge_data(e[0], e[1])['weight'] for e in sg.edges() ])) ss[key] = tmp return ss
def hopSortDemon(G,epsilon): visitedSequece = computeCentrilityandSort(G) # 存储节点是否该访问的标志 visiteFlag = {} for n in G.nodes(): visiteFlag[n] = False # 所有节点初始化 '找邻居社团,构建超图构成的子图H' allCommunities={} for ego in visitedSequece: if (visiteFlag[ego] == False): ego_minus_ego = nx.ego_graph(G, ego, 1, center=False) ##不包含ego节点,1跳邻居 '访问标志' for n in ego_minus_ego: visiteFlag[n] = True visiteFlag[ego] = True '重叠LPA' community_to_nodes=overlappingLPA(ego_minus_ego,ego) '合并' for id1,com1 in community_to_nodes.items(): allCommunities=absoluteMerge(allCommunities,id1,com1,epsilon) return allCommunities
def ego_networks(g, level=1): """ Ego-networks returns overlapping communities centered at each nodes within a given radius. :param g: a networkx/igraph object :param level: extrac communities with all neighbors of distance<=level from a node. Deafault 1 :return: NodeClustering object :Example: >>> from cdlib import algorithms >>> import networkx as nx >>> G = nx.karate_club_graph() >>> coms = algorithms.ego_networks(G) """ g = convert_graph_formats(g, nx.Graph) coms = [] for n in g.nodes(): coms.append(list(nx.ego_graph(g, n, radius=level).nodes())) return NodeClustering(coms, g, "Ego Network", method_parameters={"level": 1}, overlap=True)
def initialize_item_distribution(self, initial_item_distribution=None): temp_dict = {} if self.item_distribution == 'uniform': items_per_node = self.num_items / self.num_nodes for i in self.G.nodes(): temp_dict[i] = items_per_node elif self.item_distribution == 'direct': out_degs = self.G.out_degree() total = np.sum(out_degs.values()) for i in self.G.nodes(): temp_dict[i] = self.num_items * out_degs[i] / total elif self.item_distribution == 'inverse': out_degs = self.G.out_degree() for i in out_degs: out_degs[i] = (self.num_nodes - 1 - out_degs[i]) / (self.num_nodes - 1) total = np.sum(out_degs.values()) for i in self.G.nodes(): temp_dict[i] = self.num_items * out_degs[i] / total elif self.item_distribution == 'ego': random_node = np.random.choice(self.G.nodes()) ego_graph = nx.ego_graph(self.G, random_node, self.ego_graph_radius) for i in self.G.nodes(): if i in ego_graph.nodes(): temp_dict[i] = 0.7 * self.num_items / len( ego_graph.nodes()) else: temp_dict[i] = 0.3 * self.num_items / ( self.num_nodes - len(ego_graph.nodes())) else: # custom assert initial_item_distribution is not None, "Initial item distribution not provided" temp_dict = initial_item_distribution return temp_dict
def create_sausage_buffer_gdf(G_proj, orig_point, buffer=buffer_local, length=distance, intersection_tolerance = 15): """ Create sausage buffer geodataframe for a sample point Parameters ---------- G_proj : graphml OSM street network graphml orig_point : int the current node to start from buffer : float distance to buffer length : float distance to search intersection_tolerance: float nodes within this distance (in graph’s geometry’s units) will be dissolved into a single intersection Returns ------- subgraph geodataframe """ # locate closest node on network to orig_node = ox.get_nearest_node(G_proj, orig_point, return_dist=True) subgraph_proj = nx.ego_graph(G_proj, orig_node[0], radius=length, distance='length') subgraph_gdf = ox.graph_to_gdfs(subgraph_proj, nodes=False, edges=True, fill_edge_geometry=True) # create buffer polygon geometry to dataframe if len(subgraph_gdf) > 0: subgraph_gdf['geometry'] = subgraph_gdf.geometry.buffer(buffer) #link original node id reference subgraph_gdf['node_id'] = orig_node[0] else: subgraph_gdf['geometry'] = 0 subgraph_gdf['node_id'] = 0 return(subgraph_gdf) #output is smaple point subgraph with buffer polygon geometry and original node id reference
def local_efficiency(G): """Returns the average local efficiency of the graph. The *efficiency* of a pair of nodes in a graph is the multiplicative inverse of the shortest path distance between the nodes. The *local efficiency* of a node in the graph is the average global efficiency of the subgraph induced by the neighbors of the node. The *average local efficiency* is the average of the local efficiencies of each node [1]_. Parameters ---------- G : :class:`networkx.Graph` An undirected graph for which to compute the average local efficiency. Returns ------- float The average local efficiency of the graph. Notes ----- Edge weights are ignored when computing the shortest path distances. See also -------- global_efficiency References ---------- .. [1] Latora, Vito, and Massimo Marchiori. "Efficient behavior of small-world networks." *Physical Review Letters* 87.19 (2001): 198701. <http://dx.doi.org/10.1103/PhysRevLett.87.198701> """ # TODO This summation can be trivially parallelized. return sum(global_efficiency(nx.ego_graph(G, v)) for v in G) / len(G)
def get_component_border_neighborhood_set(networkx_graph, component, k, ego_graph_dict=None): ''' Returns a set containing the nodes in the k-hop border of the specified component component: 1D tensor of node IDs in the component (with possible padding) k: number of hops around the component that is included in the border set ego_graph_dict: dictionary mapping from node id to precomputed ego_graph for the node ''' # First, remove any padding that exists in the component if type(component) is torch.Tensor: component_inds_non_neg = (component != config.PAD_VALUE).nonzero().view(-1) component_set = {int(n) for n in component[component_inds_non_neg]} else: component_set = set(component) # calculate the ego graph for each node in the connected component & take the union of all nodes neighborhood = set() for node in component_set: if ego_graph_dict == None: # if it hasn't already been computed, calculate the ego graph (i.e. induced subgraph of neighbors centered at node with specified radius) ego_g = nx.ego_graph(networkx_graph, node, radius=k).nodes() else: ego_g = ego_graph_dict[ node - 1] #NOTE: nodes in dict were indexed with 0, while our nodes are indexed starting at 1 neighborhood = neighborhood.union(set(ego_g)) # remove from the unioned ego sets all nodes that are actually in the component # this will leave only the nodes that are in the k-hop border, but not in the subgraph component border_nodes = neighborhood.difference(component_set) return border_nodes
def get(self): # get args: # action = request.args.get('action', 0, type=str) focal_node_id_list = request.args.get('focal_node_id_list', '', type=str).split(',') hops = request.args.get('hops', 0, type=int) # node_list = request.args.get('node_list', '', type=str) # if node_list != '': # node_list = json.loads(node_list) # used to keep track of all nodes and their x,y coords of all nodes currently on display # curr_node_pos_dict = request.args.get('curr_node_positions', '', type=str) # if curr_node_pos_dict != '': # curr_node_pos_dict = json.loads(curr_node_pos_dict) # curr_node_list = list(curr_node_pos_dict.keys()) # used to retain current scaling and view position to pass back to client-side (to maintain view) # current_scale = request.args.get('curr_scale') # current_viewPos = request.args.get('curr_viewPos') print('ACTION: HOPS INDUCTION') all_graph_data = Graph.get_graph() node_list = [] print(focal_node_id_list) for node in focal_node_id_list: print('node', node) node_list = node_list + list(nx.ego_graph(all_graph_data, node, radius=hops, center=True, undirected=True, distance=None).nodes) G = all_graph_data.subgraph(node_list) response = graph_to_json(G, focal_node_id_list = focal_node_id_list) return response
def execute(self): """ Execute Demon algorithm """ for n in self.g.nodes(): self.g.node[n]['communities'] = [n] all_communities = {} for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format='Exec: {l_bar}{bar}'): ego_minus_ego = nx.ego_graph(self.g, ego, 1, False) community_to_nodes = self.__overlapping_label_propagation( ego_minus_ego, ego) # merging phase for c in community_to_nodes.keys(): if len(community_to_nodes[c]) > self.min_community_size: actual_community = community_to_nodes[c] all_communities = self.__merge_communities( all_communities, actual_community) if self.file_output is not False: out_file_com = open( "%s/demon_%s_communities.txt" % (self.base, self.epsilon), "w") idc = 0 for c in all_communities.keys(): out_file_com.write("%d\t%s\n" % (idc, str(sorted(c)))) idc += 1 out_file_com.flush() out_file_com.close() else: return all_communities
async def _construct_isochrones(self) -> None: """ TODO: Add docstring """ (ys, xs) = list(zip(*self._facilities)) nodes = osmnx.get_nearest_nodes(self._graph, xs, ys) # Projects the graph to UTM self._graph = osmnx.project_graph(self._graph) # Adds an edge attribute for time in minutes required to traverse each # edge meters_per_minute = TRAVEL_SPEED * 1000 / 60 # km/hour to m/minute for (u, v, k, data) in self._graph.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute # Makes the isochrone polygons for isochrone map self._isochrones = [] for found_node in nodes: subgraph = networkx.ego_graph(self._graph, found_node, radius=self._trip_time, distance='time') node_points = [ Point((data['x'], data['y'])) for (node, data) in subgraph.nodes(data=True) ] bounding_poly = geopandas.GeoSeries( node_points).unary_union.convex_hull self._isochrones.append(bounding_poly) self._clean_isochrones_state() # Causes the `isochrones_constructed` event await self.isochrones_constructed() # Saves data of isochrones await self._save_isochrones()
def divide_local_neighbourhood(mesh, radius): """Divide the mesh into locally connected patches of a given size. All nodes will be assigned to a patches but patches will be overlapping. Parameters ---------- mesh : trimesh.Trimesh radius : float Returns ------- list of sets """ assert isinstance(mesh, tm.Trimesh) assert isinstance(radius, numbers.Number) # Generate a graph for mesh G = mesh.vertex_adjacency_graph # Use Eucledian distance for edge weights edges = np.array(G.edges) e1 = mesh.vertices[edges[:, 0]] e2 = mesh.vertices[edges[:, 1]] dist = np.sqrt(np.sum((e1 - e2)**2, axis=1)) nx.set_edge_attributes(G, dict(zip(G.edges, dist)), name='weight') not_seen = set(G.nodes) patches = [] while not_seen: center = not_seen.pop() sg = nx.ego_graph(G, center, distance='weight', radius=radius) nodes = set(sg.nodes) patches.append(nodes) not_seen -= nodes
def draw_ego_hub(G: Graph, output_name: str) -> None: """ Draws the ego hub. Args: G (Graph): the input graph output_name (string): the output file name """ # From https://networkx.github.io/documentation/latest/auto_examples/drawing/plot_ego_graph.html?highlight=hub node_and_degree = G.degree() (largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1] # Create ego graph of main hub hub_ego = nx.ego_graph(G, largest_hub) # Draw graph pos = nx.spring_layout(hub_ego) nx.draw(hub_ego, pos, node_color='b', node_size=300, with_labels=True) # Draw ego as large and red nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='r') plt.savefig("images/" + output_name + "ego_hub.png") plt.close()
def __call__(self, G, r): from pygrank.algorithms.pagerank import PageRank G = G.to_directed() ranks = PageRank().rank(G, {r: 1}) ranks = {v: ranks[v] / G.degree(v) for v in G} max_grap = 0 threshold = 0 prev_rank = None for v, rank in sorted(ranks.items(), key=lambda item: item[1], reverse=True): if prev_rank is not None: gap = (prev_rank - rank) print(gap) if gap > max_grap: max_grap = gap threshold = rank prev_rank = rank T = nx.DiGraph() T.add_node(r) for u, v in G.edges(): if ranks[u] <= threshold and ranks[v] <= threshold: T.add_edge(u, v) return nx.ego_graph(T, r, radius=1000000)
def create(args): if args.graph_type == 'citeseer': _, _, G = graph_load(args.graph_type) G = max(nx.connected_component_subgraphs(G), key=len) G = nx.convert_node_labels_to_integers(G) graphs = [] for i in range(G.number_of_nodes()): # number of egos = number of nodes # person knowing other person G_ego = nx.ego_graph(G, i, radius=3) if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400): graphs.append(G_ego) args.max_prev_node = 250 elif args.graph_type == 'barabasi': graphs = [] for i in range(100, 200): for j in range(4, 5): for k in range(5): graphs.append(nx.barabasi_albert_graph(i, j)) args.max_prev_node = 130 elif args.graph_type == 'barabasi_small': graphs = [] for i in range(4, 21): for j in range(3, 4): for k in range(10): graphs.append(nx.barabasi_albert_graph(i, j)) args.max_prev_node = 20 return graphs
def ego_nets(graph, radius=3, **kwargs): # color center egos = [] n = graph.num_nodes # A proper deepsnap.G should have nodes indexed from 0 to n-1 for i in range(n): egos.append(nx.ego_graph(graph.G, i, radius=radius)) # relabel egos: keep center node ID, relabel other node IDs G = graph.G.__class__() id_bias = n for i in range(len(egos)): G.add_node(i, **egos[i].nodes(data=True)[i]) for i in range(len(egos)): keys = list(egos[i].nodes) keys.remove(i) id_cur = egos[i].number_of_nodes() - 1 vals = range(id_bias, id_bias + id_cur) id_bias += id_cur mapping = dict(zip(keys, vals)) ego = nx.relabel_nodes(egos[i], mapping, copy=True) G.add_nodes_from(ego.nodes(data=True)) G.add_edges_from(ego.edges(data=True)) graph.G = G graph.node_id_index = torch.arange(len(egos))
def cds_length( graph, radius=5, mode="sum", name="cds_len", degree="degree", length="mm_len", distance=None, verbose=True, ): """ Calculates length of cul-de-sacs for subgraph around each node if radius is set, or for whole graph, if ``radius=None``. Subgraph is generated around each node within set radius. If ``distance=None``, radius will define topological distance, otherwise it uses values in distance attribute. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` radius : int Include all neighbors of distance <= radius from n mode : str (default 'sum') if ``'sum'``, calculate total length, if ``'mean'`` calculate mean length name : str, optional calculated attribute name degree : str name of attribute of node degree (:py:func:`momepy.node_degree`) length : str, optional name of attribute of segment length (geographical) distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n. verbose : bool (default True) if True, shows progress bars in loops and indication of steps Returns ------- Graph networkx.Graph if radius is set float length of cul-de-sacs for graph if ``radius=None`` Examples -------- >>> network_graph = mm.cds_length(network_graph, radius=9, mode='mean') """ # node degree needed beforehand netx = graph.copy() for u, v, k in netx.edges(keys=True): if netx.nodes[u][degree] == 1 or netx.nodes[v][degree] == 1: netx[u][v][k]["cdsbool"] = True else: netx[u][v][k]["cdsbool"] = False if radius: for n in tqdm(netx, total=len(netx), disable=not verbose): sub = nx.ego_graph( netx, n, radius=radius, distance=distance) # define subgraph of steps=radius netx.nodes[n][name] = _cds_length( sub, mode=mode, length=length) # save value calculated for subgraph to node return netx return _cds_length(netx, mode=mode, length=length)
========= Ego Graph ========= Example using the NetworkX ego_graph() function to return the main egonet of the largest hub in a Barabási-Albert network. """ # Author: Drew Conway ([email protected]) from operator import itemgetter import matplotlib.pyplot as plt import networkx as nx if __name__ == '__main__': # Create a BA model graph n = 1000 m = 2 G = networkx.generators.barabasi_albert_graph(n, m) # find node with largest degree node_and_degree = G.degree() (largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1] # Create ego graph of main hub hub_ego = nx.ego_graph(G, largest_hub) # Draw graph pos = nx.spring_layout(hub_ego) nx.draw(hub_ego, pos, node_color='b', node_size=50, with_labels=False) # Draw ego as large and red nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='r') plt.show()
def feature_extraction(G): """Node feature extraction. Parameters ---------- G (nx.Graph): a networkx graph. Returns ------- node_features (float): the Nx7 matrix of node features.""" # necessary data structures node_features = np.zeros(shape=(G.number_of_nodes(), 7)) node_list = sorted(G.nodes()) node_degree_dict = dict(G.degree()) node_clustering_dict = dict(nx.clustering(G)) egonets = {n: nx.ego_graph(G, n) for n in node_list} # node degrees degs = [node_degree_dict[n] for n in node_list] # clustering coefficient clusts = [node_clustering_dict[n] for n in node_list] # average degree of neighborhood neighbor_degs = [ np.mean([node_degree_dict[m] for m in egonets[n].nodes if m != n]) if node_degree_dict[n] > 0 else 0 for n in node_list ] # average clustering coefficient of neighborhood neighbor_clusts = [ np.mean([node_clustering_dict[m] for m in egonets[n].nodes if m != n]) if node_degree_dict[n] > 0 else 0 for n in node_list ] # number of edges in the neighborhood neighbor_edges = [ egonets[n].number_of_edges() if node_degree_dict[n] > 0 else 0 for n in node_list ] # number of outgoing edges from the neighborhood # the sum of neighborhood degrees = 2*(internal edges) + external edges # node_features[:,5] = node_features[:,0] * node_features[:,2] - 2*node_features[:,4] neighbor_outgoing_edges = [ len( [ edge for edge in set.union(*[set(G.edges(j)) for j in egonets[i].nodes]) if not egonets[i].has_edge(*edge) ] ) for i in node_list ] # number of neighbors of neighbors (not in neighborhood) neighbors_of_neighbors = [ len( set([p for m in G.neighbors(n) for p in G.neighbors(m)]) - set(G.neighbors(n)) - set([n]) ) if node_degree_dict[n] > 0 else 0 for n in node_list ] # assembling the features node_features[:, 0] = degs node_features[:, 1] = clusts node_features[:, 2] = neighbor_degs node_features[:, 3] = neighbor_clusts node_features[:, 4] = neighbor_edges node_features[:, 5] = neighbor_outgoing_edges node_features[:, 6] = neighbors_of_neighbors return np.nan_to_num(node_features)
def straightness_centrality( graph, weight="mm_len", normalized=True, name="straightness", radius=None, distance=None, verbose=True, ): """ Calculates the straightness centrality for nodes. .. math:: C_{S}(i)=\\frac{1}{n-1} \\sum_{j \\in V, j \\neq i} \\frac{d_{i j}^{E u}} {d_{i j}} where :math:`\\mathrm{d}^{\\mathrm{E} \\mathrm{u}}_{\\mathrm{ij}}` is the Euclidean distance between nodes `i` and `j` along a straight line. Adapted from :cite:`porta2006`. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` weight : str (default 'mm_len') attribute holding length of edge normalized : bool normalize to number of nodes-1 in connected part (for local straightness is recommended to set to normalized False) name : str, optional calculated attribute name radius: int Include all neighbors of distance <= radius from n distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n during ego_graph generation. verbose : bool (default True) if True, shows progress bars in loops and indication of steps Returns ------- Graph networkx.Graph Examples -------- >>> network_graph = mm.straightness_centrality(network_graph) """ netx = graph.copy() if radius: for n in tqdm(netx, total=len(netx), disable=not verbose): sub = nx.ego_graph( netx, n, radius=radius, distance=distance) # define subgraph of steps=radius netx.nodes[n][name] = _straightness_centrality( sub, weight=weight, normalized=normalized)[n] else: vals = _straightness_centrality(netx, weight=weight, normalized=normalized) nx.set_node_attributes(netx, vals, name) return netx
def betweenness_centrality(graph, name="betweenness", mode="nodes", weight="mm_len", endpoints=True, radius=None, distance=None, normalized=False, verbose=True, **kwargs): """ Calculates the shortest-path betweenness centrality for nodes. Wrapper around ``networkx.betweenness_centrality`` or ``networkx.edge_betweenness_centrality``. Betweenness centrality of a node `v` is the sum of the fraction of all-pairs shortest paths that pass through `v` .. math:: c_B(v) =\\sum_{s,t \\in V} \\frac{\\sigma(s, t|v)}{\\sigma(s, t)} where `V` is the set of nodes, :math:`\\sigma(s, t)` is the number of shortest :math:`(s, t)`-paths, and :math:`\\sigma(s, t|v)` is the number of those paths passing through some node `v` other than `s, t`. If `s = t`, :math:`\\sigma(s, t) = 1`, and if `v` in `{s, t}``, :math:`\\sigma(s, t|v) = 0`. Betweenness centrality of an edge `e` is the sum of the fraction of all-pairs shortest paths that pass through `e` .. math:: c_B(e) =\\sum_{s,t \\in V} \\frac{\\sigma(s, t|e)}{\\sigma(s, t)} where `V` is the set of nodes, :math:`\\sigma(s, t)` is the number of shortest :math:`(s, t)`-paths, and :math:`\\sigma(s, t|e)` is the number of those paths passing through edge `e`. Adapted from :cite:`porta2006`. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` name : str, optional calculated attribute name mode : str, default 'nodes' mode of betweenness calculation. 'node' for node-based, 'edges' for edge-based weight : str (default 'mm_len') attribute holding the weight of edge (e.g. length, angle) radius: int Include all neighbors of distance <= radius from n distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n during ego_graph generation. normalized : bool, optional If True the betweenness values are normalized by `2/((n-1)(n-2))`, where n is the number of nodes in subgraph. verbose : bool (default True) if True, shows progress bars in loops and indication of steps **kwargs kwargs for ``networkx.betweenness_centrality`` or ``networkx.edge_betweenness_centrality`` Returns ------- Graph networkx.Graph Examples -------- >>> network_graph = mm.betweenness_centrality(network_graph) Notes ----- In case of angular betweenness, implementation is based on "Tasos Implementation". """ netx = graph.copy() # has to be Graph not MultiGraph as MG is not supported by networkx2.4 G = nx.Graph() for u, v, k, data in netx.edges(data=True, keys=True): if G.has_edge(u, v): if G[u][v][weight] > netx[u][v][k][weight]: nx.set_edge_attributes(G, {(u, v): data}) else: G.add_edge(u, v, **data) if radius: for n in tqdm(G, total=len(G), disable=not verbose): sub = nx.ego_graph( G, n, radius=radius, distance=distance) # define subgraph of steps=radius netx.nodes[n][name] = nx.betweenness_centrality( sub, weight=weight, normalized=normalized, **kwargs)[n] elif mode == "nodes": vals = nx.betweenness_centrality(G, weight=weight, endpoints=endpoints, **kwargs) nx.set_node_attributes(netx, vals, name) elif mode == "edges": vals = nx.edge_betweenness_centrality(G, weight=weight, **kwargs) for u, v, k in netx.edges(keys=True): try: val = vals[u, v] except KeyError: val = vals[v, u] netx[u][v][k][name] = val else: raise ValueError( "Mode {} is not supported. Use 'nodes' or 'edges'.".format(mode)) return netx
def closeness_centrality(graph, name="closeness", weight="mm_len", radius=None, distance=None, verbose=True, **kwargs): """ Calculates the closeness centrality for nodes. Wrapper around ``networkx.closeness_centrality``. Closeness centrality of a node `u` is the reciprocal of the average shortest path distance to `u` over all `n-1` nodes within reachable nodes. .. math:: C(u) = \\frac{n - 1}{\\sum_{v=1}^{n-1} d(v, u)}, where :math:`d(v, u)` is the shortest-path distance between :math:`v` and :math:`u`, and :math:`n` is the number of nodes that can reach :math:`u`. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` name : str, optional calculated attribute name weight : str (default 'mm_len') attribute holding the weight of edge (e.g. length, angle) radius: int Include all neighbors of distance <= radius from n distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n during ego_graph generation. verbose : bool (default True) if True, shows progress bars in loops and indication of steps **kwargs kwargs for ``networkx.closeness_centrality`` Returns ------- Graph networkx.Graph Examples -------- >>> network_graph = mm.closeness_centrality(network_graph) """ netx = graph.copy() if radius: lengraph = len(netx) for n in tqdm(netx, total=len(netx), disable=not verbose): sub = nx.ego_graph( netx, n, radius=radius, distance=distance) # define subgraph of steps=radius netx.nodes[n][name] = _closeness_centrality(sub, n, length=weight, len_graph=lengraph) else: vals = nx.closeness_centrality(netx, distance=weight, **kwargs) nx.set_node_attributes(netx, vals, name) return netx
def meshedness(graph, radius=5, name="meshedness", distance=None, verbose=True): """ Calculates meshedness for subgraph around each node if radius is set, or for whole graph, if ``radius=None``. Subgraph is generated around each node within set radius. If ``distance=None``, radius will define topological distance, otherwise it uses values in distance attribute. .. math:: \\alpha=\\frac{e-v+1}{2 v-5} where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph. Adapted from :cite:`feliciotti2018`. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` radius: int, optional Include all neighbors of distance <= radius from n name : str, optional calculated attribute name distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n. verbose : bool (default True) if True, shows progress bars in loops and indication of steps Returns ------- Graph networkx.Graph if radius is set float meshedness for graph if ``radius=None`` Examples -------- >>> network_graph = mm.meshedness(network_graph, radius=800, distance='edge_length') """ netx = graph.copy() if radius: for n in tqdm(netx, total=len(netx), disable=not verbose): sub = nx.ego_graph( netx, n, radius=radius, distance=distance) # define subgraph of steps=radius netx.nodes[n][name] = _meshedness( sub) # save value calulated for subgraph to node return netx return _meshedness(netx)
def proportion( graph, radius=5, three=None, four=None, dead=None, degree="degree", distance=None, verbose=True, ): """ Calculates the proportion of intersection types for subgraph around each node if radius is set, or for whole graph, if ``radius=None``. Subgraph is generated around each node within set radius. If ``distance=None``, radius will define topological distance, otherwise it uses values in ``distance`` attribute. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` radius: int Include all neighbors of distance <= radius from n three : str, optional attribute name for 3-way intersections proportion four : str, optional attribute name for 4-way intersections proportion dead : str, optional attribute name for deadends proportion degree : str name of attribute of node degree (:py:func:`momepy.node_degree`) distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n. verbose : bool (default True) if True, shows progress bars in loops and indication of steps Returns ------- Graph networkx.Graph if radius is set dict dict with proportions for graph if ``radius=None`` Examples -------- >>> network_graph = mm.proportion(network_graph, three='threeway', four='fourway', dead='deadends') # noqa """ if not three and not four and not dead: raise ValueError( "Nothing to calculate. Define names for at least one proportion to be " "calculated.") netx = graph.copy() if radius: for n in tqdm(netx, total=len(netx), disable=not verbose): sub = nx.ego_graph( netx, n, radius=radius, distance=distance) # define subgraph of steps=radius counts = _proportion(sub, degree=degree) if three: netx.nodes[n][three] = counts[3] / len(sub) if four: netx.nodes[n][four] = counts[4] / len(sub) if dead: netx.nodes[n][dead] = counts[1] / len(sub) return netx # add example to docs explaining keys counts = _proportion(netx, degree=degree) result = {} if three: result[three] = counts[3] / len(netx) if four: result[four] = counts[4] / len(netx) if dead: result[dead] = counts[1] / len(netx) return result
def subgraph( graph, radius=5, distance=None, meshedness=True, cds_length=True, mode="sum", degree="degree", length="mm_len", mean_node_degree=True, proportion={ 3: True, 4: True, 0: True }, cyclomatic=True, edge_node_ratio=True, gamma=True, local_closeness=True, closeness_weight=None, verbose=True, ): """ Calculates all subgraph-based characters. Generating subgraph might be a time consuming activity. If we want to use the same subgraph for more characters, ``subgraph`` allows this by generating subgraph and then analysing it using selected options. Parameters ---------- graph : networkx.Graph Graph representing street network. Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx` radius: int radius defining the extent of subgraph distance : str, optional Use specified edge data key as distance. For example, setting ``distance=’weight’`` will use the edge ``weight`` to measure the distance from the node n. meshedness : bool, default True Calculate meshedness (True/False) cds_length : bool, default True Calculate cul-de-sac length (True/False) mode : str (defualt 'sum') if ``'sum'``, calculate total cds_length, if ``'mean'`` calculate mean cds_length degree : str name of attribute of node degree (:py:func:`momepy.node_degree`) length : str, default `mm_len` name of attribute of segment length (geographical) mean_node_degree : bool, default True Calculate mean node degree (True/False) proportion : dict, default {3: True, 4: True, 0: True} Calculate proportion {3: True/False, 4: True/False, 0: True/False} cyclomatic : bool, default True Calculate cyclomatic complexity (True/False) edge_node_ratio : bool, default True Calculate edge node ratio (True/False) gamma : bool, default True Calculate gamma index (True/False) local_closeness : bool, default True Calculate local closeness centrality (True/False) closeness_weight : str, optional Use the specified edge attribute as the edge distance in shortest path calculations in closeness centrality algorithm verbose : bool (default True) if True, shows progress bars in loops and indication of steps Returns ------- Graph networkx.Graph Examples -------- >>> network_graph = mm.subgraph(network_graph) """ netx = graph.copy() for n in tqdm(netx, total=len(netx), disable=not verbose): sub = nx.ego_graph( netx, n, radius=radius, distance=distance) # define subgraph of steps=radius if meshedness: netx.nodes[n]["meshedness"] = _meshedness(sub) if cds_length: for u, v, k in netx.edges(keys=True): if netx.nodes[u][degree] == 1 or netx.nodes[v][degree] == 1: netx[u][v][k]["cdsbool"] = True else: netx[u][v][k]["cdsbool"] = False netx.nodes[n]["cds_length"] = _cds_length(sub, mode=mode, length=length) if mean_node_degree: netx.nodes[n]["mean_node_degree"] = _mean_node_degree( sub, degree=degree) if proportion: counts = _proportion(sub, degree=degree) if proportion[3]: netx.nodes[n]["proportion_3"] = counts[3] / len(sub) if proportion[4]: netx.nodes[n]["proportion_4"] = counts[4] / len(sub) if proportion[0]: netx.nodes[n]["proportion_0"] = counts[1] / len(sub) if cyclomatic: netx.nodes[n]["cyclomatic"] = _cyclomatic(sub) if edge_node_ratio: netx.nodes[n]["edge_node_ratio"] = _edge_node_ratio(sub) if gamma: netx.nodes[n]["gamma"] = _gamma(sub) if local_closeness: lengraph = len(netx) netx.nodes[n]["local_closeness"] = _closeness_centrality( sub, n, length=closeness_weight, len_graph=lengraph) return netx
def calc_sp_pop_intect_density_multi(G_proj, hexes, distance, rows, node, index): """ Calculate population and intersection density for each sample point This function is for multiprocessing. A subnetwork will be created for each sample point as a neighborhood and then intersect the hexes with pop and intersection data. Population and intersection density for each sample point are caculated by averaging the intersected hexes density data Parameters ---------- G_proj: networkx multidigraph hexes: GeoDataFrame hexagon layers containing pop and intersection info distance: int distance to search around the place geometry, in meters rows: int the number of rows to loop node: list the list of osmid of nodes index: int loop number Returns ------- list """ if index % 100 == 0: print("{0} / {1}".format(index, rows)) # create subgraph of neighbors centered at a node within a given radius. subgraph_proj = nx.ego_graph(G_proj, node, radius=distance, distance="length") # convert subgraph into edge GeoDataFrame try: subgraph_gdf = ox.graph_to_gdfs(subgraph_proj, nodes=False, edges=True, fill_edge_geometry=True) # intersect GeoDataFrame with hexes if len(subgraph_gdf) > 0: intersections = gpd.sjoin(hexes, subgraph_gdf, how="inner", op="intersects") # drop all rows where 'index_right' is nan intersections = intersections[ intersections["index_right"].notnull()] # remove rows where 'index' is duplicate intersections = intersections.drop_duplicates(subset=["index"]) # return list of nodes with osmid, pop and intersection density return [ node, float(intersections["pop_per_sqkm"].mean()), float(intersections["intersections_per_sqkm"].mean()), ] else: return [node] except ValueError as e: return [node]
k_neighbors = DG.neighbors(k) #k 的所有邻居 k_neighbors.append(k) j_and_k = set(j_neighbors) & set(k_neighbors) # 交集 j_or_k = set(j_neighbors) | set(k_neighbors) #并集 S = float(len(j_and_k)) / len(j_or_k) print '两条边的相似度为', S G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (2, 3), (4, 5), (2, 4), (5, 8), (2, 8), (8, 9), (9, 10), (9, 11)]) #图 pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True) plt.show() print '输入节点的值,并显示节点对应的ego网络图' l = input() if l in G.nodes(): node_ego = nx.ego_graph(G, l) #自我中心节点 DG = nx.Graph(node_ego) #节点l的ego网络图 nx.draw(DG, pos, with_labels=True) plt.show() while True: print '请输入两条边的三个节点' i = input() j = input() k = input() if (i, j) and (i, k) in DG.edges(): similarity(i, j, k) break else: print '请重新输入边'
print ("--------------------------------------------------------------") purchasedAsin = '0805047905' # Let's first get some metadata associated with this book print ("ASIN = ", purchasedAsin) print ("Title = ", amazonBooks[purchasedAsin]['Title']) print ("SalesRank = ", amazonBooks[purchasedAsin]['SalesRank']) print ("TotalReviews = ", amazonBooks[purchasedAsin]['TotalReviews']) print ("AvgRating = ", amazonBooks[purchasedAsin]['AvgRating']) print ("DegreeCentrality = ", amazonBooks[purchasedAsin]['DegreeCentrality']) print ("ClusteringCoeff = ", amazonBooks[purchasedAsin]['ClusteringCoeff']) # (1) # Get the depth-1 ego network of purchasedAsin from copurchaseGraph, # and assign the resulting graph to purchasedAsinEgoGraph. purchasedAsinEgoGraph = networkx.ego_graph(copurchaseGraph,purchasedAsin,radius=1) # (2) # Use the island method on purchasedAsinEgoGraph to only retain edges with # threshold >= 0.5, and assign resulting graph to purchasedAsinEgoTrimGraph threshold = 0.5 purchasedAsinEgoTrimGraph = networkx.Graph() # get the weight weightNodeDict={} for fnode, tnode, edge in purchasedAsinEgoGraph.edges(data=True): if edge['weight'] >= threshold: purchasedAsinEgoTrimGraph.add_edge(fnode,tnode,edge=edge['weight']) if (fnode==purchasedAsin):
def effective_size(G, nodes=None, weight=None): r"""Returns the effective size of all nodes in the graph ``G``. The *effective size* of a node's ego network is based on the concept of redundancy. A person's ego network has redundancy to the extent that her contacts are connected to each other as well. The nonredundant part of a person's relationships it's the effective size of her ego network [1]_. Formally, the effective size of a node `u`, denoted `e(u)`, is defined by .. math:: e(u) = \sum_{v \in N(u) \setminus \{u\}} \left(1 - \sum_{w \in N(v)} p_{uw} m_{vw}\right) where `N(u)` is the set of neighbors of `u` and :math:`p_{uw}` is the normalized mutual weight of the (directed or undirected) edges joining `u` and `v`, for each vertex `u` and `v` [1]_. And :math:`m_{vw}` is the mutual weight of `v` and `w` divided by `v` highest mutual weight with any of its neighbors. The *mutual weight* of `u` and `v` is the sum of the weights of edges joining them (edge weights are assumed to be one if the graph is unweighted). For the case of unweighted and undirected graphs, Borgatti proposed a simplified formula to compute effective size [2]_ .. math:: e(u) = n - \frac{2t}{n} where `t` is the number of ties in the ego network (not including ties to ego) and `n` is the number of nodes (excluding ego). Parameters ---------- G : NetworkX graph The graph containing ``v``. Directed graphs are treated like undirected graphs when computing neighbors of ``v``. nodes : container, optional Container of nodes in the graph ``G``. weight : None or string, optional If None, all edge weights are considered equal. Otherwise holds the name of the edge attribute used as weight. Returns ------- dict Dictionary with nodes as keys and the constraint on the node as values. Notes ----- Burt also defined the related concept of *efficency* of a node's ego network, which is its effective size divided by the degree of that node [1]_. So you can easily compute efficencty: >>> G = nx.DiGraph() >>> G.add_edges_from([(0, 1), (0, 2), (1, 0), (2, 1)]) >>> esize = nx.effective_size(G) >>> efficency = {n: v / G.degree(n) for n, v in esize.items()} See also -------- constraint References ---------- .. [1] Burt, Ronald S. *Structural Holes: The Social Structure of Competition.* Cambridge: Harvard University Press, 1995. .. [2] Borgatti, S. "Structural Holes: Unpacking Burt's Redundancy Measures" CONNECTIONS 20(1):35-38. http://www.analytictech.com/connections/v20(1)/holes.htm """ def redundancy(G, u, v, weight=None): nmw = normalized_mutual_weight r = sum( nmw(G, u, w, weight=weight) * nmw(G, v, w, norm=max, weight=weight) for w in set(nx.all_neighbors(G, u))) return 1 - r effective_size = {} if nodes is None: nodes = G # Use Borgatti's simplified formula for unweighted and undirected graphs if not G.is_directed() and weight is None: for v in G: # Effective size is not defined for isolated nodes if len(G[v]) == 0: effective_size[v] = float('nan') continue E = nx.ego_graph(G, v, center=False, undirected=True) effective_size[v] = len(E) - (2 * E.size()) / len(E) else: for v in G: # Effective size is not defined for isolated nodes if len(G[v]) == 0: effective_size[v] = float('nan') continue effective_size[v] = sum( redundancy(G, v, u, weight) for u in set(nx.all_neighbors(G, v))) return effective_size