本文整理汇总了Python中networkx.all_shortest_paths方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.all_shortest_paths方法的具体用法?Python networkx.all_shortest_paths怎么用?Python networkx.all_shortest_paths使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.all_shortest_paths方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_nodes_in_all_shortest_paths
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def get_nodes_in_all_shortest_paths(
graph: BELGraph,
nodes: Iterable[BaseEntity],
weight: Optional[str] = None,
remove_pathologies: bool = False,
) -> Set[BaseEntity]:
"""Get a set of nodes in all shortest paths between the given nodes.
Thinly wraps :func:`networkx.all_shortest_paths`.
:param graph: A BEL graph
:param nodes: The list of nodes to use to use to find all shortest paths
:param weight: Edge data key corresponding to the edge weight. If none, uses unweighted search.
:param remove_pathologies: Should pathology nodes be removed first?
:return: A set of nodes appearing in the shortest paths between nodes in the BEL graph
.. note:: This can be trivially parallelized using :func:`networkx.single_source_shortest_path`
"""
if remove_pathologies:
graph = _remove_pathologies_oop(graph)
return set(_iterate_nodes_in_shortest_paths(graph, nodes, weight=weight))
示例2: _get_nx_paths
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def _get_nx_paths(self, begin, end):
"""
Get the possible (networkx) simple paths between two nodes or addresses
corresponding to nodes.
Input: addresses or node instances
Return: a list of lists of nodes representing paths.
"""
if isinstance(begin, int) and isinstance(end, int):
n_begin = self.get_any_node(begin)
n_end = self.get_any_node(end)
elif isinstance(begin, CFGENode) and isinstance(end, CFGENode):
n_begin = begin
n_end = end
else:
raise AngrCFGError("from and to should be of the same type")
self.remove_fakerets()
return networkx.all_shortest_paths(self.graph, n_begin, n_end)
示例3: create_ranks
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def create_ranks(self):
# Dump everything into networkx to get depth
G = nx.Graph()
# First, add all the nodes
G.add_nodes_from(self.nodes.keys())
# Next, add all the edges
for key, node in self.nodes.items():
for neighbor in node.neighbors:
G.add_edge(key, neighbor)
# Finally, find the shortest path
for key, node in self.nodes.items():
try:
node.shortest = [p for p in nx.all_shortest_paths(G, key, 1)]
node.rank = len(node.shortest[0])
except (nx.exception.NetworkXNoPath, IndexError):
# Unconnected devices (remotes) may have no current path.
node.rank = 1
node.shortest = []
self.ranked = True
示例4: collect_concepts_and_relations
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def collect_concepts_and_relations(self):
g = self.graph
nodes, depths, is_connected = self.bfs()
concepts = [self.name2concept[n] for n in nodes]
relations = dict()
for i, src in enumerate(nodes):
relations[i] = dict()
for j, tgt in enumerate(nodes):
relations[i][j] = list()
for path in nx.all_shortest_paths(g, src, tgt):
info = dict()
info['node'] = path[1:-1]
info['edge'] = [g[path[i]][path[i+1]]['label'] for i in range(len(path)-1)]
info['length'] = len(info['edge'])
relations[i][j].append(info)
return concepts, depths, relations, is_connected
示例5: test_all_shortest_paths
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def test_all_shortest_paths(self):
G = nx.Graph()
nx.add_path(G, [0, 1, 2, 3])
nx.add_path(G, [0, 10, 20, 3])
assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
sorted(nx.all_shortest_paths(G, 0, 3)))
# with weights
G = nx.Graph()
nx.add_path(G, [0, 1, 2, 3])
nx.add_path(G, [0, 10, 20, 3])
assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
sorted(nx.all_shortest_paths(G, 0, 3, weight='weight')))
# weights and method specified
G = nx.Graph()
nx.add_path(G, [0, 1, 2, 3])
nx.add_path(G, [0, 10, 20, 3])
assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
sorted(nx.all_shortest_paths(G, 0, 3, weight='weight',
method='dijkstra')))
G = nx.Graph()
nx.add_path(G, [0, 1, 2, 3])
nx.add_path(G, [0, 10, 20, 3])
assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
sorted(nx.all_shortest_paths(G, 0, 3, weight='weight',
method='bellman-ford')))
示例6: findSwitchRoute
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def findSwitchRoute():
pathKey = ""
nodeList = []
src = int(switch[h2].split(":",7)[7],16)
dst = int(switch[h1].split(":",7)[7],16)
print src
print dst
for currentPath in nx.all_shortest_paths(G, source=src, target=dst, weight=None):
for node in currentPath:
tmp = ""
if node < 17:
pathKey = pathKey + "0" + str(hex(node)).split("x",1)[1] + "::"
tmp = "00:00:00:00:00:00:00:0" + str(hex(node)).split("x",1)[1]
else:
pathKey = pathKey + str(hex(node)).split("x",1)[1] + "::"
tmp = "00:00:00:00:00:00:00:" + str(hex(node)).split("x",1)[1]
nodeList.append(tmp)
pathKey=pathKey.strip("::")
path[pathKey] = nodeList
pathKey = ""
nodeList = []
print path
# Computes Link TX
示例7: _iterate_nodes_in_shortest_paths
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def _iterate_nodes_in_shortest_paths(
graph: BELGraph,
nodes: Iterable[BaseEntity],
weight: Optional[str] = None,
) -> Iterable[BaseEntity]:
"""Iterate over nodes in the shortest paths between all pairs of nodes in the given list."""
for source, target in itt.product(nodes, repeat=2):
try:
paths = nx.all_shortest_paths(graph, source, target, weight=weight)
for path in paths:
for node in path:
yield node
except nx.exception.NetworkXNoPath:
continue
示例8: network_distance_between_genes
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def network_distance_between_genes(self, gene1_id, gene2_id, shortest=True):
all_shortest_paths = []
for i, path in enumerate(nx.all_shortest_paths(self.gene_met_network, gene1_id, gene2_id)):
edges_in_path = zip(path[0:], path[1:])
full_info = [(u, v, self.gene_met_network[u][v]['object']) for (u, v) in edges_in_path]
if shortest:
return full_info
all_shortest_paths.append(full_info)
return all_shortest_paths
示例9: network_distance_between_mets
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def network_distance_between_mets(self, met1_id, met2_id, shortest=True):
all_shortest_paths = []
for i, path in enumerate(nx.all_shortest_paths(self.met_rxn_network, met1_id, met2_id)):
edges_in_path = zip(path[0:], path[1:])
full_info = [(u, v, self.met_rxn_network[u][v]['object']) for (u, v) in edges_in_path]
if shortest:
return full_info
all_shortest_paths.append(full_info)
return all_shortest_paths
示例10: _check_rule_typing
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def _check_rule_typing(hierarchy, rule_id, graph_id, lhs_mapping, rhs_mapping):
all_paths = dict(nx.all_pairs_shortest_path(hierarchy))
paths_from_target = {}
for s in hierarchy.nodes():
if s == graph_id:
for key in all_paths[graph_id].keys():
paths_from_target[key] = all_paths[graph_id][key]
for t in paths_from_target.keys():
if t != graph_id:
new_lhs_h = compose(
lhs_mapping,
hierarchy.compose_path_typing(paths_from_target[t]))
new_rhs_h = compose(
rhs_mapping,
hierarchy.compose_path_typing(paths_from_target[t]))
try:
# find homomorphisms from s to t via other paths
s_t_paths = nx.all_shortest_paths(hierarchy, rule_id, t)
for path in s_t_paths:
lhs_h, rhs_h = hierarchy.compose_path_typing(path)
if lhs_h != new_lhs_h:
raise HierarchyError(
"Invalid lhs typing: homomorphism does not "
"commute with an existing "
"path from '%s' to '%s'!" % (s, t)
)
if rhs_h != new_rhs_h:
raise HierarchyError(
"Invalid rhs typing: homomorphism does not "
"commute with an existing " +
"path from '%s' to '%s'!" % (s, t)
)
except(nx.NetworkXNoPath):
pass
return
示例11: _check_rule_typing
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def _check_rule_typing(self, rule_id, graph_id, lhs_mapping, rhs_mapping):
all_paths = dict(nx.all_pairs_shortest_path(self._graph))
paths_from_target = {}
for s in self.nodes():
if s == graph_id:
for key in all_paths[graph_id].keys():
paths_from_target[key] = all_paths[graph_id][key]
for t in paths_from_target.keys():
if t != graph_id:
new_lhs_h = compose(
lhs_mapping,
self.compose_path_typing(paths_from_target[t]))
new_rhs_h = compose(
rhs_mapping,
self.compose_path_typing(paths_from_target[t]))
try:
# find homomorphisms from s to t via other paths
s_t_paths = nx.all_shortest_paths(self._graph, rule_id, t)
for path in s_t_paths:
lhs_h, _, rhs_h = self.compose_path_typing(path)
if lhs_h != new_lhs_h:
raise HierarchyError(
"Invalid lhs typing: homomorphism does not "
"commute with an existing "
"path from '{}' to '{}'!".format(s, t)
)
if rhs_h != new_rhs_h:
raise HierarchyError(
"Invalid rhs typing: homomorphism does not "
"commute with an existing " +
"path from '{}' to '{}'!".format(s, t)
)
except(nx.NetworkXNoPath):
pass
return
示例12: total_number_of_paths
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def total_number_of_paths(self):
"""Returns the total number of shortests paths between all host pairs in the network"""
total_paths = 0
for host in self.get_hosts():
for host_pair in self.get_hosts():
if host == host_pair:
continue
# compute the number of paths
npaths = sum(1 for _ in nx.all_shortest_paths(self, host, host_pair, 'weight'))
total_paths += npaths
return total_paths
示例13: get_paths_between_nodes
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def get_paths_between_nodes(self, node1, node2):
"""Compute the paths between two nodes."""
paths = nx.all_shortest_paths(self, node1, node2, 'weight')
paths = [tuple(x) for x in paths]
return paths
示例14: shortest_path
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def shortest_path(self, dest_dp, src_dp=None):
"""Return shortest path to a DP, as a list of DPs."""
if src_dp is None:
src_dp = self.name
if self.stack_graph:
try:
return sorted(networkx.all_shortest_paths(self.stack_graph, src_dp, dest_dp))[0]
except (networkx.exception.NetworkXNoPath, networkx.exception.NodeNotFound):
pass
return []
示例15: _route_demands
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_shortest_paths [as 别名]
def _route_demands(self, model):
"""
Routes demands in input 'model'
:param model: input 'model' parameter object (may be different from self)
:return: model with routed demands
"""
G = self._make_weighted_network_graph(include_failed_circuits=False)
for demand in model.demand_objects:
demand.path = []
# Find all LSPs that can carry the demand:
for lsp in (lsp for lsp in model.rsvp_lsp_objects):
if (lsp.source_node_object == demand.source_node_object and
lsp.dest_node_object == demand.dest_node_object and
'Unrouted' not in lsp.path):
demand.path.append(lsp)
if demand.path == []:
src = demand.source_node_object.name
dest = demand.dest_node_object.name
# Shortest path in networkx multidigraph
try:
nx_sp = list(nx.all_shortest_paths(G, src, dest, weight='cost'))
except nx.exception.NetworkXNoPath:
# There is no path, demand.path = 'Unrouted'
demand.path = 'Unrouted'
continue
# all_paths is list of paths from source to destination
all_paths = self.convert_graph_path_to_model_path(nx_sp)
demand.path = all_paths
self._update_interface_utilization()
return self