本文整理匯總了Python中networkx.ego_graph方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.ego_graph方法的具體用法?Python networkx.ego_graph怎麽用?Python networkx.ego_graph使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.ego_graph方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_hub_vertices
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def get_hub_vertices(self, num):
"""Get account vertices randomly (high-degree vertices are likely selected)
:param num: Number of total account vertices
:return: Account ID list
"""
# if suspicious is None:
# candidates = self.g.nodes()
# else:
# candidates = [n for n in self.g.nodes() if self.g.nodes[n]["suspicious"] == suspicious] # True/False
# candidates = [n for n in candidates if self.factor <= self.degrees[n]]
# degrees = [self.degrees[n] for n in candidates]
# probs = np.array(degrees) / float(sum(degrees))
candidates = set()
while len(candidates) < num:
hub = random.choice(self.hubs)
candidates.update([hub]+self.g.adj[hub].keys()) # candidates.update(nx.ego_graph(self.g, hub).nodes())
return np.random.choice(list(candidates), num, False)
示例2: ego_networks
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def ego_networks(g_original, level=1):
"""
Ego-networks returns overlapping communities centered at each nodes within a given radius.
:param g_original: 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_original, nx.Graph)
coms = []
for n in g.nodes():
coms.append(list(nx.ego_graph(g, n, radius=level).nodes()))
return NodeClustering(coms, g_original, "Ego Network", method_parameters={"level": 1}, overlap=True)
示例3: test_ego
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
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)])
H=nx.ego_graph(G,0,undirected=True)
assert_equal(H.edges(), [(0, 1)])
H=nx.ego_graph(G,0,center=False)
assert_equal(H.edges(), [])
示例4: test_ego
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
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(), [])
示例5: citeseer_ego
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
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
示例6: execute
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def execute(self):
"""
Execute Demon algorithm
"""
for n in self.g.nodes():
self.g.nodes[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())
示例7: _get_egonet_features
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def _get_egonet_features(self) -> pd.DataFrame:
"""
Return egonet features for each node in the graph
"""
egonet_features = {}
for node in self.G.nodes:
ego = nx.ego_graph(self.G, node, radius=1)
ego_boundary = list(nx.edge_boundary(self.G, ego.nodes))
egonet_features[node] = {
'internal_edges': self._get_edge_sum(ego.edges),
'external_edges': self._get_edge_sum(ego_boundary)
}
return pd.DataFrame.from_dict(egonet_features, orient='index')
### helpers ###
示例8: test_ego_distance
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
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='weight',undirected=True)
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])
示例9: test_ego_distance
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
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_nodes_equal(nx.ego_graph(G, 0, radius=3).nodes(), [0, 1, 2, 3])
eg = nx.ego_graph(G, 0, radius=3, distance='weight')
assert_nodes_equal(eg.nodes(), [0, 1])
eg = nx.ego_graph(G, 0, radius=3, distance='weight', undirected=True)
assert_nodes_equal(eg.nodes(), [0, 1])
eg = nx.ego_graph(G, 0, radius=3, distance='distance')
assert_nodes_equal(eg.nodes(), [0, 1, 2])
示例10: local_efficiency
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
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)
示例11: Graph_load
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def Graph_load(dataset = 'cora'):
'''
Load a single graph dataset
:param dataset: dataset name
:return:
'''
names = ['x', 'tx', 'allx', 'graph']
objects = []
for i in range(len(names)):
load = pkl.load(open("dataset/ind.{}.{}".format(dataset, names[i]), 'rb'), encoding='latin1')
# print('loaded')
objects.append(load)
# print(load)
x, tx, allx, graph = tuple(objects)
test_idx_reorder = parse_index_file("dataset/ind.{}.test.index".format(dataset))
test_idx_range = np.sort(test_idx_reorder)
if dataset == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder) + 1)
tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
tx_extended[test_idx_range - min(test_idx_range), :] = tx
tx = tx_extended
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
G = nx.from_dict_of_lists(graph)
adj = nx.adjacency_matrix(G)
return adj, features, G
######### code test ########
# adj, features,G = Graph_load()
# print(adj)
# print(G.number_of_nodes(), G.number_of_edges())
# _,_,G = Graph_load(dataset='citeseer')
# G = max(nx.connected_component_subgraphs(G), key=len)
# G = nx.convert_node_labels_to_integers(G)
#
# count = 0
# max_node = 0
# for i in range(G.number_of_nodes()):
# G_ego = nx.ego_graph(G, i, radius=3)
# # draw_graph(G_ego,prefix='test'+str(i))
# m = G_ego.number_of_nodes()
# if m>max_node:
# max_node = m
# if m>=50:
# print(i, G_ego.number_of_nodes(), G_ego.number_of_edges())
# count += 1
# print('count', count)
# print('max_node', max_node)
示例12: meshedness
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def meshedness(graph, radius=5, name="meshedness", distance=None):
"""
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.
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)):
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)
示例13: mean_node_degree
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def mean_node_degree(graph, radius=5, name="mean_nd", degree="degree", distance=None):
"""
Calculates mean node degree 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
radius defining the extent of subgraph
name : str, optional
calculated attribute name
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.
Returns
-------
Graph
networkx.Graph if radius is set
float
mean node degree for graph if ``radius=None``
Examples
--------
>>> network_graph = mm.mean_node_degree(network_graph, radius=3)
"""
netx = graph.copy()
if radius:
for n in tqdm(netx, total=len(netx)):
sub = nx.ego_graph(
netx, n, radius=radius, distance=distance
) # define subgraph of steps=radius
netx.nodes[n][name] = _mean_node_degree(sub, degree=degree)
return netx
return _mean_node_degree(netx, degree=degree)
示例14: cyclomatic
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def cyclomatic(graph, radius=5, name="cyclomatic", distance=None):
"""
Calculates cyclomatic complexity 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=e-v+1
where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.
Adapted from :cite:`bourdic2012`.
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
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.
Returns
-------
Graph
networkx.Graph if radius is set
float
cyclomatic complexity for graph if ``radius=None``
Examples
--------
>>> network_graph = mm.cyclomatic(network_graph, radius=3)
"""
netx = graph.copy()
if radius:
for n in tqdm(netx, total=len(netx)):
sub = nx.ego_graph(
netx, n, radius=radius, distance=distance
) # define subgraph of steps=radius
netx.nodes[n][name] = _cyclomatic(
sub
) # save value calulated for subgraph to node
return netx
return _cyclomatic(netx)
示例15: edge_node_ratio
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import ego_graph [as 別名]
def edge_node_ratio(graph, radius=5, name="edge_node_ratio", distance=None):
"""
Calculates edge / node ratio 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=e/v
where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.
Adapted from :cite:`dibble2017`.
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
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.
Returns
-------
Graph
networkx.Graph if radius is set
float
edge / node ratio for graph if ``radius=None``
Examples
--------
>>> network_graph = mm.edge_node_ratio(network_graph, radius=3)
"""
netx = graph.copy()
if radius:
for n in tqdm(netx, total=len(netx)):
sub = nx.ego_graph(
netx, n, radius=radius, distance=distance
) # define subgraph of steps=radius
netx.nodes[n][name] = _edge_node_ratio(
sub
) # save value calulated for subgraph to node
return netx
return _edge_node_ratio(netx)