本文整理汇总了Python中networkx.is_connected方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.is_connected方法的具体用法?Python networkx.is_connected怎么用?Python networkx.is_connected使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.is_connected方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_scalefree_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def generate_scalefree_graph(variables_count, m_edge, allow_subgraph):
if not allow_subgraph:
graph = nx.barabasi_albert_graph(variables_count, m_edge)
is_connected = nx.is_connected(graph)
while not is_connected:
graph = nx.barabasi_albert_graph(variables_count, m_edge)
is_connected = nx.is_connected(graph)
else:
graph = nx.barabasi_albert_graph(variables_count, m_edge)
# In the obtained graph, low rank nodes will have a much higher edge count
# than high rank nodes. We shuffle the nodes names to avoid this effect:
new_nodes = list(range(variables_count))
random.shuffle(new_nodes)
node_mapping = {n: nn for n, nn in zip(graph.nodes, new_nodes)}
new_graph = nx.Graph((node_mapping[e1], node_mapping[e2]) for e1, e2 in graph.edges)
return new_graph
示例2: decode_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def decode_graph(adj, prefix):
adj = np.asmatrix(adj)
G = nx.from_numpy_matrix(adj)
# G.remove_nodes_from(nx.isolates(G))
print('num of nodes: {}'.format(G.number_of_nodes()))
print('num of edges: {}'.format(G.number_of_edges()))
G_deg = nx.degree_histogram(G)
G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
if nx.is_connected(G):
print('average path length: {}'.format(nx.average_shortest_path_length(G)))
print('average diameter: {}'.format(nx.diameter(G)))
G_cluster = sorted(list(nx.clustering(G).values()))
print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
cycle_len = []
cycle_all = nx.cycle_basis(G, 0)
for item in cycle_all:
cycle_len.append(len(item))
print('cycles', cycle_len)
print('cycle count', len(cycle_len))
draw_graph(G, prefix=prefix)
示例3: dendritic_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [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
示例4: validate_cuts
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
assert_true(all(n in G for n in partition[0]),
msg=msg.format(flow_func.__name__))
assert_true(all(n in G for n in partition[1]),
msg=msg.format(flow_func.__name__))
cutset = compute_cutset(G, partition)
assert_true(all(G.has_edge(u, v) for (u, v) in cutset),
msg=msg.format(flow_func.__name__))
assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),
msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_edges_from(cutset)
if not G.is_directed():
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
else:
assert_false(nx.is_strongly_connected(H),
msg=msg.format(flow_func.__name__))
示例5: test_petersen_cutset
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def test_petersen_cutset():
G = nx.petersen_graph()
for flow_func in flow_funcs:
kwargs = dict(flow_func=flow_func)
# edge cuts
edge_cut = nx.minimum_edge_cut(G, **kwargs)
assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_edges_from(edge_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
# node cuts
node_cut = nx.minimum_node_cut(G, **kwargs)
assert_equal(3, len(node_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_nodes_from(node_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
示例6: test_icosahedral_cutset
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def test_icosahedral_cutset():
G=nx.icosahedral_graph()
for flow_func in flow_funcs:
kwargs = dict(flow_func=flow_func)
# edge cuts
edge_cut = nx.minimum_edge_cut(G, **kwargs)
assert_equal(5, len(edge_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_edges_from(edge_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
# node cuts
node_cut = nx.minimum_node_cut(G, **kwargs)
assert_equal(5, len(node_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_nodes_from(node_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
示例7: validate_cuts
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def validate_cuts(G, s, t, solnValue, partition, capacity, flow_func):
assert_true(all(n in G for n in partition[0]),
msg=msg.format(flow_func.__name__))
assert_true(all(n in G for n in partition[1]),
msg=msg.format(flow_func.__name__))
cutset = compute_cutset(G, partition)
assert_true(all(G.has_edge(u, v) for (u, v) in cutset),
msg=msg.format(flow_func.__name__))
assert_equal(solnValue, sum(G[u][v][capacity] for (u, v) in cutset),
msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_edges_from(cutset)
if not G.is_directed():
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
else:
assert_false(nx.is_strongly_connected(H),
msg=msg.format(flow_func.__name__))
示例8: test_icosahedral_cutset
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def test_icosahedral_cutset():
G = nx.icosahedral_graph()
for flow_func in flow_funcs:
kwargs = dict(flow_func=flow_func)
# edge cuts
edge_cut = nx.minimum_edge_cut(G, **kwargs)
assert_equal(5, len(edge_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_edges_from(edge_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
# node cuts
node_cut = nx.minimum_node_cut(G, **kwargs)
assert_equal(5, len(node_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_nodes_from(node_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
示例9: test_octahedral_cutset
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def test_octahedral_cutset():
G=nx.octahedral_graph()
for flow_func in flow_funcs:
kwargs = dict(flow_func=flow_func)
# edge cuts
edge_cut = nx.minimum_edge_cut(G, **kwargs)
assert_equal(4, len(edge_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_edges_from(edge_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
# node cuts
node_cut = nx.minimum_node_cut(G, **kwargs)
assert_equal(4, len(node_cut), msg=msg.format(flow_func.__name__))
H = G.copy()
H.remove_nodes_from(node_cut)
assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
示例10: generate_random_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def generate_random_graph(variables_count, p_edge, allow_subgraph):
if not allow_subgraph:
graph = nx.gnp_random_graph(variables_count, p_edge)
is_connected = nx.is_connected(graph)
while not is_connected:
graph = nx.gnp_random_graph(variables_count, p_edge)
is_connected = nx.is_connected(graph)
else:
graph = nx.gnp_random_graph(variables_count, p_edge)
return graph
示例11: _check_connectivity
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def _check_connectivity(self, graph):
"""Checking the connected nature of a single graph."""
connected = nx.is_connected(graph)
assert connected, "Graph is not connected."
示例12: is_k_edge_connected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def is_k_edge_connected(G, k):
"""
Tests to see if a graph is k-edge-connected
See Also
--------
is_locally_k_edge_connected
Example
-------
>>> G = nx.barbell_graph(10, 0)
>>> is_k_edge_connected(G, k=1)
True
>>> is_k_edge_connected(G, k=2)
False
"""
if k < 1:
raise ValueError('k must be positive, not {}'.format(k))
# First try to quickly determine if G is not k-edge-connected
if G.number_of_nodes() < k + 1:
return False
elif any(d < k for n, d in G.degree()):
return False
else:
# Otherwise perform the full check
if k == 1:
return nx.is_connected(G)
elif k == 2:
return not nx.has_bridges(G)
else:
# return nx.edge_connectivity(G, cutoff=k) >= k
return nx.edge_connectivity(G) >= k
示例13: weighted_one_edge_augmentation
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
"""Finds the minimum weight set of edges to connect G if one exists.
This is a variant of the weighted MST problem.
Example
-------
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
>>> G.add_nodes_from([6, 7, 8])
>>> # any edge not in avail has an implicit weight of infinity
>>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 1)]
>>> # find another solution by giving large weights to edges in the
>>> # previous solution (note some of the old edges must be used)
>>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 2)]
"""
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
# Collapse CCs in the original graph into nodes in a metagraph
# Then find an MST of the metagraph instead of the original graph
C = collapse(G, nx.connected_components(G))
mapping = C.graph['mapping']
# Assign each available edge to an edge in the metagraph
candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
# nx.set_edge_attributes(C, name='weight', values=0)
C.add_edges_from(
(mu, mv, {'weight': w, 'generator': uv})
for (mu, mv), uv, w in candidate_mapping
)
# Find MST of the meta graph
meta_mst = nx.minimum_spanning_tree(C)
if not partial and not nx.is_connected(meta_mst):
raise nx.NetworkXUnfeasible(
'Not possible to connect G with available edges')
# Yield the edge that generated the meta-edge
for mu, mv, d in meta_mst.edges(data=True):
if 'generator' in d:
edge = d['generator']
yield edge
示例14: _check_inconsistency
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def _check_inconsistency(infr, nid, cc=None):
"""
Check if a PCC contains an error
"""
if cc is None:
cc = infr.pos_graph.component(nid)
was_clean = infr._purge_error_edges(nid)
neg_edges = list(nxu.edges_inside(infr.neg_graph, cc))
if neg_edges:
pos_subgraph_ = infr.pos_graph.subgraph(cc, dynamic=False).copy()
if not nx.is_connected(pos_subgraph_):
print('cc = %r' % (cc,))
print('pos_subgraph_ = %r' % (pos_subgraph_,))
raise AssertionError('must be connected')
hypothesis = dict(infr.hypothesis_errors(pos_subgraph_, neg_edges))
assert len(hypothesis) > 0, 'must have at least one'
infr._set_error_edges(nid, set(hypothesis.keys()))
is_clean = False
else:
infr.recover_graph.remove_nodes_from(cc)
num = infr.recover_graph.number_of_components()
# num = len(list(nx.connected_components(infr.recover_graph)))
msg = ('An inconsistent PCC recovered, '
'{} inconsistent PCC(s) remain').format(num)
infr.print(msg, 2, color='green')
infr.update_pos_redun(nid, force=True)
infr.update_extern_neg_redun(nid, force=True)
is_clean = True
return (was_clean, is_clean)
示例15: hypothesis_errors
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_connected [as 别名]
def hypothesis_errors(infr, pos_subgraph, neg_edges):
if not nx.is_connected(pos_subgraph):
raise AssertionError('Not connected' + repr(pos_subgraph))
infr.print(
'Find hypothesis errors in {} nodes with {} neg edges'.format(
len(pos_subgraph), len(neg_edges)), 3)
pos_edges = list(pos_subgraph.edges())
neg_weight = infr._mincut_edge_weights(neg_edges)
pos_weight = infr._mincut_edge_weights(pos_edges)
capacity = 'weight'
nx.set_edge_attributes(pos_subgraph, name=capacity, values=ut.dzip(pos_edges, pos_weight))
# Solve a multicut problem for multiple pairs of terminal nodes.
# Running multiple min-cuts produces a k-factor approximation
maybe_error_edges = set([])
for (s, t), join_weight in zip(neg_edges, neg_weight):
cut_weight, parts = nx.minimum_cut(pos_subgraph, s, t,
capacity=capacity)
cut_edgeset = nxu.edges_cross(pos_subgraph, *parts)
if join_weight < cut_weight:
join_edgeset = {(s, t)}
chosen = join_edgeset
hypothesis = POSTV
else:
chosen = cut_edgeset
hypothesis = NEGTV
for edge in chosen:
if edge not in maybe_error_edges:
maybe_error_edges.add(edge)
yield (edge, hypothesis)