ó žÃÒYc@sldZddlmZddlmZmZddlmZddlZ ddl m Z ddl Z ddd d d d d ddddddddddddddddddgZd „Zd!d"„Zd!d#„Zdd!d$„Zdd!d%„Zddd!d&„Zdd!d'„Zdd!d(„Zddd!d)„Zddddd*„Zddddd+„Zdd!d,„Zdd!d-„Zdd!d.„Zdd!d/„Zd!d0„Zddd!d1„Z dddddd2„Z!d!d3„Z"d!d4„Z#dd!d5„Z$dd!d6„Z%ddd!d7„Z&dd!d8„Z'dd!d9„Z(d!d:„Z)d!d;„Z*d!d<„Z+d!d=„Z,dS(>s. Shortest path algorithms for weighed graphs. iÿÿÿÿ(tdeque(theappushtheappop(tcountN(tgenerate_unique_nodet dijkstra_pathtdijkstra_path_lengthtbidirectional_dijkstratsingle_source_dijkstratsingle_source_dijkstra_patht"single_source_dijkstra_path_lengthtmulti_source_dijkstratmulti_source_dijkstra_patht!multi_source_dijkstra_path_lengthtall_pairs_dijkstratall_pairs_dijkstra_pathtall_pairs_dijkstra_path_lengtht!dijkstra_predecessor_and_distancetbellman_ford_pathtbellman_ford_path_lengthtsingle_source_bellman_fordtsingle_source_bellman_ford_patht&single_source_bellman_ford_path_lengthtall_pairs_bellman_ford_patht"all_pairs_bellman_ford_path_lengtht bellman_fordt%bellman_ford_predecessor_and_distancetnegative_edge_cycletgoldberg_radziktjohnsoncs6tˆƒrˆS|jƒr)‡fd†S‡fd†S(s_Returns a function that returns the weight of an edge. The returned function is specifically suitable for input to functions :func:`_dijkstra` and :func:`_bellman_ford_relaxation`. Parameters ---------- G : NetworkX graph. weight : string or function If it is callable, `weight` itself is returned. If it is a string, it is assumed to be the name of the edge attribute that represents the weight of an edge. In that case, a function is returned that gets the edge weight according to the specified edge attribute. Returns ------- function This function returns a callable that accepts exactly three inputs: a node, an node adjacent to the first one, and the edge attribute dictionary for the eedge joining those nodes. That function returns a number representing the weight of an edge. If `G` is a multigraph, and `weight` is not callable, the minimum edge weight over all parallel edges is returned. If any edge does not have an attribute with key `weight`, it is assumed to have weight one. cs t‡fd†|jƒDƒƒS(Nc3s!|]}|jˆdƒVqdS(iN(tget(t.0tattr(tweight(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys Xs(tmintvalues(tutvtd(R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pytXscs|jˆdƒS(Ni(R(R$R%tdata(R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR'Ys(tcallablet is_multigraph(tGR!((R!s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyt_weight_function4s    R!cCs%t||d|d|ƒ\}}|S(sèReturns the shortest weighted path from source to target in G. Uses Dijkstra's Method to compute the shortest weighted path between two nodes in a graph. Parameters ---------- G : NetworkX graph source : node Starting node target : node Ending node weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- path : list List of nodes in a shortest path. Raises ------ NetworkXNoPath If no path exists between source and target. Examples -------- >>> G=nx.path_graph(5) >>> print(nx.dijkstra_path(G,0,4)) [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. The weight function can be used to include node weights. >>> def func(u, v, d): ... node_u_wt = G.nodes[u].get('node_weight', 1) ... node_v_wt = G.nodes[v].get('node_weight', 1) ... edge_wt = d.get('weight', 1) ... return node_u_wt/2 + node_v_wt/2 + edge_wt In this example we take the average of start and end node weights of an edge and add it to the weight of the edge. See Also -------- bidirectional_dijkstra(), bellman_ford_path() ttargetR!(R(R+tsourceR-R!tlengthtpath((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR\sEcCst||krdSt||ƒ}t|||d|ƒ}y ||SWn*tk rotjd||fƒ‚nXdS(sgReturns the shortest weighted path length in G from source to target. Uses Dijkstra's Method to compute the shortest weighted path length between two nodes in a graph. Parameters ---------- G : NetworkX graph source : node label starting node for path target : node label ending node for path weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- length : number Shortest path length. Raises ------ NetworkXNoPath If no path exists between source and target. Examples -------- >>> G=nx.path_graph(5) >>> print(nx.dijkstra_path_length(G,0,4)) 4 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. See Also -------- bidirectional_dijkstra(), bellman_ford_path_length() iR-sNode %s not reachable from %sN(R,t _dijkstratKeyErrortnxtNetworkXNoPath(R+R.R-R!R/((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR¦s;   cCst||hd|d|ƒS(slFind shortest weighted paths in G from a source node. Compute shortest path between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- paths : dictionary Dictionary of shortest path lengths keyed by target. Examples -------- >>> G=nx.path_graph(5) >>> path=nx.single_source_dijkstra_path(G,0) >>> path[4] [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. See Also -------- single_source_dijkstra(), single_source_bellman_ford() tcutoffR!(R (R+R.R5R!((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR ìs7cCst||hd|d|ƒS(sFind shortest weighted path lengths in G from a source node. Compute the shortest path length between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- length : dict Dict keyed by node to shortest path length from source. Examples -------- >>> G = nx.path_graph(5) >>> length = nx.single_source_dijkstra_path_length(G, 0) >>> length[4] 4 >>> for node in [0, 1, 2, 3, 4]: ... print('{}: {}'.format(node, length[node])) 0: 0 1: 1 2: 2 3: 3 4: 4 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. See Also -------- single_source_dijkstra(), single_source_bellman_ford_path_length() R5R!(R (R+R.R5R!((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR 's?c Cs"t||hd|d|d|ƒS(sq Find shortest weighted paths and lengths from a source node. Compute the shortest path length between source and all other reachable nodes for a weighted graph. Uses Dijkstra's algorithm to compute shortest paths and lengths between a source and all other reachable nodes in a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path target : node label, optional Ending node for path cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- distance, path : pair of dictionaries, or numeric and list. If target is None, paths and lengths to all nodes are computed. The return value is a tuple of two dictionaries keyed by target nodes. The first dictionary stores distance to each target node. The second stores the path to each target node. If target is not None, returns a tuple (distance, path), where distance is the distance from source to target and path is a list representing the path from source to target. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.single_source_dijkstra(G, 0) >>> print(length[4]) 4 >>> for node in [0, 1, 2, 3, 4]: ... print('{}: {}'.format(node, length[node])) 0: 0 1: 1 2: 2 3: 3 4: 4 >>> path[4] [0, 1, 2, 3, 4] >>> length, path = nx.single_source_dijkstra(G, 0, 1) >>> length 1 >>> path [0, 1] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. Based on the Python cookbook recipe (119466) at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows and roundoff errors can cause problems). See Also -------- single_source_dijkstra_path() single_source_dijkstra_path_length() single_source_bellman_ford() R5R-R!(R (R+R.R-R5R!((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRjs[cCs%t||d|d|ƒ\}}|S(sñFind shortest weighted paths in G from a given set of source nodes. Compute shortest path between any of the source nodes and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph sources : non-empty set of nodes Starting nodes for paths. If this is just a set containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in the set, the computed paths may begin from any one of the start nodes. cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- paths : dictionary Dictionary of shortest paths keyed by target. Examples -------- >>> G = nx.path_graph(5) >>> path = nx.multi_source_dijkstra_path(G, {0, 4}) >>> path[1] [0, 1] >>> path[3] [4, 3] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. Raises ------ ValueError If `sources` is empty. See Also -------- multi_source_dijkstra(), multi_source_bellman_ford() R5R!(R (R+tsourcesR5R!R/R0((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR ÉsBcCs:|stdƒ‚nt||ƒ}t|||d|ƒS(sNFind shortest weighted path lengths in G from a given set of source nodes. Compute the shortest path length between any of the source nodes and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph sources : non-empty set of nodes Starting nodes for paths. If this is just a set containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in the set, the computed paths may begin from any one of the start nodes. cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- length : dict Dict keyed by node to shortest path length to nearest source. Examples -------- >>> G = nx.path_graph(5) >>> length = nx.multi_source_dijkstra_path_length(G, {0, 4}) >>> for node in [0, 1, 2, 3, 4]: ... print('{}: {}'.format(node, length[node])) 0: 0 1: 1 2: 2 3: 1 4: 0 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. Raises ------ ValueError If `sources` is empty. See Also -------- multi_source_dijkstra() ssources must not be emptyR5(t ValueErrorR,t_dijkstra_multisource(R+R6R5R!((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR sFc CsÍ|stdƒ‚n||kr.d|gfSt||ƒ}d„|Dƒ}t|||d|d|d|ƒ}|dkr‡||fSy||||fSWn)tk rÈtjdj|ƒƒ‚nXdS( sN Find shortest weighted paths and lengths from a given set of source nodes. Uses Dijkstra's algorithm to compute the shortest paths and lengths between one of the source nodes and the given `target`, or all other reachable nodes if not specified, for a weighted graph. Parameters ---------- G : NetworkX graph sources : non-empty set of nodes Starting nodes for paths. If this is just a set containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in the set, the computed paths may begin from any one of the start nodes. target : node label, optional Ending node for path cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- distance, path : pair of dictionaries, or numeric and list If target is None, returns a tuple of two dictionaries keyed by node. The first dictionary stores distance from one of the source nodes. The second stores the path from one of the sources to that node. If target is not None, returns a tuple of (distance, path) where distance is the distance from source to target and path is a list representing the path from source to target. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.multi_source_dijkstra(G, {0, 4}) >>> for node in [0, 1, 2, 3, 4]: ... print('{}: {}'.format(node, length[node])) 0: 0 1: 1 2: 2 3: 1 4: 0 >>> path[1] [0, 1] >>> path[3] [4, 3] >>> length, path = nx.multi_source_dijkstra(G, {0, 4}, 1) >>> length 1 >>> path [0, 1] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. Based on the Python cookbook recipe (119466) at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows and roundoff errors can cause problems). Raises ------ ValueError If `sources` is empty. See Also -------- multi_source_dijkstra_path() multi_source_dijkstra_path_length() ssources must not be emptyicSsi|]}|g|“qS(((RR.((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys Âs tpathsR5R-sNo path to {}.N(R7R,R8tNoneR2R3R4tformat(R+R6R-R5R!R9tdist((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR \sa     c Cs+t||g|d|d|d|d|ƒS(sUses Dijkstra's algorithm to find shortest weighted paths from a single source. This is a convenience function for :func:`_dijkstra_multisource` with all the arguments the same, except the keyword argument `sources` set to ``[source]``. tpredR9R5R-(R8(R+R.R!R=R9R5R-((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR1Ís cCs+|jƒr|jn|j}t}t} i} i} tƒ} g} x4|D],}d| |<|| dt| ƒ|fƒqLWx¨| r&| | ƒ\}}}|| kr¬qn|| |<||krÆPnxZ||jƒD]H\}}||||ƒ}|dkrq×n| ||}|dk r6||kr6q×q6n|| krg|| |krt ddƒ‚qq×|| ksƒ|| |krì|| |<|| |t| ƒ|fƒ|dk rÍ|||g||t||ƒ}ig|6}|t|||d|d|ƒfS(s}Compute weighted shortest path length and predecessors. Uses Dijkstra's Method to obtain the shortest weighted paths and return dictionaries of predecessors for each node and distance for each node from the `source`. Parameters ---------- G : NetworkX graph source : node label Starting node for path cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- pred, distance : dictionaries Returns two dictionaries representing a list of predecessors of a node and the distance to each node. Warning: If target is specified, the dicts are incomplete as they only contain information for the nodes along a path to target. Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The list of predecessors contains more than one element only when there are more than one shortest paths to the key node. Examples -------- >>> import networkx as nx >>> G = nx.path_graph(5, create_using = nx.DiGraph()) >>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0) >>> sorted(pred.items()) [(0, []), (1, [0]), (2, [1]), (3, [2]), (4, [3])] >>> sorted(dist.items()) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> pred, dist = nx.dijkstra_predecessor_and_distance(G, 0, 1) >>> sorted(pred.items()) [(0, []), (1, [0])] >>> sorted(dist.items()) [(0, 0), (1, 1)] R=R5(R,R1(R+R.R5R!R=((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR8s? ccsGx@|D]8}t||d|d|ƒ\}}|||ffVqWdS(s´Find shortest weighted paths and lengths between all nodes. Parameters ---------- G : NetworkX graph cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edge[u][v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Yields ------ (node, (distance, path)) : (node obj, (dict, dict)) Each source node has two associated dicts. The first holds distance keyed by target and the second holds paths keyed by target. (See single_source_dijkstra for the source/target node terminology.) If desired you can apply `dict()` to this function to create a dict keyed by source node to the two dicts. Examples -------- >>> G = nx.path_graph(5) >>> len_path = dict(nx.all_pairs_dijkstra(G)) >>> print(len_path[3][0][1]) 2 >>> for node in [0, 1, 2, 3, 4]: ... print('3 - {}: {}'.format(node, len_path[3][0][node])) 3 - 0: 3 3 - 1: 2 3 - 2: 1 3 - 3: 0 3 - 4: 1 >>> len_path[3][1][1] [3, 2, 1] >>> for n, (dist, path) in nx.all_pairs_dijkstra(G): ... print(path[1]) [0, 1] [1] [2, 1] [3, 2, 1] [4, 3, 2, 1] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The yielded dicts only have keys for reachable nodes. R5R!N(R(R+R5R!tnR<R0((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR|s> !c cs;t}x.|D]&}||||d|d|ƒfVq WdS(s&Compute shortest path lengths between all nodes in a weighted graph. Parameters ---------- G : NetworkX graph cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- distance : iterator (source, dictionary) iterator with dictionary keyed by target and shortest path length as the key value. Examples -------- >>> G = nx.path_graph(5) >>> length = dict(nx.all_pairs_dijkstra_path_length(G)) >>> for node in [0, 1, 2, 3, 4]: ... print('1 - {}: {}'.format(node, length[1][node])) 1 - 0: 1 1 - 1: 0 1 - 2: 1 1 - 3: 2 1 - 4: 3 >>> length[3][2] 1 >>> length[2][2] 0 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The dictionary returned only has keys for reachable node pairs. R5R!N(R (R+R5R!R/RN((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR¿s4 c cs;t}x.|D]&}||||d|d|ƒfVq WdS(s@Compute shortest paths between all nodes in a weighted graph. Parameters ---------- G : NetworkX graph cutoff : integer or float, optional Depth to stop the search. Only return paths with length <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- distance : dictionary Dictionary, keyed by source and target, of shortest paths. Examples -------- >>> G = nx.path_graph(5) >>> path = dict(nx.all_pairs_dijkstra_path(G)) >>> print(path[0][4]) [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- floyd_warshall(), all_pairs_bellman_ford_path() R5R!N(R (R+R5R!R0RN((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRøs- cCs)d}tj|tƒt||d|ƒS(sFDEPRECATED: Replaced by bellman_ford_predecessor_and_distance(). suFunction bellman_ford() is deprecated and will be removedin 2.1, use bellman_ford_predecessor_and_distance() instead.R!(t _warningstwarntDeprecationWarningR(R+R.R!tmsg((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR+sc sí||kr"tjd|ƒ‚nt|ˆƒ‰t‡fd†tj|dtƒDƒƒrntjdƒ‚nid|6}id g|6}t|ƒdkr§||fSt|ˆƒ‰t ||gˆd|d|d |d |ƒ}||fS( sV Compute shortest path lengths and predecessors on shortest paths in weighted graphs. The algorithm has a running time of $O(mn)$ where $n$ is the number of nodes and $m$ is the number of edges. It is slower than Dijkstra but can handle negative edge weights. Parameters ---------- G : NetworkX graph The algorithm works for all types of graphs, including directed graphs and multigraphs. source: node label Starting node for path weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- pred, dist : dictionaries Returns two dictionaries keyed by node to predecessor in the path and to the distance from the source respectively. Warning: If target is specified, the dicts are incomplete as they only contain information for the nodes along a path to target. Raises ------ NetworkXUnbounded If the (di)graph contains a negative cost (di)cycle, the algorithm raises an exception to indicate the presence of the negative cost (di)cycle. Note: any negative weight edge in an undirected graph is a negative cost cycle. Examples -------- >>> import networkx as nx >>> G = nx.path_graph(5, create_using = nx.DiGraph()) >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0) >>> sorted(pred.items()) [(0, [None]), (1, [0]), (2, [1]), (3, [2]), (4, [3])] >>> sorted(dist.items()) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0, 1) >>> sorted(pred.items()) [(0, [None]), (1, [0])] >>> sorted(dist.items()) [(0, 0), (1, 1)] >>> from nose.tools import assert_raises >>> G = nx.cycle_graph(5, create_using = nx.DiGraph()) >>> G[1][2]['weight'] = -7 >>> assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 0) Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The dictionaries returned only have keys for nodes reachable from the source. In the case where the (di)graph is not connected, if a component not containing the source contains a negative cost (di)cycle, it will not be detected. s!Node %s is not found in the graphc3s0|]&\}}}ˆ|||ƒdkVqdS(iN((RR$R%R&(R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys ‹sR(sNegative cost cycle detected.iiR=R<R5R-N( R3t NodeNotFoundR,tanytselfloop_edgestTruetNetworkXUnboundedR:tlent _bellman_ford(R+R.R-R5R!R<R=((R!s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR6sR +  csÙ|dkrd„|Dƒ}n|dkr>d„|Dƒ}n|jƒrS|jn|j}tdƒ} t|ƒ} i} t|ƒ} t|ƒ‰x¬| r@| jƒ} ˆj | ƒt ‡fd†|| Dƒƒr•|| }x\|| j ƒD]G\}}|||| |ƒ}|dk r2||kr2qïq2n|dk r_||j || ƒkr_qïq_n||j || ƒkrø|ˆkrÞ| j |ƒˆj|ƒ| j |dƒd}|| krÑtjdƒ‚n|| |Ïs cSsi|]}d|“qS(i((RR%((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys Òs tinfc3s|]}|ˆkVqdS(N((Rtpred_u(tin_q(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys àsiisNegative cost cycle detected.N(R:R>tsucctadjtfloatRXRtsettpoplefttremovetallRBRRCtaddR3RWtreverse(R+R.R!R=R9R<R5R-RDRZRNRtqR$tdist_uR%RKtdist_vtcount_vtdststdstR0tcur((R\s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRY›s^3                       *    cCs%t||d|d|ƒ\}}|S(s-Returns the shortest path from source to target in a weighted graph G. Parameters ---------- G : NetworkX graph source : node Starting node target : node Ending node weight: string, optional (default='weight') Edge data key corresponding to the edge weight Returns ------- path : list List of nodes in a shortest path. Raises ------ NetworkXNoPath If no path exists between source and target. Examples -------- >>> G=nx.path_graph(5) >>> print(nx.bellman_ford_path(G, 0, 4)) [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- dijkstra_path(), bellman_ford_path_length() R-R!(R(R+R.R-R!R/R0((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR s) cCsw||krdSt||ƒ}t||g|d|ƒ}y ||SWn*tk rrtjd||fƒ‚nXdS(sEReturns the shortest path length from source to target in a weighted graph. Parameters ---------- G : NetworkX graph source : node label starting node for path target : node label ending node for path weight: string, optional (default='weight') Edge data key corresponding to the edge weight Returns ------- length : number Shortest path length. Raises ------ NetworkXNoPath If no path exists between source and target. Examples -------- >>> G=nx.path_graph(5) >>> print(nx.bellman_ford_path_length(G,0,4)) 4 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- dijkstra_path_length(), bellman_ford_path() iR-snode %s not reachable from %sN(R,RYR2R3R4(R+R.R-R!R/((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR;s*   cCs%t||d|d|ƒ\}}|S(s~Compute shortest path between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. weight: string, optional (default='weight') Edge data key corresponding to the edge weight cutoff : integer or float, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- paths : dictionary Dictionary of shortest path lengths keyed by target. Examples -------- >>> G=nx.path_graph(5) >>> path=nx.single_source_bellman_ford_path(G,0) >>> path[4] [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- single_source_dijkstra(), single_source_bellman_ford() R5R!(R(R+R.R5R!R/R0((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRss'cCs(t||ƒ}t||g|d|ƒS(sCompute the shortest path length between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path weight: string, optional (default='weight') Edge data key corresponding to the edge weight. cutoff : integer or float, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- length : iterator (target, shortest path length) iterator Examples -------- >>> G = nx.path_graph(5) >>> length = dict(nx.single_source_bellman_ford_path_length(G, 0)) >>> length[4] 4 >>> for node in [0, 1, 2, 3, 4]: ... print('{}: {}'.format(node, length[node])) 0: 0 1: 1 2: 2 3: 3 4: 4 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- single_source_dijkstra(), single_source_bellman_ford() R5(R,RY(R+R.R5R!((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRŸs/c CsÂ||krd|gfSt||ƒ}i|g|6}t||g|d|d|d|ƒ}|dkru||fSy||||fSWn0tk r½d||f}tj|ƒ‚nXdS(sMCompute shortest paths and lengths in a weighted graph G. Uses Bellman-Ford algorithm for shortest paths. Parameters ---------- G : NetworkX graph source : node label Starting node for path target : node label, optional Ending node for path cutoff : integer or float, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- distance, path : pair of dictionaries, or numeric and list If target is None, returns a tuple of two dictionaries keyed by node. The first dictionary stores distance from one of the source nodes. The second stores the path from one of the sources to that node. If target is not None, returns a tuple of (distance, path) where distance is the distance from source to target and path is a list representing the path from source to target. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.single_source_bellman_ford(G, 0) >>> print(length[4]) 4 >>> for node in [0, 1, 2, 3, 4]: ... print('{}: {}'.format(node, length[node])) 0: 0 1: 1 2: 2 3: 3 4: 4 >>> path[4] [0, 1, 2, 3, 4] >>> length, path = nx.single_source_bellman_ford(G, 0, 1) >>> length 1 >>> path [0, 1] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- single_source_dijkstra() single_source_bellman_ford_path() single_source_bellman_ford_path_length() iR9R5R-sNode %s not reachable from %sN(R,RYR:R2R3R4(R+R.R-R5R!R9R<RR((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRÒs>      c csAt}x4|D],}|t|||d|d|ƒƒfVq WdS(s$ Compute shortest path lengths between all nodes in a weighted graph. Parameters ---------- G : NetworkX graph weight: string, optional (default='weight') Edge data key corresponding to the edge weight cutoff : integer or float, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- distance : iterator (source, dictionary) iterator with dictionary keyed by target and shortest path length as the key value. Examples -------- >>> G = nx.path_graph(5) >>> length = dict(nx.all_pairs_bellman_ford_path_length(G)) >>> for node in [0, 1, 2, 3, 4]: ... print('1 - {}: {}'.format(node, length[1][node])) 1 - 0: 1 1 - 1: 0 1 - 2: 1 1 - 3: 2 1 - 4: 3 >>> length[3][2] 1 >>> length[2][2] 0 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The dictionary returned only has keys for reachable node pairs. R5R!N(Rtdict(R+R5R!R/RN((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR!s* c cs;t}x.|D]&}||||d|d|ƒfVq WdS(s: Compute shortest paths between all nodes in a weighted graph. Parameters ---------- G : NetworkX graph weight: string, optional (default='weight') Edge data key corresponding to the edge weight cutoff : integer or float, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- distance : dictionary Dictionary, keyed by source and target, of shortest paths. Examples -------- >>> G = nx.path_graph(5) >>> path = dict(nx.all_pairs_bellman_ford_path(G)) >>> print(path[0][4]) [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- floyd_warshall(), all_pairs_dijkstra_path() R5R!N(R(R+R5R!R0RN((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRPs# cs‚||kr"tjd|ƒ‚nt|ˆƒ‰t‡fd†tj|dtƒDƒƒrntjdƒ‚nt|ƒdkr˜id |6id|6fS|j ƒr°|j ‰n |j ‰t dƒ‰t ‡fd†|Dƒƒ‰dˆ|>> import networkx as nx >>> G = nx.path_graph(5, create_using = nx.DiGraph()) >>> pred, dist = nx.goldberg_radzik(G, 0) >>> sorted(pred.items()) [(0, None), (1, 0), (2, 1), (3, 2), (4, 3)] >>> sorted(dist.items()) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> from nose.tools import assert_raises >>> G = nx.cycle_graph(5, create_using = nx.DiGraph()) >>> G[1][2]['weight'] = -7 >>> assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 0) Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The dictionaries returned only have keys for nodes reachable from the source. In the case where the (di)graph is not connected, if a component not containing the source contains a negative cost (di)cycle, it will not be detected. s!Node %s is not found in the graphc3s0|]&\}}}ˆ|||ƒdkVqdS(iN((RR$R%R&(R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys ÄsR(sNegative cost cycle detected.iiRZc3s|]}|ˆfVqdS(N((RR$(RZ(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys Ðsc sg}i}xë|D]㉈|kr+qnˆˆ‰t‡‡‡‡fd†ˆˆjƒDƒƒrjqnˆtˆˆjƒƒfg}tˆgƒ}d|ˆèsiiÿÿÿÿsNegative cost cycle detected.(RcRBtiterR`RAt StopIterationRCRFRbtintRdR3RWRe( t relabeledtto_scant neg_counttstacktin_stacktitR%RKtttd_vtis_neg(RDR&R=R!(RnR$s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyt topo_sortÔsJ               #  cs—tƒ}x‡|D]}ˆ|}xlˆ|jƒD]Z\}}ˆ|||ƒ}||ˆ|kr1||ˆ|<|ˆ|<|j|ƒq1q1WqW|S(s,Relax out-edges of relabeled nodes. (R`RBRd(RsRrR$RnR%RKtw_e(RDR&R=R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pytrelaxs    c3s|]}|ˆ|fVqdS(N((RR$(R&(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys 'sN(R3RSR,RTRURVRWRXR:R>R]R^R_RmR`(R+R.R!R{R}RrRs((RDR&RZR=R!s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRys,H +      ;  cCsttƒ}|jg|D]}||f^qƒz0yt|||ƒWntjk r]tSXWd|j|ƒXtS(sëReturn True if there exists a negative edge cycle anywhere in G. Parameters ---------- G : NetworkX graph weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- negative_cycle : bool True if a negative edge cycle exists, otherwise False. Examples -------- >>> import networkx as nx >>> G = nx.cycle_graph(5, create_using = nx.DiGraph()) >>> print(nx.negative_edge_cycle(G)) False >>> G[1][2]['weight'] = -7 >>> print(nx.negative_edge_cycle(G)) True Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. This algorithm uses bellman_ford_predecessor_and_distance() but finds negative cycles on any component by first adding a new node connected to every node, and starting bellman_ford_predecessor_and_distance on that node. It then removes that extra node. N(Rtadd_edges_fromRR3RWRVt remove_nodetFalse(R+R!tnewnodeRN((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyR+s- & cs||ks||kr<d}tj|j||ƒƒ‚n||krUd|gfSt}t}iig}i|g|6i|g|6g}ggg} id|6id|6g} tƒ} || ddt| ƒ|fƒ|| ddt| ƒ|fƒ|jƒr|j|j g} n|j |j g} g} d}x¦| drã| drãd|}|| |ƒ\}}}|||kr‹q>n||||<||d|kr·|| fSx&| ||ƒD]}|dkrB|j ƒrt ‡fd†|||j ƒDƒƒ}n|||jˆdƒ}||||}ne|j ƒr{t ‡fd†|||j ƒDƒƒ}n|||jˆdƒ}||||}|||krÝ||||krÜtdƒ‚qÜqÈ|| |ks|| ||krÈ|| ||<|| ||t| ƒ|fƒ||||g|||<|| dkrÜ|| dkrÜ| d|| d|}| gksž||krÙ|}|d|}|jƒ|d||d} qÙqÜqÈqÈWq>Wtjd||fƒ‚dS( shDijkstra's algorithm for shortest paths using bidirectional search. Parameters ---------- G : NetworkX graph source : node Starting node. target : node Ending node. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- length, path : number and list length is the distance from source to target. path is a list of nodes on a path from source to target. Raises ------ NetworkXNoPath If no path exists between source and target. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.bidirectional_dijkstra(G, 0, 4) >>> print(length) 4 >>> print(path) [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. In practice bidirectional Dijkstra is much more than twice as fast as ordinary Dijkstra. Ordinary Dijkstra expands nodes in a sphere-like manner from the source. The radius of this sphere will eventually be the length of the shortest path. Bidirectional Dijkstra will expand nodes from both the source and the target, making two spheres of half this radius. Volume of the first sphere is `\pi*r*r` while the others are `2*\pi*r/2*r/2`, making up half the volume. This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows and roundoff errors can cause problems). See Also -------- shortest_path shortest_path_length s)Either source {} or target {} is not in Giic3s'|]\}}|jˆdƒVqdS(iN(R(Rtktdd(R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys ×sc3s'|]\}}|jˆdƒVqdS(iN(R(RR‚Rƒ(R!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys Þss,Contradictory paths found: negative weights?sNo path between %s and %s.N(R3RSR;RRRRAR>t successorst predecessorst neighborsR*R"RBRR7ReR4(R+R.R-R!RRRERFtdistsR9RIRGRHtneighst finalpathtdirR<RJR%t finaldisttwt minweighttvwLengtht totaldisttrevpath((R!s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRdsnF              $   'cs²tjˆdˆƒs'tjdƒ‚nd„ˆDƒ}d„ˆDƒ}tˆˆƒ‰tˆtˆƒˆd|d|ƒ‰‡‡fd†‰‡‡fd†‰‡fd †ˆDƒS( s¡Uses Johnson's Algorithm to compute shortest paths. Johnson's Algorithm finds a shortest path between each pair of nodes in a weighted graph even if negative weights are present. Parameters ---------- G : NetworkX graph weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- distance : dictionary Dictionary, keyed by source and target, of shortest paths. Raises ------ NetworkXError If given graph is not weighted. Examples -------- >>> import networkx as nx >>> graph = nx.DiGraph() >>> graph.add_weighted_edges_from([('0', '3', 3), ('0', '1', -5), ... ('0', '2', 2), ('1', '2', 4), ('2', '3', 1)]) >>> paths = nx.johnson(graph, weight='weight') >>> paths['0']['2'] ['0', '1', '2'] Notes ----- Johnson's algorithm is suitable even for graphs with negative weights. It works by using the Bellman–Ford algorithm to compute a transformation of the input graph that removes all negative weights, allowing Dijkstra's algorithm to be used on the transformed graph. The time complexity of this algorithm is $O(n^2 \log n + n m)$, where $n$ is the number of nodes and $m$ the number of edges in the graph. For dense graphs, this may be faster than the Floyd–Warshall algorithm. See Also -------- floyd_warshall_predecessor_and_distance floyd_warshall_numpy all_pairs_shortest_path all_pairs_shortest_path_length all_pairs_dijkstra_path bellman_ford_predecessor_and_distance all_pairs_bellman_ford_path all_pairs_bellman_ford_path_length R!sGraph is not weighted.cSsi|]}d|“qS(i((RR%((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys ?s cSsi|]}dg|“qS(N(R:(RR%((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys @s R=R<cs ˆ|||ƒˆ|ˆ|S(N((R$R%R&(t dist_bellmanR!(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyt new_weightHscs*i|g|6}tˆ|ˆd|ƒ|S(NR9(R1(R%R9(R+R’(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyt dist_pathKscsi|]}ˆ|ƒ|“qS(((RR%(R“(s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pys Ps (R3t is_weightedt NetworkXErrorR,RYtlist(R+R!R<R=((R+R‘R“R’R!s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pyRùsC$(-t__doc__t collectionsRtheapqRRt itertoolsRtnetworkxR3tnetworkx.utilsRtwarningsROt__all__R,RRR:R R RR R R R1R8RRRRRRRYRRRRRRRRRRR(((s/private/var/folders/w6/vb91730s7bb1k90y_rnhql1dhvdd44/T/pip-build-w4MwvS/networkx/networkx/algorithms/shortest_paths/weighted.pytsˆ    ( J F; B ^G K p  \DC93 d q . 8-3N/) ² 9 •