本文整理汇总了Python中networkx.connected_component_subgraphs方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.connected_component_subgraphs方法的具体用法?Python networkx.connected_component_subgraphs怎么用?Python networkx.connected_component_subgraphs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.connected_component_subgraphs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: caveman_special
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def caveman_special(c=2,k=20,p_path=0.1,p_edge=0.3):
p = p_path
path_count = max(int(np.ceil(p * k)),1)
G = nx.caveman_graph(c, k)
# remove 50% edges
p = 1-p_edge
for (u, v) in list(G.edges()):
if np.random.rand() < p and ((u < k and v < k) or (u >= k and v >= k)):
G.remove_edge(u, v)
# add path_count links
for i in range(path_count):
u = np.random.randint(0, k)
v = np.random.randint(k, k * 2)
G.add_edge(u, v)
G = max(nx.connected_component_subgraphs(G), key=len)
return G
示例2: getNetworkGraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def getNetworkGraph(segments,segmentlengths):
"""
Builds a networkx graph from the network file, inluding segment length taken from arcpy.
It selects the largest connected component of the network (to prevent errors from routing between unconnected parts)
"""
#generate the full network path for GDAL to be able to read the file
path =str(os.path.join(arcpy.env.workspace,segments))
print path
if arcpy.Exists(path):
g = nx.read_shp(path)
#This selects the largest connected component of the graph
sg = list(nx.connected_component_subgraphs(g.to_undirected()))[0]
print "graph size (excluding unconnected parts): "+str(len(g))
# Get the length for each road segment and append it as an attribute to the edges in the graph.
for n0, n1 in sg.edges():
oid = sg[n0][n1]["OBJECTID"]
sg[n0][n1]['length'] = segmentlengths[oid]
return sg
else:
print "network file not found on path: "+path
示例3: get_seed_scaffold
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def get_seed_scaffold():
g_idx = 1
seed_scaffolds = {} #this stores initial long scaffolds
to_merge = set()
for subg in nx.connected_component_subgraphs(G):
p = []
for node in subg.nodes():
if subg.degree(node) == 1:
p.append(node)
#If this is 2 then we have found the path!
if len(p) == 2:
path = nx.shortest_path(subg,p[0],p[1])
seed_scaffolds[g_idx] = path
g_idx += 1
#else try to insert these contigs in the long scaffolds generated previously
else:
for node in subg.nodes():
to_merge.add(node.split(':')[0])
return seed_scaffolds, to_merge
示例4: n_community
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def n_community(c_sizes, p_inter=0.01):
graphs = [nx.gnp_random_graph(c_sizes[i], 0.7, seed=i) for i in range(len(c_sizes))]
G = nx.disjoint_union_all(graphs)
communities = list(nx.connected_component_subgraphs(G))
for i in range(len(communities)):
subG1 = communities[i]
nodes1 = list(subG1.nodes())
for j in range(i+1, len(communities)):
subG2 = communities[j]
nodes2 = list(subG2.nodes())
has_inter_edge = False
for n1 in nodes1:
for n2 in nodes2:
if np.random.rand() < p_inter:
G.add_edge(n1, n2)
has_inter_edge = True
if not has_inter_edge:
G.add_edge(nodes1[0], nodes2[0])
#print('connected comp: ', len(list(nx.connected_component_subgraphs(G))))
return G
示例5: ensure_names_are_connected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def ensure_names_are_connected(graph, aids_list):
aug_graph = graph.copy().to_undirected()
orig_edges = aug_graph.edges()
unflat_edges = [list(itertools.product(aids, aids)) for aids in aids_list]
aid_pairs = [tup for tup in ut.iflatten(unflat_edges) if tup[0] != tup[1]]
new_edges = ut.setdiff_ordered(aid_pairs, aug_graph.edges())
preweighted_edges = nx.get_edge_attributes(aug_graph, 'weight')
if preweighted_edges:
orig_edges = ut.setdiff(orig_edges, list(preweighted_edges.keys()))
aug_graph.add_edges_from(new_edges)
# Ensure the largest possible set of original edges is in the MST
nx.set_edge_attributes(aug_graph, name='weight', values=dict([(edge, 1.0) for edge in new_edges]))
nx.set_edge_attributes(aug_graph, name='weight', values=dict([(edge, 0.1) for edge in orig_edges]))
for cc_sub_graph in nx.connected_component_subgraphs(aug_graph):
mst_sub_graph = nx.minimum_spanning_tree(cc_sub_graph)
for edge in mst_sub_graph.edges():
redge = edge[::-1]
if not (graph.has_edge(*edge) or graph.has_edge(*redge)):
graph.add_edge(*redge, attr_dict={})
示例6: Partition
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def Partition(UnclusteredGraph, code, type, scale):
# Make edges on Unclustered graph
# between all nodes separated by distance 'scale'
# on Dual Lattice
for node1 in UnclusteredGraph.nodes():
for node2 in UnclusteredGraph.nodes():
if node1 != node2:
d = code.distance(type, node1, node2)
if d <= scale:
UnclusteredGraph.add_edge(*(node1, node2), weight=d)
Clusters = []
# Networkx connected components analysis
subgraphs = nx.connected_component_subgraphs(UnclusteredGraph)
for i, sg in enumerate(subgraphs):
Clusters.append(sg.nodes(data=True))
return Clusters
# Choose fixed node for cluster fusion
示例7: strategy_connected_sequential
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def strategy_connected_sequential(G, colors, traversal='bfs'):
"""
Connected sequential ordering (CS). Yield nodes in such an order, that
each node, except the first one, has at least one neighbour in the
preceeding sequence. The sequence can be generated using both BFS and
DFS search (using the strategy_connected_sequential_bfs and
strategy_connected_sequential_dfs method). The default is bfs.
"""
for component_graph in nx.connected_component_subgraphs(G):
source = component_graph.nodes()[0]
yield source # Pick the first node as source
if traversal == 'bfs':
tree = nx.bfs_edges(component_graph, source)
elif traversal == 'dfs':
tree = nx.dfs_edges(component_graph, source)
else:
raise nx.NetworkXError(
'Please specify bfs or dfs for connected sequential ordering')
for (_, end) in tree:
# Then yield nodes in the order traversed by either BFS or DFS
yield end
示例8: setUp
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def setUp(self):
self.undirected = [
nx.connected_component_subgraphs,
nx.biconnected_component_subgraphs,
]
self.directed = [
nx.weakly_connected_component_subgraphs,
nx.strongly_connected_component_subgraphs,
nx.attracting_component_subgraphs,
]
self.subgraph_funcs = self.undirected + self.directed
self.D = nx.DiGraph()
self.D.add_edge(1, 2, eattr='red')
self.D.add_edge(2, 1, eattr='red')
self.D.nodes[1]['nattr'] = 'blue'
self.D.graph['gattr'] = 'green'
self.G = nx.Graph()
self.G.add_edge(1, 2, eattr='red')
self.G.nodes[1]['nattr'] = 'blue'
self.G.graph['gattr'] = 'green'
示例9: setUp
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def setUp(self):
self.undirected = [
nx.connected_component_subgraphs,
nx.biconnected_component_subgraphs,
]
self.directed = [
nx.weakly_connected_component_subgraphs,
nx.strongly_connected_component_subgraphs,
nx.attracting_component_subgraphs,
]
self.subgraph_funcs = self.undirected + self.directed
self.D = nx.DiGraph()
self.D.add_edge(1, 2, eattr='red')
self.D.add_edge(2, 1, eattr='red')
self.D.nodes[1]['nattr'] = 'blue'
self.D.graph['gattr'] = 'green'
self.G = nx.Graph()
self.G.add_edge(1, 2, eattr='red')
self.G.nodes[1]['nattr'] = 'blue'
self.G.graph['gattr'] = 'green'
示例10: read_net
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def read_net(fname, weighted, directed, log):
if weighted:
G = nx.read_edgelist(inodetype=int, data=(('weight', float),),
create_using=nx.DiGraph())
else:
G = nx.read_edgelist(fname, nodetype=int, create_using=nx.DiGraph())
for edge in G.edges():
G[edge[0]][edge[1]]['weight'] = 1
if not directed:
G = G.to_undirected()
log.info('N: %d E: %d' % (G.number_of_nodes(), G.number_of_edges()))
log.info('CC: %d' % nx.number_connected_components(G))
giant = max(nx.connected_component_subgraphs(G), key=len)
log.info('N: %d E: %d' % (giant.number_of_nodes(), giant.number_of_edges()))
return giant
示例11: find_consensus_calls
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def find_consensus_calls(graph):
"""
Find all connected subgraphs such that calls with only self-self overlaps
will exist as singleton graphs while all nodes that overlap each other
directly or transitively will be clustered in the same graph.
"""
for subgraph in nx.connected_component_subgraphs(graph):
# Collect all nodes in this group by their start positions.
nodes_by_start = defaultdict(list)
for node in subgraph.nodes():
try:
nodes_by_start[int(node[1])].append(node)
except:
sys.stderr.write("Exception with node (%s) and graph (%s)\n and " % (node, graph))
raise
# Find the start position with the most nodes (i.e., the consensus start
# position) and return one of the nodes from this set as the
# representative node.
consensus_nodes = max(nodes_by_start.values(), key=lambda nodes: len(nodes))
# If not more than one node shares the same breakpoint, search all nodes
# for optimally placed variant.
if len(consensus_nodes) == 1:
consensus_nodes = [node for start_nodes in nodes_by_start.values() for node in start_nodes]
# Get the node with the smallest difference between distances from
# breakpoints to the edge of the local assembly. This corresponds to
# the node located as close to the middle of a local assembly as
# possible.
if len(consensus_nodes) > 1:
consensus_node = min(consensus_nodes, key=lambda node: abs((int(node[QUERY_LENGTH]) - int(node[QUERY_END])) - int(node[QUERY_START])))
else:
consensus_node = consensus_nodes[0]
# Report the representative node along with the number of nodes in the
# subgraph corresponding to the support for the representative event.
print "\t".join(consensus_node + (str(len(subgraph.nodes())),))
示例12: merge
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def merge(contigs):
#print "MERGING " + str(contigs)
scaffolds = []
subg = all_G.subgraph(contigs)
best_hic_graph = nx.Graph()
edges = []
contigs = set()
for u,v,data in subg.edges(data=True):
edges.append((u,v,data['score']))
edges.sort(key=lambda x: x[2],reverse=True)
#print edges
for u,v,score in edges:
if u not in best_hic_graph.nodes() and v not in best_hic_graph.nodes():
best_hic_graph.add_edge(u,v,score=score)
contigs.add(u.split(':')[0])
contigs.add(v.split(':')[0])
for contig in contigs:
best_hic_graph.add_edge(contig+':B',contig+':E',score=0)
#print best_hic_graph.nodes()
for g in nx.connected_component_subgraphs(best_hic_graph):
#print g.nodes()
p = []
for node in g.nodes():
if g.degree(node) == 1:
p.append(node)
if len(p) == 2:
path = nx.shortest_path(g,p[0],p[1])
scaffolds.append(path)
else:
contigs = set()
for node in g.nodes():
contigs.add(node.split(':')[0])
for each in contigs:
scaffolds.append([each+':B',each+':E'])
#print scaffolds
return scaffolds
示例13: get_lcc_undirected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def get_lcc_undirected(G):
G2 = max(nx.connected_component_subgraphs(G), key=len)
tdl_nodes = G2.nodes()
nodeListMap = dict(zip(tdl_nodes, range(len(tdl_nodes))))
G2 = nx.relabel_nodes(G2, nodeListMap, copy=True)
return G2, nodeListMap
示例14: get_nk_lcc_undirected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [as 别名]
def get_nk_lcc_undirected(G):
G2 = max(nx.connected_component_subgraphs(G), key=len)
tdl_nodes = G2.nodes()
nodeListMap = dict(zip(tdl_nodes, range(len(tdl_nodes))))
G2 = nx.relabel_nodes(G2, nodeListMap, copy=True)
return G2, nodeListMap
示例15: citeseer_ego
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import connected_component_subgraphs [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