本文整理匯總了Python中networkx.shortest_path方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.shortest_path方法的具體用法?Python networkx.shortest_path怎麽用?Python networkx.shortest_path使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.shortest_path方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: verify
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def verify(prog, src_name, dst_name):
src = prog.subs.find(src_name)
dst = prog.subs.find(dst_name)
if src is None or dst is None:
return None
graphs = GraphsBuilder()
graphs.run(prog)
cg = graphs.callgraph
if nx.has_path(cg, src.id.number, dst.id.number):
return ('calls', nx.shortest_path(cg, src.id.number, dst.id.number))
calls = CallsitesCollector(graphs.callgraph, src.id.number, dst.id.number)
for sub in prog.subs:
calls.run(sub)
cfg = graphs.callgraph.nodes[sub.id.number]['cfg']
for src in calls.srcs:
for dst in calls.dsts:
if src != dst and nx.has_path(cfg, src, dst):
return ('sites', nx.shortest_path(cfg, src, dst))
calls.clear()
return None
示例2: get_path_node_ids
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_path_node_ids(self, leaf_id: NodeId, root_id: NodeId = None) -> List[NodeId]:
"""
Get the data of the path between ``leaf_id`` and ``root_id``.
Args:
leaf_id: Id that identifies the leaf of the tree. \
If ``leaf_id`` is the hash of a walker state ``from_hash`` \
needs to be ``True``. Otherwise it refers to a node id of \
the leaf node.
root_id: Node id of the root node of the tree.
Returns:
List of the node ids between ``root`` and ``leaf_id``.
"""
root = root_id if root_id is not None else self.root_id
nodes = nx.shortest_path(self.data, root, leaf_id)
return nodes
示例3: get_seed_scaffold
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [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: get_typing
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_typing(self, source, target):
"""Get a typing dict associated to the edge 'source->target'."""
if (source, target) in self.edges():
if self.is_graph(source):
return self.get_edge(source, target)["mapping"]
else:
edge = self.get_edge(source, target)
return (edge["lhs_mapping"], edge["rhs_mapping"])
else:
try:
path = nx.shortest_path(self._graph, source, target)
except:
raise HierarchyError(
"No path from '{}' to '{}' in the hierarchy".format(
source, target))
return self.compose_path_typing(path)
示例5: get_event_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_event_path(self, current_state, target_state):
path_events = []
try:
states = nx.shortest_path(G=self.G, source=current_state.state_str, target=target_state.state_str)
if not isinstance(states, list) or len(states) < 2:
self.logger.warning("Error getting path from %s to %s" %
(current_state.state_str, target_state.state_str))
start_state = states[0]
for state in states[1:]:
edge = self.G[start_state][state]
edge_event_strs = list(edge["events"].keys())
if self.random_input:
random.shuffle(edge_event_strs)
path_events.append(edge["events"][edge_event_strs[0]]["event"])
start_state = state
except Exception as e:
print(e)
self.logger.warning("Cannot find a path from %s to %s" % (current_state.state_str, target_state.state_str))
return path_events
示例6: shortest_undirected_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def shortest_undirected_path(self, physical_qubit1, physical_qubit2):
"""Returns the shortest undirected path between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
List: The shortest undirected path
Raises:
CouplingError: When there is no path between physical_qubit1, physical_qubit2.
"""
try:
return nx.shortest_path(self.graph.to_undirected(as_view=True), source=physical_qubit1,
target=physical_qubit2)
except nx.exception.NetworkXNoPath:
raise CouplingError(
"Nodes %s and %s are not connected" % (str(physical_qubit1), str(physical_qubit2)))
示例7: get_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic, from_des):
"""
Get the path between a node of the topology and a module deployed in a node. Furthermore it chooses the process deployed in that node.
"""
node_src = topology_src # TOPOLOGY SOURCE where the message is generated
# print "Node (Topo id): %s" %node_src
# print "Service DST: %s "%message.dst
DES_dst = alloc_module[app_name][message.dst]
# print "DES DST: %s" % DES_dst
minLenPath = float('inf')
minPath = []
bestDES = 0
for des in DES_dst:
node_dst = sim.alloc_DES[des]
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
if len(path) < minLenPath:
minLenPath = len(path)
minPath = [path]
bestDES = [des]
return minPath, bestDES
示例8: compute_BEST_DES
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def compute_BEST_DES(self, node_src, alloc_DES, sim, DES_dst,message):
try:
bestLong = float('inf')
minPath = []
bestDES = []
#print len(DES_dst)
for dev in DES_dst:
#print "DES :",dev
node_dst = alloc_DES[dev]
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
long = len(path)
if long < bestLong:
bestLong = long
minPath = path
bestDES = dev
#print bestDES,minPath
return minPath, bestDES
except (nx.NetworkXNoPath, nx.NodeNotFound) as e:
self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst))
# print "Simulation ends?"
return [], None
示例9: get_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic,from_des):
node_src = topology_src
DES_dst = alloc_module[app_name][message.dst] # returns an array with all DES process serving
if message.dst not in self.rr.keys():
self.rr[message.dst] = 0
# print "GET PATH"
# print "\tNode _ src (id_topology): %i" % node_src
# print "\tRequest service: %s " % (message.dst)
# print "\tProcess serving that service: %s (pos ID: %i)" % (DES_dst, self.rr[message.dst])
next_DES_dst =DES_dst[self.rr[message.dst]]
dst_node = alloc_DES[next_DES_dst]
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dst_node))
bestPath = [path]
bestDES = [next_DES_dst]
self.rr[message.dst] = (self.rr[message.dst] + 1) % len(DES_dst)
return bestPath, bestDES
示例10: compute_most_near
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def compute_most_near(self,node_src,alloc_DES,sim,DES_dst):
"""
This functions caches the minimun path among client-devices and fog-devices-Module Calculator and it chooses the best calculator process deployed in that node
"""
#By Placement policy we know that:
try:
minLenPath = float('inf')
minPath = []
bestDES = []
for dev in DES_dst:
node_dst = alloc_DES[dev]
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
if len(path)<minLenPath:
minLenPath = len(path)
minPath = path
bestDES = dev
return minPath,bestDES
except nx.NetworkXNoPath:
self.logger.warning("There is no path between two nodes: %s - %s "%(node_src,node_dst))
print "Simulation ends?"
return [],None
示例11: get_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic, from_des):
node_src = topology_src
DES_dst = alloc_module[app_name][message.dst]
bestPath = []
bestDES = []
for des in DES_dst:
dst_node = alloc_DES[des]
# print type(node_src)
# print type(dst_node)
# print "NODE SRC: %s" %node_src
# print "NODE DST: %s" %dst_node
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=str(dst_node)))
# print path
bestPath = [path]
bestDES = [des]
return bestPath,bestDES
示例12: get_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_path(self, sim, app_name, message, topology_src, alloc_DES, alloc_module, traffic, from_des):
node_src = topology_src
DES_dst = alloc_module[app_name][message.dst] # returns an array with all DES process serving
if message.dst not in self.rr.keys():
self.rr[message.dst] = 0
# print "GET PATH"
# print "\tNode _ src (id_topology): %i" % node_src
# print "\tRequest service: %s " % (message.dst)
# print "\tProcess serving that service: %s (pos ID: %i)" % (DES_dst, self.rr[message.dst])
next_DES_dst =DES_dst[self.rr[message.dst]]
dst_node = alloc_DES[next_DES_dst]
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dst_node))
bestPath = [path]
bestDES = [next_DES_dst]
self.rr[message.dst] = (self.rr[message.dst] + 1) % len(DES_dst)
return bestPath, bestDES
示例13: compute_most_near
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def compute_most_near(self,node_src,alloc_DES,sim,DES_dst):
"""
This functions caches the minimun path among client-devices and fog-devices-Module Calculator and it chooses the best calculator process deployed in that node
"""
#By Placement policy we know that:
minLenPath = float('inf')
minPath = []
bestDES = []
for dev in DES_dst:
node_dst = alloc_DES[dev]
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=node_dst))
if len(path)<minLenPath:
minLenPath = len(path)
minPath = path
bestDES = dev
return minPath,bestDES
示例14: get_path
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def get_path(self, sim, app_name,message, topology_src, alloc_DES, alloc_module, traffic,from_des):
paths = []
dst_idDES = []
node_src = topology_src #TOPOLOGY SOURCE where the message is generated
DES_dst = alloc_module[app_name][message.dst]
#Among all possible path we choose the smallest
bestPath = []
bestDES = []
print (DES_dst)
for des in DES_dst:
dst_node = alloc_DES[des]
# print "DES Node %i " %dst_node
path = list(nx.shortest_path(sim.topology.G, source=node_src, target=dst_node))
bestPath = [path]
bestDES = [des]
print (path)
return bestPath,bestDES
示例15: bring_farthest_pair_together
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import shortest_path [as 別名]
def bring_farthest_pair_together(self, pairs: Sequence[QidPair]):
"""Adds SWAPs to bring the farthest-apart pair of logical qubits
together."""
distances = [self.distance(pair) for pair in pairs]
assert distances
max_distance = min(distances)
farthest_pairs = [
pair for pair, d in zip(pairs, distances) if d == max_distance
]
choice = self.prng.choice(len(farthest_pairs))
farthest_pair = farthest_pairs[choice]
edge = self.log_to_phys(*farthest_pair)
shortest_path = nx.shortest_path(self.device_graph, *edge)
assert len(shortest_path) - 1 == max_distance
midpoint = max_distance // 2
self.swap_along_path(shortest_path[:midpoint])
self.swap_along_path(shortest_path[midpoint:])