Python networkx.NetworkXNoPath() Examples
The following are 30
code examples of networkx.NetworkXNoPath().
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: selection_multipleDeploys.py From YAFS with MIT License | 6 votes |
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
Example #2
Source File: test_simple_paths.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_bidirectional_shortest_path_restricted_directed_cycle(): directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) length, path = _bidirectional_shortest_path(directed_cycle, 0, 3) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_nodes=[1], ) length, path = _bidirectional_shortest_path(directed_cycle, 0, 3, ignore_edges=[(2, 1)]) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_edges=[(1, 2)], )
Example #3
Source File: selection_multipleDeploys.py From YAFS with MIT License | 6 votes |
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
Example #4
Source File: generic.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def has_path(G, source, target): """Return True if G has a path from source to target, False otherwise. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path """ try: sp = nx.shortest_path(G,source, target) except nx.NetworkXNoPath: return False return True
Example #5
Source File: test_simple_paths.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_bidirectional_shortest_path_restricted_directed_cycle(): directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) length, path = _bidirectional_shortest_path(directed_cycle, 0, 3) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_nodes=[1], ) length, path = _bidirectional_shortest_path(directed_cycle, 0, 3, ignore_edges=[(2, 1)]) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_edges=[(1, 2)], )
Example #6
Source File: pathfinding.py From indra with BSD 2-Clause "Simplified" License | 6 votes |
def get_path_iter(graph, source, target, path_length, loop): """Return a generator of paths with path_length cutoff from source to target.""" path_iter = nx.all_simple_paths(graph, source, target, path_length) try: for p in path_iter: path = deepcopy(p) # Remove common target from a path. path.remove(target) if loop: path.append(path[0]) # A path should contain at least one edge if len(path) < 2: continue yield path except nx.NetworkXNoPath: pass
Example #7
Source File: generic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def has_path(G, source, target): """Returns *True* if *G* has a path from *source* to *target*. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path """ try: nx.shortest_path(G, source, target) except nx.NetworkXNoPath: return False return True
Example #8
Source File: generic.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def has_path(G, source, target): """Return *True* if *G* has a path from *source* to *target*. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path """ try: sp = nx.shortest_path(G, source, target) except nx.NetworkXNoPath: return False return True
Example #9
Source File: astar.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def astar_path_length(G, source, target, heuristic=None, weight='weight'): """Return the length of the shortest path between source and target using the A* ("A-star") algorithm. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path heuristic : function A function to evaluate the estimate of the distance from the a node to the target. The function takes two nodes arguments and must return a number. Raises ------ NetworkXNoPath If no path exists between source and target. See Also -------- astar_path """ if source not in G or target not in G: msg = 'Either source {} or target {} is not in G' raise nx.NodeNotFound(msg.format(source, target)) path = astar_path(G, source, target, heuristic, weight) return sum(G[u][v].get(weight, 1) for u, v in zip(path[:-1], path[1:]))
Example #10
Source File: selection_multipleDeploys.py From YAFS with MIT License | 5 votes |
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 as e: self.logger.warning("There is no path between two nodes: %s - %s " % (node_src, node_dst)) print "Simulation ends?. Time:", sim.env.now # sim.stop = True ## You can stop all DES process return [], None except nx.NodeNotFound as e: self.logger.warning("Node not found: %s - %s "%(node_src,node_dst)) print "Simulation ends?. Time:",sim.env.now # sim.stop = True ## You can stop all DES process return [],None
Example #11
Source File: test_pathfinding.py From indra with BSD 2-Clause "Simplified" License | 5 votes |
def test_shortest_simple_paths_mod_unsigned(): dg, all_ns = _setup_unsigned_graph() dg.add_edge('B1', 'A3', belief=0.7, weight=-np.log(0.7)) # Add long path # between # B1 and C1 source, target = 'B1', 'D1' # Unweighted searches paths = [p for p in shortest_simple_paths(dg, source, target)] assert len(paths) == 2 assert tuple(paths[0]) == ('B1', 'C1', 'D1') assert tuple(paths[1]) == ('B1', 'A3', 'B2', 'C1', 'D1') assert len([p for p in shortest_simple_paths( dg, source, target, ignore_nodes={'A3'})]) == 1 # Test nx.NoPathFound try: len([p for p in shortest_simple_paths( dg, source, target, ignore_nodes={'C1'})]) == 0 except Exception as exc: assert isinstance(exc, nx.NetworkXNoPath) # Weighted searches paths = [p for p in shortest_simple_paths(dg, source, target, weight='weight')] assert tuple(paths[0]) == ('B1', 'C1', 'D1') assert tuple(paths[1]) == ('B1', 'A3', 'B2', 'C1', 'D1')
Example #12
Source File: selection_multipleDeploys.py From YAFS with MIT License | 5 votes |
def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message): try: bestSpeed = 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)) speed = 0 for i in range(len(path) - 1): link = (path[i], path[i + 1]) # print "LINK : ",link # print " BYTES :", message.bytes speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW]) #print sim.topology.G.edges[link][Topology.LINK_BW] att_node = sim.topology.get_nodes_att()[path[-1]] time_service = message.inst / float(att_node["IPT"]) speed += time_service # HW - computation of last node #print "SPEED: ",speed if speed < bestSpeed: bestSpeed = speed 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
Example #13
Source File: astar.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def astar_path_length(G, source, target, heuristic=None, weight='weight'): """Return the length of the shortest path between source and target using the A* ("A-star") algorithm. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path heuristic : function A function to evaluate the estimate of the distance from the a node to the target. The function takes two nodes arguments and must return a number. Raises ------ NetworkXNoPath If no path exists between source and target. See Also -------- astar_path """ path = astar_path(G, source, target, heuristic, weight) return sum(G[u][v].get(weight, 1) for u, v in zip(path[:-1], path[1:]))
Example #14
Source File: test_simple_paths.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bidirectional_shortest_path_ignore(): G = nx.Graph() nx.add_path(G, [1, 2]) nx.add_path(G, [1, 3]) nx.add_path(G, [1, 4]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[1], ) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[2], ) G = nx.Graph() nx.add_path(G, [1, 3]) nx.add_path(G, [1, 4]) nx.add_path(G, [3, 2]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, G, 1, 2, ignore_nodes=[1, 2], )
Example #15
Source File: test_simple_paths.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_bidirectional_dijksta_restricted(): XG = nx.DiGraph() XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1), ('u', 'x', 2), ('v', 'y', 1), ('x', 'u', 3), ('x', 'v', 5), ('x', 'y', 2), ('y', 's', 7), ('y', 'v', 6)]) XG3 = nx.Graph() XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]) validate_length_path(XG, 's', 'v', 9, *_bidirectional_dijkstra(XG, 's', 'v')) validate_length_path(XG, 's', 'v', 10, *_bidirectional_dijkstra(XG, 's', 'v', ignore_nodes=['u'])) validate_length_path(XG, 's', 'v', 11, *_bidirectional_dijkstra(XG, 's', 'v', ignore_edges=[('s', 'x')])) assert_raises( nx.NetworkXNoPath, _bidirectional_dijkstra, XG, 's', 'v', ignore_nodes=['u'], ignore_edges=[('s', 'x')], ) validate_length_path(XG3, 0, 3, 15, *_bidirectional_dijkstra(XG3, 0, 3)) validate_length_path(XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_nodes=[1])) validate_length_path(XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_edges=[(2, 3)])) assert_raises( nx.NetworkXNoPath, _bidirectional_dijkstra, XG3, 0, 3, ignore_nodes=[1], ignore_edges=[(5, 4)], )
Example #16
Source File: test_simple_paths.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_bidirectional_shortest_path_restricted(): grid = cnlti(nx.grid_2d_graph(4,4), first_label=1, ordering="sorted") cycle = nx.cycle_graph(7) directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) length, path = _bidirectional_shortest_path(cycle, 0, 3) assert_equal(path, [0, 1, 2, 3]) length, path = _bidirectional_shortest_path(cycle, 0, 3, ignore_nodes=[1]) assert_equal(path, [0, 6, 5, 4, 3]) length, path = _bidirectional_shortest_path(grid, 1, 12) assert_equal(path, [1, 2, 3, 4, 8, 12]) length, path = _bidirectional_shortest_path(grid, 1, 12, ignore_nodes=[2]) assert_equal(path, [1, 5, 6, 10, 11, 12]) length, path = _bidirectional_shortest_path(grid, 1, 12, ignore_nodes=[2, 6]) assert_equal(path, [1, 5, 9, 10, 11, 12]) length, path = _bidirectional_shortest_path(grid, 1, 12, ignore_nodes=[2, 6], ignore_edges=[(10, 11)]) assert_equal(path, [1, 5, 9, 10, 14, 15, 16, 12]) length, path = _bidirectional_shortest_path(directed_cycle, 0, 3) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_nodes=[1], ) length, path = _bidirectional_shortest_path(directed_cycle, 0, 3, ignore_edges=[(2, 1)]) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_edges=[(1, 2)], )
Example #17
Source File: test_simple_paths.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bidirectional_dijksta_restricted(): XG = nx.DiGraph() XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1), ('u', 'x', 2), ('v', 'y', 1), ('x', 'u', 3), ('x', 'v', 5), ('x', 'y', 2), ('y', 's', 7), ('y', 'v', 6)]) XG3 = nx.Graph() XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]) validate_length_path(XG, 's', 'v', 9, *_bidirectional_dijkstra(XG, 's', 'v')) validate_length_path(XG, 's', 'v', 10, *_bidirectional_dijkstra(XG, 's', 'v', ignore_nodes=['u'])) validate_length_path(XG, 's', 'v', 11, *_bidirectional_dijkstra(XG, 's', 'v', ignore_edges=[('s', 'x')])) assert_raises( nx.NetworkXNoPath, _bidirectional_dijkstra, XG, 's', 'v', ignore_nodes=['u'], ignore_edges=[('s', 'x')], ) validate_length_path(XG3, 0, 3, 15, *_bidirectional_dijkstra(XG3, 0, 3)) validate_length_path(XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_nodes=[1])) validate_length_path(XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_edges=[(2, 3)])) assert_raises( nx.NetworkXNoPath, _bidirectional_dijkstra, XG3, 0, 3, ignore_nodes=[1], ignore_edges=[(5, 4)], )
Example #18
Source File: selection_multipleDeploys.py From YAFS with MIT License | 5 votes |
def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message): try: bestSpeed = 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)) speed = 0 for i in range(len(path) - 1): link = (path[i], path[i + 1]) # print "LINK : ",link # print " BYTES :", message.bytes speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW]) #print sim.topology.G.edges[link][Topology.LINK_BW] att_node = sim.topology.get_nodes_att()[path[-1]] time_service = message.inst / float(att_node["IPT"]) speed += time_service # HW - computation of last node #print "SPEED: ",speed if speed < bestSpeed: bestSpeed = speed 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
Example #19
Source File: selection_multipleDeploys.py From YAFS with MIT License | 5 votes |
def compute_DSAR(self, node_src, alloc_DES, sim, DES_dst,message): try: bestSpeed = float('inf') minPath = [] bestDES = [] # print "LEN %i" %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)) speed = 0 for i in range(len(path) - 1): link = (path[i], path[i + 1]) #print " LINK : ",link #print " BYTES :", message.bytes speed += sim.topology.G.edges[link][Topology.LINK_PR] + (message.bytes/sim.topology.G.edges[link][Topology.LINK_BW]) #print " Spped :" , speed #print sim.topology.G.edges[link][Topology.LINK_BW] att_node = sim.topology.get_nodes_att()[path[-1]] time_service = message.inst / float(att_node["IPT"]) # print "Tims serviice %s" %time_service speed += time_service # HW - computation of last node #print "SPEED: ",speed if speed < bestSpeed: bestSpeed = speed minPath = path bestDES = dev # print "DES %s PATH %s" %(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
Example #20
Source File: astar.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def astar_path_length(G, source, target, heuristic=None, weight='weight'): """Returns the length of the shortest path between source and target using the A* ("A-star") algorithm. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path heuristic : function A function to evaluate the estimate of the distance from the a node to the target. The function takes two nodes arguments and must return a number. Raises ------ NetworkXNoPath If no path exists between source and target. See Also -------- astar_path """ if source not in G or target not in G: msg = 'Either source {} or target {} is not in G' raise nx.NodeNotFound(msg.format(source, target)) path = astar_path(G, source, target, heuristic, weight) return sum(G[u][v].get(weight, 1) for u, v in zip(path[:-1], path[1:]))
Example #21
Source File: graph.py From sonare with MIT License | 5 votes |
def _makeEdgePaths(self): """Make edgePaths dict. (Also removes used edges from _graph.)""" # sort edges by Y values. the idea is that the straight flow's edges # will be handled first and will get nicer edges, though we probably # won't be doing exactly the right thing here. self.edgeLayoutInfos.sort( key=lambda eli: (eli.y1, eli.y2 >= eli.y1, abs(eli.y2 - eli.y1))) edgePaths = {} for eli in self.edgeLayoutInfos: try: path = self._choosePath(eli.p1, eli.p2) # don't use these edges for any other paths for p1, p2 in zip(path, path[1:]): self._graph.remove_edge(p1, p2) except networkx.NetworkXNoPath: # TODO: try again with more rect outlines print('no path! between', p1, p2, file=sys.stderr) # create direct edge for debugging path = [p1, p2] # Force vertical beginning and end of edges. # TODO: it'd be nicer to include these edges in the graph path.insert(0, eli.p0) path.append(eli.p3) edgePaths[eli.b1Addr, eli.b2Addr] = path return edgePaths
Example #22
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 #23
Source File: type_checking.py From ReGraph with MIT License | 5 votes |
def _check_instance(hierarchy, graph_id, pattern, instance, pattern_typing): # Check that the homomorphism is valid try: check_homomorphism( pattern, hierarchy.get_graph(graph_id), instance, total=True ) except InvalidHomomorphism as e: raise RewritingError( "Homomorphism from the pattern to the instance subgraph " "is not valid, got: '{}'".format(e)) # Check that it is a mono if not is_monic(instance): raise RewritingError( "Homomorphism from the pattern to the instance subgraph " "is not injective") # Check that instance typing and lhs typing coincide for node in pattern.nodes(): if pattern_typing: for typing_graph, typing in pattern_typing.items(): try: instance_typing = hierarchy.compose_path_typing( nx.shortest_path(hierarchy, graph_id, typing_graph)) if node in pattern_typing.keys() and\ instance[node] in instance_typing.keys(): if typing[node] != instance_typing[instance[node]]: raise RewritingError( "Typing of the instance of LHS does not " + " coincide with typing of LHS!") except NetworkXNoPath: raise RewritingError( "Graph '%s' is not typed by '%s' specified " "as a typing graph of the lhs of the rule." % (graph_id, typing_graph))
Example #24
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 #25
Source File: test_simple_paths.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_bidirectional_dijksta_restricted(): XG = nx.DiGraph() XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1), ('u', 'x', 2), ('v', 'y', 1), ('x', 'u', 3), ('x', 'v', 5), ('x', 'y', 2), ('y', 's', 7), ('y', 'v', 6)]) XG3 = nx.Graph() XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]]) validate_length_path(XG, 's', 'v', 9, *_bidirectional_dijkstra(XG, 's', 'v')) validate_length_path(XG, 's', 'v', 10, *_bidirectional_dijkstra(XG, 's', 'v', ignore_nodes=['u'])) validate_length_path(XG, 's', 'v', 11, *_bidirectional_dijkstra(XG, 's', 'v', ignore_edges=[('s', 'x')])) assert_raises( nx.NetworkXNoPath, _bidirectional_dijkstra, XG, 's', 'v', ignore_nodes=['u'], ignore_edges=[('s', 'x')], ) validate_length_path(XG3, 0, 3, 15, *_bidirectional_dijkstra(XG3, 0, 3)) validate_length_path(XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_nodes=[1])) validate_length_path(XG3, 0, 3, 16, *_bidirectional_dijkstra(XG3, 0, 3, ignore_edges=[(2, 3)])) assert_raises( nx.NetworkXNoPath, _bidirectional_dijkstra, XG3, 0, 3, ignore_nodes=[1], ignore_edges=[(5, 4)], )
Example #26
Source File: graph_canvas.py From networkx_viewer with GNU General Public License v3.0 | 5 votes |
def plot_path(self, frm_node, to_node, levels=1, add_to_exsting=False): """Plot shortest path between two nodes""" try: path = nx.shortest_path(self.dataG, frm_node, to_node) except nx.NetworkXNoPath as e: tkm.showerror("No path", str(e)) return except nx.NetworkXError as e: tkm.showerror("Node not in graph", str(e)) return graph = self.dataG.subgraph(self._neighbors(path,levels=levels)) if add_to_exsting: self._plot_additional(graph.nodes()) else: self.clear() self._plot_graph(graph) # Mark the path if levels > 0 or add_to_exsting: for u, v in zip(path[:-1], path[1:]): u_disp = self._find_disp_node(u) v_disp = self._find_disp_node(v) for key, value in self.dispG.edge[u_disp][v_disp].items(): self.mark_edge(u_disp, v_disp, key)
Example #27
Source File: unweighted.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def bidirectional_shortest_path(G, source, target): """Returns a list of nodes in a shortest path between source and target. Parameters ---------- G : NetworkX graph source : node label starting node for path target : node label ending node for path Returns ------- path: list List of nodes in a path from source to target. Raises ------ NetworkXNoPath If no path exists between source and target. See Also -------- shortest_path Notes ----- This algorithm is used by shortest_path(G, source, target). """ if source not in G or target not in G: msg = 'Either source {} or target {} is not in G' raise nx.NodeNotFound(msg.format(source, target)) # call helper to do the real work results = _bidirectional_pred_succ(G, source, target) pred, succ, w = results # build path from pred+w+succ path = [] # from source to w while w is not None: path.append(w) w = pred[w] path.reverse() # from w to target w = succ[path[-1]] while w is not None: path.append(w) w = succ[w] return path
Example #28
Source File: unweighted.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _bidirectional_pred_succ(G, source, target): """Bidirectional shortest path helper. Returns (pred, succ, w) where pred is a dictionary of predecessors from w to the source, and succ is a dictionary of successors from w to the target. """ # does BFS from both source and target and meets in the middle if target == source: return ({target: None}, {source: None}, source) # handle either directed or undirected if G.is_directed(): Gpred = G.pred Gsucc = G.succ else: Gpred = G.adj Gsucc = G.adj # predecesssor and successors in search pred = {source: None} succ = {target: None} # initialize fringes, start with forward forward_fringe = [source] reverse_fringe = [target] while forward_fringe and reverse_fringe: if len(forward_fringe) <= len(reverse_fringe): this_level = forward_fringe forward_fringe = [] for v in this_level: for w in Gsucc[v]: if w not in pred: forward_fringe.append(w) pred[w] = v if w in succ: # path found return pred, succ, w else: this_level = reverse_fringe reverse_fringe = [] for v in this_level: for w in Gpred[v]: if w not in succ: succ[w] = v reverse_fringe.append(w) if w in pred: # found path return pred, succ, w raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
Example #29
Source File: test_weighted.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def test_dijkstra(self): (D, P) = nx.single_source_dijkstra(self.XG, 's') validate_path(self.XG, 's', 'v', 9, P['v']) assert_equal(D['v'], 9) validate_path( self.XG, 's', 'v', 9, nx.single_source_dijkstra_path(self.XG, 's')['v']) assert_equal( nx.single_source_dijkstra_path_length(self.XG, 's')['v'], 9) validate_path( self.XG, 's', 'v', 9, nx.single_source_dijkstra(self.XG, 's')[1]['v']) validate_path( self.MXG, 's', 'v', 9, nx.single_source_dijkstra_path(self.MXG, 's')['v']) GG = self.XG.to_undirected() # make sure we get lower weight # to_undirected might choose either edge with weight 2 or weight 3 GG['u']['x']['weight'] = 2 (D, P) = nx.single_source_dijkstra(GG, 's') validate_path(GG, 's', 'v', 8, P['v']) assert_equal(D['v'], 8) # uses lower weight of 2 on u<->x edge validate_path(GG, 's', 'v', 8, nx.dijkstra_path(GG, 's', 'v')) assert_equal(nx.dijkstra_path_length(GG, 's', 'v'), 8) validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3)) validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3)) assert_equal(nx.dijkstra_path_length(self.XG3, 0, 3), 15) validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2)) assert_equal(nx.dijkstra_path_length(self.XG4, 0, 2), 4) validate_path(self.MXG4, 0, 2, 4, nx.dijkstra_path(self.MXG4, 0, 2)) validate_path( self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's', 'v')[1]['v']) validate_path( self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's')[1]['v']) validate_path(self.G, 's', 'v', 2, nx.dijkstra_path(self.G, 's', 'v')) assert_equal(nx.dijkstra_path_length(self.G, 's', 'v'), 2) # NetworkXError: node s not reachable from moon assert_raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, 's', 'moon') assert_raises( nx.NetworkXNoPath, nx.dijkstra_path_length, self.G, 's', 'moon') validate_path(self.cycle, 0, 3, 3, nx.dijkstra_path(self.cycle, 0, 3)) validate_path(self.cycle, 0, 4, 3, nx.dijkstra_path(self.cycle, 0, 4)) assert_equal( nx.single_source_dijkstra(self.cycle, 0, 0), ({0: 0}, {0: [0]}))
Example #30
Source File: connectivity.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _bidirectional_shortest_path(G, source, target, exclude): """Returns shortest path between source and target ignoring nodes in the container 'exclude'. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path exclude: container Container for nodes to exclude from the search for shortest paths Returns ------- path: list Shortest path between source and target ignoring nodes in 'exclude' Raises ------ NetworkXNoPath: exception If there is no path or if nodes are adjacent and have only one path between them Notes ----- This function and its helper are originally from networkx.algorithms.shortest_paths.unweighted and are modified to accept the extra parameter 'exclude', which is a container for nodes already used in other paths that should be ignored. References ---------- .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 http://eclectic.ss.uci.edu/~drwhite/working.pdf """ # call helper to do the real work results = _bidirectional_pred_succ(G, source, target, exclude) pred, succ, w = results # build path from pred+w+succ path = [] # from source to w while w is not None: path.append(w) w = pred[w] path.reverse() # from w to target w = succ[path[-1]] while w is not None: path.append(w) w = succ[w] return path