Python networkx.all_shortest_paths() Examples
The following are 25
code examples of networkx.all_shortest_paths().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: paths.py From pybel with MIT License | 7 votes |
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))
Example #2
Source File: cfg_emulated.py From angr with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #3
Source File: z-wave-graph.py From home-assistant-z-wave-graph with GNU General Public License v3.0 | 6 votes |
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
Example #4
Source File: test_generic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
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')))
Example #5
Source File: AMRGraph.py From gtos with MIT License | 6 votes |
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
Example #6
Source File: dp.py From faucet with Apache License 2.0 | 5 votes |
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 []
Example #7
Source File: test_generic.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_all_shortest_paths_raise(self): G = nx.path_graph(4) G.add_node(4) paths = list(nx.all_shortest_paths(G,0,4))
Example #8
Source File: test_generic.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
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)))
Example #9
Source File: test_generic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bad_method(self): G = nx.path_graph(2) list(nx.all_shortest_paths(G, 0, 1, weight='weight', method='SPAM'))
Example #10
Source File: test_generic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_all_shortest_paths_raise(self): G = nx.path_graph(4) G.add_node(4) list(nx.all_shortest_paths(G, 0, 4))
Example #11
Source File: test_generic.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_all_shortest_paths_raise(self): G = nx.Graph() G.add_path([0,1,2,3]) G.add_node(4) paths = list(nx.all_shortest_paths(G,0,4))
Example #12
Source File: test_generic.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_all_shortest_paths(self): G = nx.Graph() G.add_path([0,1,2,3]) G.add_path([0,10,20,3]) assert_equal([[0,1,2,3],[0,10,20,3]], sorted(nx.all_shortest_paths(G,0,3)))
Example #13
Source File: flex_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 5 votes |
def get_shortest_path(self, source_node_name, dest_node_name, needed_bw=0): # TODO - does this work? """ For a source and dest node name pair, find the shortest path(s) with at least needed_bw available. :param source_node_name: name of source node in path :param dest_node_name: name of destination node in path :param needed_bw: the amount of reservable bandwidth required on the path :return: Return the shortest path in dictionary form: shortest_path = {'path': [list of shortest path routes], 'cost': path_cost} """ # Define a networkx DiGraph to find the path G = self._make_weighted_network_graph_mdg(include_failed_circuits=False, needed_bw=needed_bw) # Define the Model-style path to be built converted_path = dict() converted_path['path'] = [] converted_path['cost'] = None # Find the shortest paths in G between source and dest multidigraph_shortest_paths = nx.all_shortest_paths(G, source_node_name, dest_node_name, weight='cost') # Get shortest path(s) from source to destination; this may include paths # that have multiple links between nodes try: for path in multidigraph_shortest_paths: model_path = self._convert_nx_path_to_model_path(path, needed_bw) converted_path['path'].append(model_path) converted_path['cost'] = nx.shortest_path_length(G, source_node_name, dest_node_name, weight='cost') except BaseException: return converted_path # Normalize the path info to get all combinations of with parallel # interfaces path_info = self._normalize_multidigraph_paths(converted_path['path']) return {'cost': converted_path['cost'], 'path': path_info}
Example #14
Source File: performance_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 5 votes |
def get_shortest_path(self, source_node_name, dest_node_name, needed_bw=0): """ For a source and dest node name pair, find the shortest path(s) with at least needed_bw available. :param source_node_name: name of source node in path :param dest_node_name: name of destination node in path :param needed_bw: the amount of reservable bandwidth required on the path :return: Return the shortest path in dictionary form Example: shortest_path = {'path': [list of shortest path routes], 'cost': path_cost} """ # Define a networkx DiGraph to find the path G = self._make_weighted_network_graph(include_failed_circuits=False, needed_bw=needed_bw) # Define the Model-style path to be built converted_path = dict() converted_path['path'] = [] converted_path['cost'] = None # Find the shortest paths in G between source and dest digraph_shortest_paths = nx.all_shortest_paths(G, source_node_name, dest_node_name, weight='cost') try: for path in digraph_shortest_paths: model_path = self._convert_nx_path_to_model_path(path) converted_path['path'].append(model_path) converted_path['cost'] = nx.shortest_path_length(G, source_node_name, dest_node_name, weight='cost') return converted_path except BaseException: return converted_path
Example #15
Source File: performance_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 5 votes |
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
Example #16
Source File: loadbalancer.py From sdn-loadbalancing with GNU General Public License v3.0 | 5 votes |
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
Example #17
Source File: topology.py From p4-utils with GNU General Public License v2.0 | 5 votes |
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
Example #18
Source File: topology.py From p4-utils with GNU General Public License v2.0 | 5 votes |
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
Example #19
Source File: hierarchies.py From ReGraph with MIT License | 5 votes |
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
Example #20
Source File: type_checking.py From ReGraph with MIT License | 5 votes |
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
Example #21
Source File: modelpro.py From ssbio with MIT License | 5 votes |
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
Example #22
Source File: modelpro.py From ssbio with MIT License | 5 votes |
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
Example #23
Source File: paths.py From pybel with MIT License | 5 votes |
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
Example #24
Source File: performance_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 4 votes |
def get_shortest_path_for_routed_lsp(self, source_node_name, dest_node_name, lsp, needed_bw): """ For a source and dest node name pair, find the shortest path(s) with at least needed_bw available for an LSP that is already routed. This takes into account reserved bandwidth on the Interfaces the LSP already transits, allowing the bandwidth reserved by the LSP to be considered for reservation on any new path for the input LSP Return the shortest path in dictionary form: shortest_path = {'path': [list of shortest path routes], 'cost': path_cost} :param source_node_name: name of source node :param dest_node_name: name of destination node :param lsp: LSP object :param needed_bw: reserved bandwidth for LSPs :return: dict {'path': [list of lists, each list a shortest path route], 'cost': path_cost} Example:: >>> lsp RSVP_LSP(source = B, dest = C, lsp_name = 'lsp_b_c_1') >>> path = model.get_shortest_path_for_routed_lsp('A', 'D', lsp, 10) >>> path {'path': [[Interface(name = 'A-to-D', cost = 40, capacity = 20.0, node_object = Node('A'), remote_node_object = Node('D'), circuit_id = 3)]], 'cost': 40} """ # Define a networkx DiGraph to find the path G = self._make_weighted_network_graph_routed_lsp(lsp, needed_bw=needed_bw) # Define the Model-style path to be built converted_path = dict() converted_path['path'] = [] converted_path['cost'] = None # Find the shortest paths in G between source and dest digraph_shortest_paths = nx.all_shortest_paths(G, source_node_name, dest_node_name, weight='cost') try: for path in digraph_shortest_paths: model_path = self._convert_nx_path_to_model_path(path) converted_path['path'].append(model_path) converted_path['cost'] = nx.shortest_path_length(G, source_node_name, dest_node_name, weight='cost') return converted_path except BaseException: return converted_path
Example #25
Source File: flex_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 4 votes |
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_mdg(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; these paths # may include paths that have multiple links between nodes all_paths = self._get_all_paths_mdg(G, nx_sp) path_list = self._normalize_multidigraph_paths(all_paths) demand.path = path_list self._update_interface_utilization() return self