本文整理汇总了Python中networkx.is_weakly_connected方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.is_weakly_connected方法的具体用法?Python networkx.is_weakly_connected怎么用?Python networkx.is_weakly_connected使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.is_weakly_connected方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_connected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def is_connected(self):
"""
Test if the graph is connected.
Return True if connected, False otherwise
"""
try:
return nx.is_weakly_connected(self.graph)
except nx.exception.NetworkXException:
return False
示例2: _get_subgraphs
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def _get_subgraphs(self, graph, name, size=3):
subgraphs = set()
# print "\nSubgraphs START: " + name
target = nx.complete_graph(size)
for sub_nodes in itertools.combinations(graph.nodes(),len(target.nodes())):
subg = graph.subgraph(sub_nodes)
if nx.is_weakly_connected(subg):
# print subg.edges()
subgraphs.add(subg)
# print "Subgraphs END \n"
return subgraphs
示例3: test_is_weakly_connected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def test_is_weakly_connected(self):
for G, C in self.gc:
U = G.to_undirected()
assert_equal(nx.is_weakly_connected(G), nx.is_connected(U))
示例4: test_connected_raise
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def test_connected_raise(self):
G=nx.Graph()
assert_raises(NetworkXNotImplemented,nx.weakly_connected_components, G)
assert_raises(NetworkXNotImplemented,nx.number_weakly_connected_components, G)
assert_raises(NetworkXNotImplemented,nx.weakly_connected_component_subgraphs, G)
assert_raises(NetworkXNotImplemented,nx.is_weakly_connected, G)
示例5: is_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def is_tree(G):
"""
Returns True if `G` is a tree.
A tree is a connected graph with no undirected cycles.
For directed graphs, `G` is a tree if the underlying graph is a tree. The
underlying graph is obtained by treating each directed edge as a single
undirected edge in a multigraph.
Parameters
----------
G : graph
The graph to test.
Returns
-------
b : bool
A boolean that is True if `G` is a tree.
Notes
-----
In another convention, a directed tree is known as a *polytree* and then
*tree* corresponds to an *arborescence*.
See Also
--------
is_arborescence
"""
if len(G) == 0:
raise nx.exception.NetworkXPointlessConcept('G has no nodes.')
if G.is_directed():
is_connected = nx.is_weakly_connected
else:
is_connected = nx.is_connected
# A connected graph with no cycles has n-1 edges.
return len(G) - 1 == G.number_of_edges() and is_connected(G)
示例6: test_null_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def test_null_graph(self):
G = nx.DiGraph()
assert_equal(list(nx.weakly_connected_components(G)), [])
assert_equal(nx.number_weakly_connected_components(G), 0)
assert_raises(nx.NetworkXPointlessConcept, nx.is_weakly_connected, G)
示例7: test_connected_raise
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def test_connected_raise(self):
G = nx.Graph()
assert_raises(NetworkXNotImplemented, nx.weakly_connected_components, G)
assert_raises(NetworkXNotImplemented, nx.number_weakly_connected_components, G)
assert_raises(NetworkXNotImplemented, nx.is_weakly_connected, G)
# deprecated
assert_raises(NetworkXNotImplemented, nx.weakly_connected_component_subgraphs, G)
示例8: get_largest_component
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def get_largest_component(G, strongly=False):
"""
https://github.com/gboeing/osmnx/blob/master/osmnx/utils.py
Return a subgraph of the largest weakly or strongly connected component
from a directed graph.
Parameters
----------
G : networkx multidigraph
strongly : bool
if True, return the largest strongly instead of weakly connected
component
Returns
-------
G : networkx multidigraph
the largest connected component subgraph from the original graph
"""
start_time = time.time()
original_len = len(list(G.nodes()))
if strongly:
# if the graph is not connected retain only the largest strongly connected component
if not nx.is_strongly_connected(G):
# get all the strongly connected components in graph then identify the largest
sccs = nx.strongly_connected_components(G)
largest_scc = max(sccs, key=len)
G = induce_subgraph(G, largest_scc)
msg = ('Graph was not connected, retained only the largest strongly '
'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
print(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))
else:
# if the graph is not connected retain only the largest weakly connected component
if not nx.is_weakly_connected(G):
# get all the weakly connected components in graph then identify the largest
wccs = nx.weakly_connected_components(G)
largest_wcc = max(wccs, key=len)
G = induce_subgraph(G, largest_wcc)
msg = ('Graph was not connected, retained only the largest weakly '
'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
print(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))
return G
示例9: get_largest_component
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def get_largest_component(G, strongly=False):
"""
Get subgraph of MultiDiGraph's largest weakly/strongly connected component.
Parameters
----------
G : networkx.MultiDiGraph
input graph
strongly : bool
if True, return the largest strongly instead of weakly connected
component
Returns
-------
G : networkx.MultiDiGraph
the largest connected component subgraph from the original graph
"""
original_len = len(list(G.nodes()))
if strongly:
# if the graph is not connected retain only the largest strongly connected component
if not nx.is_strongly_connected(G):
# get all the strongly connected components in graph then identify the largest
sccs = nx.strongly_connected_components(G)
largest_scc = max(sccs, key=len)
G = induce_subgraph(G, largest_scc)
msg = (
f"Graph was not connected, retained only the largest strongly "
f"connected component ({len(G)} of {original_len} total nodes)"
)
utils.log(msg)
else:
# if the graph is not connected retain only the largest weakly connected component
if not nx.is_weakly_connected(G):
# get all the weakly connected components in graph then identify the largest
wccs = nx.weakly_connected_components(G)
largest_wcc = max(wccs, key=len)
G = induce_subgraph(G, largest_wcc)
msg = (
f"Graph was not connected, retained only the largest weakly "
f"connected component ({len(G)} of {original_len} total nodes)"
)
utils.log(msg)
return G
示例10: is_fully_connected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def is_fully_connected(graph):
r"""
Checks whether the input graph is fully connected in the undirected case
or weakly connected in the directed case.
Connected means one can get from any vertex u to vertex v by traversing
the graph. For a directed graph, weakly connected means that the graph
is connected after it is converted to an unweighted graph (ignore the
direction of each edge)
Parameters
----------
graph: nx.Graph, nx.DiGraph, nx.MultiDiGraph, nx.MultiGraph, np.ndarray
Input graph in any of the above specified formats. If np.ndarray,
interpreted as an :math:`n \times n` adjacency matrix
Returns
-------
boolean: True if the entire input graph is connected
References
----------
http://mathworld.wolfram.com/ConnectedGraph.html
http://mathworld.wolfram.com/WeaklyConnectedDigraph.html
Examples
--------
>>> a = np.array([
... [0, 1, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> is_fully_connected(a)
False
"""
if type(graph) is np.ndarray:
if is_symmetric(graph):
g_object = nx.Graph()
else:
g_object = nx.DiGraph()
graph = nx.from_numpy_array(graph, create_using=g_object)
if type(graph) in [nx.Graph, nx.MultiGraph]:
return nx.is_connected(graph)
elif type(graph) in [nx.DiGraph, nx.MultiDiGraph]:
return nx.is_weakly_connected(graph)
示例11: _validate_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def _validate_graph(self):
"""Raise an exception if the link-joint structure is invalid.
Checks for the following:
- The graph is connected in the undirected sense.
- The graph is acyclic in the directed sense.
- The graph has only one base link.
Returns
-------
base_link : :class:`.Link`
The base link of the URDF.
end_links : list of :class:`.Link`
The end links of the URDF.
"""
# Check that the link graph is weakly connected
if not nx.is_weakly_connected(self._G):
link_clusters = []
for cc in nx.weakly_connected_components(self._G):
cluster = []
for n in cc:
cluster.append(n.name)
link_clusters.append(cluster)
message = ('Links are not all connected. '
'Connected components are:')
for lc in link_clusters:
message += '\n\t'
for n in lc:
message += ' {}'.format(n)
raise ValueError(message)
# Check that link graph is acyclic
if not nx.is_directed_acyclic_graph(self._G):
raise ValueError('There are cycles in the link graph')
# Ensure that there is exactly one base link, which has no parent
base_link = None
end_links = []
for n in self._G:
if len(nx.descendants(self._G, n)) == 0:
if base_link is None:
base_link = n
else:
raise ValueError('Links {} and {} are both base links!'
.format(n.name, base_link.name))
if len(nx.ancestors(self._G, n)) == 0:
end_links.append(n)
return base_link, end_links
示例12: is_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def is_tree(G):
"""
Returns ``True`` if ``G`` is a tree.
A tree is a connected graph with no undirected cycles.
For directed graphs, ``G`` is a tree if the underlying graph is a tree. The
underlying graph is obtained by treating each directed edge as a single
undirected edge in a multigraph.
Parameters
----------
G : graph
The graph to test.
Returns
-------
b : bool
A boolean that is ``True`` if ``G`` is a tree.
Notes
-----
In another convention, a directed tree is known as a *polytree* and then
*tree* corresponds to an *arborescence*.
See Also
--------
is_arborescence
"""
if len(G) == 0:
raise nx.exception.NetworkXPointlessConcept('G has no nodes.')
# A connected graph with no cycles has n-1 edges.
if G.number_of_edges() != len(G) - 1:
return False
if G.is_directed():
is_connected = nx.is_weakly_connected
else:
is_connected = nx.is_connected
return is_connected(G)
示例13: average_shortest_path_length
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def average_shortest_path_length(G, weight=None):
r"""Return the average shortest path length.
The average shortest path length is
.. math::
a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}
where `V` is the set of nodes in `G`,
`d(s, t)` is the shortest path from `s` to `t`,
and `n` is the number of nodes in `G`.
Parameters
----------
G : NetworkX graph
weight : None or string, optional (default = None)
If None, every edge has weight/distance/cost 1.
If a string, use this edge attribute as the edge weight.
Any edge attribute not present defaults to 1.
Raises
------
NetworkXError:
if the graph is not connected.
Examples
--------
>>> G=nx.path_graph(5)
>>> print(nx.average_shortest_path_length(G))
2.0
For disconnected graphs you can compute the average shortest path
length for each component:
>>> G=nx.Graph([(1,2),(3,4)])
>>> for g in nx.connected_component_subgraphs(G):
... print(nx.average_shortest_path_length(g))
1.0
1.0
"""
if G.is_directed():
if not nx.is_weakly_connected(G):
raise nx.NetworkXError("Graph is not connected.")
else:
if not nx.is_connected(G):
raise nx.NetworkXError("Graph is not connected.")
avg=0.0
if weight is None:
for node in G:
path_length=nx.single_source_shortest_path_length(G, node)
avg += sum(path_length.values())
else:
for node in G:
path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight)
avg += sum(path_length.values())
n=len(G)
return avg/(n*(n-1))
示例14: is_semiconnected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def is_semiconnected(G):
"""Return True if the graph is semiconnected, False otherwise.
A graph is semiconnected if, and only if, for any pair of nodes, either one
is reachable from the other, or they are mutually reachable.
Parameters
----------
G : NetworkX graph
A directed graph.
Returns
-------
semiconnected : bool
True if the graph is semiconnected, False otherwise.
Raises
------
NetworkXNotImplemented :
If the input graph is not directed.
NetworkXPointlessConcept :
If the graph is empty.
Examples
--------
>>> G=nx.path_graph(4,create_using=nx.DiGraph())
>>> print(nx.is_semiconnected(G))
True
>>> G=nx.DiGraph([(1, 2), (3, 2)])
>>> print(nx.is_semiconnected(G))
False
See Also
--------
is_strongly_connected,
is_weakly_connected
"""
if len(G) == 0:
raise nx.NetworkXPointlessConcept(
'Connectivity is undefined for the null graph.')
if not nx.is_weakly_connected(G):
return False
G = nx.condensation(G)
path = nx.topological_sort(G)
return all(G.has_edge(u, v) for u, v in zip(path[:-1], path[1:]))
示例15: is_semiconnected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_weakly_connected [as 别名]
def is_semiconnected(G):
"""Returns True if the graph is semiconnected, False otherwise.
A graph is semiconnected if, and only if, for any pair of nodes, either one
is reachable from the other, or they are mutually reachable.
Parameters
----------
G : NetworkX graph
A directed graph.
Returns
-------
semiconnected : bool
True if the graph is semiconnected, False otherwise.
Raises
------
NetworkXNotImplemented :
If the input graph is undirected.
NetworkXPointlessConcept :
If the graph is empty.
Examples
--------
>>> G=nx.path_graph(4,create_using=nx.DiGraph())
>>> print(nx.is_semiconnected(G))
True
>>> G=nx.DiGraph([(1, 2), (3, 2)])
>>> print(nx.is_semiconnected(G))
False
See Also
--------
is_strongly_connected
is_weakly_connected
is_connected
is_biconnected
"""
if len(G) == 0:
raise nx.NetworkXPointlessConcept(
'Connectivity is undefined for the null graph.')
if not nx.is_weakly_connected(G):
return False
G = nx.condensation(G)
path = nx.topological_sort(G)
return all(G.has_edge(u, v) for u, v in pairwise(path))