本文整理汇总了Python中networkx.connected_components方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.connected_components方法的具体用法?Python networkx.connected_components怎么用?Python networkx.connected_components使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.connected_components方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _max_common_subgraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def _max_common_subgraph(GA, GB, pairings):
matches = dict([(i, j) for i, j in enumerate(pairings)])
node_ids = []
for i, j in GA.edges():
ii = matches[i]
jj = matches[j]
li = GA.node[i]['label']
lii = GB.node[ii]['label']
lj = GA.node[j]['label']
ljj = GB.node[jj]['label']
if ((ii, jj) in GB.edges() or (jj, ii) in GB.edges()) and li == lii and lj == ljj:
node_ids.append(ii)
node_ids.append(jj)
G = nx.subgraph(GB, node_ids)
cc = nx.connected_components(G)
return cc, G
示例2: _radial_behind
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def _radial_behind(self, home_node, behind_node):
"""Detect what nodes create a radial string behind the edge from
home_node to behind_node"""
base_islands = nx.number_connected_components(self.dispG)
# If we remove the edge in question, it should radialize the system
# and we can then detect the side to remove
G = nx.Graph()
G.add_nodes_from(self.dispG.nodes())
G.add_edges_from(self.dispG.edges())
G.remove_edge(home_node, behind_node)
node_sets = list(nx.connected_components(G))
if len(node_sets) == base_islands:
# There is no radial path behind this node
return None
else:
for ns in node_sets:
if behind_node in ns:
# We know know what nodes to remove from the display graph
# to remove the radial string
return ns
示例3: graph_diameter
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def graph_diameter(variables, relations):
"""
Compute the graph diameter(s).
If the graph contains several independent sub graph, returns a list the
diamater of each of the subgraphs.
:param variables:
:param relations:
:return:
"""
diams = []
g = as_networkx_graph(variables, relations)
components = (g.subgraph(c).copy() for c in nx.connected_components(g))
for c in components:
diams.append(nx.diameter(c))
return diams
示例4: _create_egonet
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def _create_egonet(self, node):
"""
Creating an ego net, extracting personas and partitioning it.
Args:
node: Node ID for egonet (ego node).
"""
ego_net_minus_ego = self.graph.subgraph(self.graph.neighbors(node))
components = {i: n for i, n in enumerate(nx.connected_components(ego_net_minus_ego))}
new_mapping = {}
personalities = []
for k, v in components.items():
personalities.append(self.index)
for other_node in v:
new_mapping[other_node] = self.index
self.index = self.index+1
self.components[node] = new_mapping
self.personalities[node] = personalities
示例5: _create_egonet
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def _create_egonet(self, node):
"""
Creating an ego net, extracting personas and partitioning it.
Arg types:
* **node** *(int)* - Node ID for ego-net (ego node).
"""
ego_net_minus_ego = self.graph.subgraph(self.graph.neighbors(node))
components = {i: n for i, n in enumerate(nx.connected_components(ego_net_minus_ego))}
new_mapping = {}
personalities = []
for k, v in components.items():
personalities.append(self.index)
for other_node in v:
new_mapping[other_node] = self.index
self.index = self.index+1
self.components[node] = new_mapping
self.personalities[node] = personalities
示例6: rectify_labels
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def rectify_labels(G, labels):
# Ensure labels are rebased and
# are different between different connected compoments
graph = G.copy()
node_to_annot_idx = nx.get_node_attributes(graph, 'annot_idx')
cut_edges = []
for u, v in graph.edges():
idx1 = node_to_annot_idx[u]
idx2 = node_to_annot_idx[v]
if labels[idx1] != labels[idx2]:
cut_edges.append((u, v))
graph.remove_edges_from(cut_edges)
ccs_nodes = list(nx.connected_components(graph))
ccs_idxs = ut.unflat_take(node_to_annot_idx, ccs_nodes)
# Make consistent sorting
ccs_idxs = [sorted(idxs) for idxs in ccs_idxs]
ccs_idxs = ut.sortedby(ccs_idxs, ut.take_column(ccs_idxs, 0))
labels = ut.ungroup([[c] * len(x) for c, x in enumerate(ccs_idxs)], ccs_idxs)
labels = np.array(labels)
return labels
示例7: unconstrained_one_edge_augmentation
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def unconstrained_one_edge_augmentation(G):
"""Finds the smallest set of edges to connect G.
This is a variant of the unweighted MST problem.
If G is not empty, a feasible solution always exists.
Example
-------
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
>>> G.add_nodes_from([6, 7, 8])
>>> sorted(unconstrained_one_edge_augmentation(G))
[(1, 4), (4, 6), (6, 7), (7, 8)]
"""
ccs1 = list(nx.connected_components(G))
C = collapse(G, ccs1)
# When we are not constrained, we can just make a meta graph tree.
meta_nodes = list(C.nodes())
# build a path in the metagraph
meta_aug = list(zip(meta_nodes, meta_nodes[1:]))
# map that path to the original graph
inverse = defaultdict(list)
for k, v in C.graph['mapping'].items():
inverse[v].append(k)
for mu, mv in meta_aug:
yield (inverse[mu][0], inverse[mv][0])
示例8: _high_degree_components
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def _high_degree_components(G, k):
"""Helper for filtering components that cant be k-edge-connected.
Removes and generates each node with degree less than k. Then generates
remaining components where all nodes have degree at least k.
"""
# Iteravely remove parts of the graph that are not k-edge-connected
H = G.copy()
singletons = set(_low_degree_nodes(H, k))
while singletons:
# Only search neighbors of removed nodes
nbunch = set(it.chain.from_iterable(map(H.neighbors, singletons)))
nbunch.difference_update(singletons)
H.remove_nodes_from(singletons)
for node in singletons:
yield {node}
singletons = set(_low_degree_nodes(H, k, nbunch))
# Note: remaining connected components may not be k-edge-connected
if G.is_directed():
for cc in nx.strongly_connected_components(H):
yield cc
else:
for cc in nx.connected_components(H):
yield cc
示例9: positive_components
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def positive_components(infr, graph=None):
r"""
Generates the positive connected compoments (PCCs) in the graph
These will contain both consistent and inconsinstent PCCs.
Yields:
cc: set: nodes within the PCC
"""
pos_graph = infr.pos_graph
if graph is None or graph is infr.graph:
ccs = pos_graph.connected_components()
else:
unique_labels = {
pos_graph.node_label(node) for node in graph.nodes()}
ccs = (pos_graph.connected_to(node) for node in unique_labels)
for cc in ccs:
yield cc
示例10: _create_egonet
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def _create_egonet(self, node):
"""
Creating an ego net, extracting personas and partitioning it.
Args:
node: Node ID for egonet (ego node).
"""
ego_net_minus_ego = self.graph.subgraph(self.graph.neighbors(node))
components = {i: n for i, n in enumerate(nx.connected_components(ego_net_minus_ego))}
new_mapping = {}
personalities = []
for k, v in components.items():
personalities.append(self.index)
for other_node in v:
new_mapping[other_node] = self.index
self.index = self.index+1
self.components[node] = new_mapping
self.personalities[node] = personalities
示例11: visualize_frags
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def visualize_frags(outdir, graphs, options):
from rpy2.robjects import r
utilities.ensure_dir(outdir)
for i, graph in enumerate(graphs):
r.pdf(os.path.join(outdir, "fragments.cluster_{}.pdf".format(i)))
for component in networkx.connected_components(graph):
subgraph = graph.subgraph(component)
ends = [node for node,degree in subgraph.degree_iter() if degree==1]
breakends = [node for node in list(networkx.shortest_simple_paths(subgraph, ends[0], ends[1]))[0]]
# breakends = [breakend_from_label(node) for node in breakends]
breakends = breakends[:-1:2] + breakends[-1:]
# print ")"*100, breakends
for sample, dataset in sorted(options.iter_10xdatasets()):
plot_frags(breakends, options, sample, dataset)
# plot_frags(breakpoints, options, sample, dataset)
r["dev.off"]()
示例12: dendritic_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def dendritic_graph(self):
"""
Builds skeleton of the topological representation (used internally)
"""
diam = networkx.diameter(self.gl)
g3 = networkx.Graph()
dicdend = {}
for n in range(diam-1):
nodedist = []
for k in self.pl:
dil = networkx.shortest_path_length(self.gl, self.root, k)
if dil == n:
nodedist.append(str(k))
g2 = self.gl.subgraph(nodedist)
dicdend[n] = sorted(networkx.connected_components(g2))
for n2, yu in enumerate(dicdend[n]):
g3.add_node(str(n) + '_' + str(n2))
if n > 0:
for n3, yu2 in enumerate(dicdend[n-1]):
if networkx.is_connected(self.gl.subgraph(list(yu)+list(yu2))):
g3.add_edge(str(n) + '_' + str(n2), str(n-1) + '_' + str(n3))
return g3, dicdend
示例13: findSubtours
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def findSubtours(self, checkonly, sol):
EPS = 1.e-6
edges = []
x = self.model.data
for (i, j) in x:
if self.model.getSolVal(sol, x[i, j]) > EPS:
edges.append((i,j))
G = networkx.Graph()
G.add_edges_from(edges)
Components = list(networkx.connected_components(G))
if len(Components) == 1:
return False
elif checkonly:
return True
for S in Components:
self.model.addCons(quicksum(x[i, j] for i in S for j in S if j > i) <= len(S) - 1)
print("cut: len(%s) <= %s" % (S, len(S) - 1))
return True
示例14: assign_cc
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def assign_cc(DG,max_cc_size=sys.maxsize):
#CC=list(nx.connected_components(nx.Graph(DG)))
#for cc in CC:
# remove_outsider_nodes_from_cc(DG,cc)
# recompute CC after having removed outsiders from original CCs
# assign each node to its cc_id
CC=list(nx.connected_components(nx.Graph(DG)))
cc_id=0
for cc in CC:
cc_id +=1
if len(cc) > max_cc_size:
# print ("remove nodes from too large", len(cc) )
for node_id in cc:
DG.remove_node(node_id)
continue
for node_id in cc:
DG.nodes[node_id]['cc_id'] = cc_id
示例15: Tab_split
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_components [as 别名]
def Tab_split(self):
UG1 = self._Callinout.fcgnx_class_level.to_undirected(reciprocal=False)
nodelist = list(nx.connected_components(UG1))
#for i in nodelist:
# print i
threshold = 5 #from 5 to 10
del UG1
max_nodes = max([len(i) for i in nodelist])
if max_nodes < threshold or Global.WHOLE_PROGRAM_ANALYSIS:
#not split
t = []
for i in nodelist:
t = list(t) + list(i)
self.new_nodelist = t
self.subgraph_num = 1
else:
self.new_nodelist = [ i for i in nodelist if len(i) >= threshold ]
self.subgraph_num = len(self.new_nodelist)
# this part is to find the major components