
    Vhb                     z   d Z ddlZg dZej                  d        Z ej                  d      dd       Z ej                  d      dd       Z ej                  d      dd	       Z ej                  d      dd
       Z	 ej                  d      dd       Z
 ej                  d      dd       Zd Zy)z
Compute the shortest paths and path lengths between nodes in the graph.

These algorithms work with undirected and directed graphs.

    N)shortest_pathall_shortest_paths single_source_all_shortest_pathsall_pairs_all_shortest_pathsshortest_path_lengthaverage_shortest_path_lengthhas_pathc                 f    	 t        j                  | ||       y# t         j                  $ r Y yw xY w)zReturns *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
    FT)nxr   NetworkXNoPath)Gsourcetargets      Z/home/dcms/DCMS/lib/python3.12/site-packages/networkx/algorithms/shortest_paths/generic.pyr	   r	      s8    
FF+   s    00weight)
edge_attrsc                 r   |dvrt        d|       |dn|}||S|dk(  rt        j                  |       }|S |dk(  rt        j                  | |      }|S t        j                  | |      }|S | j                         r| j                  d      } |dk(  rt        j                  | |      }n6|dk(  rt        j                  | ||      }nt        j                  | ||      }|D ]  }t        t        ||               ||<    |S |V|dk(  rt        j                  | |      }|S |dk(  rt        j                  | ||      }|S t        j                  | ||      }|S |dk(  rt        j                  | ||      }|S |dk(  rt        j                  | |||      \  }}|S t        j                  | |||      }|S )a*  Compute shortest paths in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node, optional
        Starting node for path. If not specified, compute shortest
        paths for each possible starting node.

    target : node, optional
        Ending node for path. If not specified, compute shortest
        paths to all possible nodes.

    weight : None, string or function, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.
        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.

    method : string, optional (default = 'dijkstra')
        The algorithm to use to compute the path.
        Supported options: 'dijkstra', 'bellman-ford'.
        Other inputs produce a ValueError.
        If `weight` is None, unweighted graph methods are used, and this
        suggestion is ignored.

    Returns
    -------
    path: list or dictionary or iterator
        All returned paths include both the source and target in the path.

        If the source and target are both specified, return a single list
        of nodes in a shortest path from the source to the target.

        If only the source is specified, return a dictionary keyed by
        targets with a list of nodes in a shortest path from the source
        to one of the targets.

        If only the target is specified, return a dictionary keyed by
        sources with a list of nodes in a shortest path from one of the
        sources to the target.

        If neither the source nor target are specified, return an iterator
        over (source, dictionary) where dictionary is keyed by target to
        list of nodes in a shortest path from the source to the target.

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    ValueError
        If `method` is not among the supported options.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> print(nx.shortest_path(G, source=0, target=4))
    [0, 1, 2, 3, 4]
    >>> p = nx.shortest_path(G, source=0)  # target not specified
    >>> p[3]  # shortest path from source=0 to target=3
    [0, 1, 2, 3]
    >>> p = nx.shortest_path(G, target=4)  # source not specified
    >>> p[1]  # shortest path from source=1 to target=4
    [1, 2, 3, 4]
    >>> p = dict(nx.shortest_path(G))  # source, target not specified
    >>> p[2][4]  # shortest path from source=2 to target=4
    [2, 3, 4]

    Notes
    -----
    There may be more than one shortest path between a source and target.
    This returns only one of them.

    See Also
    --------
    all_pairs_shortest_path
    all_pairs_dijkstra_path
    all_pairs_bellman_ford_path
    single_source_shortest_path
    single_source_dijkstra_path
    single_source_bellman_ford_path
    dijkstrabellman-fordmethod not supported: 
unweightedr   r   Fcopy)
ValueErrorr   all_pairs_shortest_pathall_pairs_dijkstra_pathall_pairs_bellman_ford_pathis_directedreversesingle_source_shortest_pathsingle_source_dijkstra_pathsingle_source_bellman_ford_pathlistreversedbidirectional_shortest_pathbidirectional_dijkstrabellman_ford_path)r   r   r   r   methodpaths_s          r   r   r   *   s   t 111&:;;#^\F~>%2215F LE :%221VDB L? 66qH> L9 }}II5I)%66q&A:%66q&P::1fVT > $XeFm%< =f>& L! >%66q&A L :%66q&P L ::1fVT L %66q&&I
 L	 :%44QO5 L ,,QGL    c                 h   |dvrt        d|       |dn|}||S|dk(  rt        j                  |       }|S |dk(  rt        j                  | |      }|S t        j                  | |      }|S | j                         r| j                  d      } |dk(  rt        j                  } || |      }|S |dk(  rt        j                  } || ||      }|S t        j                  } || ||      }|S |\|dk(  rt        j                  | |      }|S |dk(  rt        j                  } || ||      }|S t        j                  } || ||      }|S |dk(  r't        j                  | ||      }t        |      dz
  }|S |dk(  rt        j                  | |||      }|S t        j                  | |||      }|S )	af  Compute shortest path lengths in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node, optional
        Starting node for path.
        If not specified, compute shortest path lengths using all nodes as
        source nodes.

    target : node, optional
        Ending node for path.
        If not specified, compute shortest path lengths using all nodes as
        target nodes.

    weight : None, string or function, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.
        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.

    method : string, optional (default = 'dijkstra')
        The algorithm to use to compute the path length.
        Supported options: 'dijkstra', 'bellman-ford'.
        Other inputs produce a ValueError.
        If `weight` is None, unweighted graph methods are used, and this
        suggestion is ignored.

    Returns
    -------
    length: number or iterator
        If the source and target are both specified, return the length of
        the shortest path from the source to the target.

        If only the source is specified, return a dict keyed by target
        to the shortest path length from the source to that target.

        If only the target is specified, return a dict keyed by source
        to the shortest path length from that source to the target.

        If neither the source nor target are specified, return an iterator
        over (source, dictionary) where dictionary is keyed by target to
        shortest path length from source to that target.

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    NetworkXNoPath
        If no path exists between source and target.

    ValueError
        If `method` is not among the supported options.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> nx.shortest_path_length(G, source=0, target=4)
    4
    >>> p = nx.shortest_path_length(G, source=0)  # target not specified
    >>> p[4]
    4
    >>> p = nx.shortest_path_length(G, target=4)  # source not specified
    >>> p[0]
    4
    >>> p = dict(nx.shortest_path_length(G))  # source,target not specified
    >>> p[0][4]
    4

    Notes
    -----
    The length of the path is always 1 less than the number of nodes involved
    in the path since the length measures the number of edges followed.

    For digraphs this returns the shortest directed path length. To find path
    lengths in the reverse direction use G.reverse(copy=False) first to flip
    the edge orientation.

    See Also
    --------
    all_pairs_shortest_path_length
    all_pairs_dijkstra_path_length
    all_pairs_bellman_ford_path_length
    single_source_shortest_path_length
    single_source_dijkstra_path_length
    single_source_bellman_ford_path_length
    r   r   r   r   r   Fr      )r   r   all_pairs_shortest_path_lengthall_pairs_dijkstra_path_length"all_pairs_bellman_ford_path_lengthr    r!   "single_source_shortest_path_length"single_source_dijkstra_path_length&single_source_bellman_ford_path_lengthr'   lendijkstra_path_lengthbellman_ford_path_length)r   r   r   r   r*   r+   path_lengthps           r   r   r      s   ~ 111&:;;#^\F~>%99!<L LK :%99!FKH LE ==aOD L? }}II5I)% CC#Av.6 L5 :% CC#Avf=0 L- !GG#Avf=* L' >%==aH  L :% CC#Avf= L !GG#Avf= L %221ffEA

 L	 :%//666J L 33AvvvNLr-   c                    
 g d}ddg}||z   }dnd|vrt        d       t               }|dk(  rd}t        j                  |      |d	k(  ry j	                         r*t        j
                         st        j                  d
       j	                         s*t        j                         st        j                  d       fd
|v rt        
fd D              }npdk(  r8t        j                         }	t        d |	j                         D              }n3dk(  r.t        t        j                         j                               }||d	z
  z  z  S )ao  Returns the average shortest path length.

    The average shortest path length is

    .. math::

       a =\sum_{\substack{s,t \in V \\ s\neq t}} \frac{d(s, t)}{n(n-1)}

    where `V` is the set of nodes in `G`,
    `d(s, t)` is the shortest path from `s` to `t`,
    and `n` is the number of nodes in `G`.

    .. versionchanged:: 3.0
       An exception is raised for directed graphs that are not strongly
       connected.

    Parameters
    ----------
    G : NetworkX graph

    weight : None, string or function, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.
        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.

    method : string, optional (default = 'unweighted' or 'dijkstra')
        The algorithm to use to compute the path lengths.
        Supported options are 'unweighted', 'dijkstra', 'bellman-ford',
        'floyd-warshall' and 'floyd-warshall-numpy'.
        Other method values produce a ValueError.
        The default method is 'unweighted' if `weight` is None,
        otherwise the default method is 'dijkstra'.

    Raises
    ------
    NetworkXPointlessConcept
        If `G` is the null graph (that is, the graph on zero nodes).

    NetworkXError
        If `G` is not connected (or not strongly connected, in the case
        of a directed graph).

    ValueError
        If `method` is not among the supported options.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> nx.average_shortest_path_length(G)
    2.0

    For disconnected graphs, you can compute the average shortest path
    length for each component

    >>> G = nx.Graph([(1, 2), (3, 4)])
    >>> for C in (G.subgraph(c).copy() for c in nx.connected_components(G)):
    ...     print(nx.average_shortest_path_length(C))
    1.0
    1.0

    )r   r   r   zfloyd-warshallzfloyd-warshall-numpyr   r   r   r   zJthe null graph has no paths, thus there is no average shortest path lengthr/   z Graph is not strongly connected.zGraph is not connected.c                     dk(  rt        j                  |       S dk(  rt        j                  |       S dk(  rt        j                  |       S y )Nr   r   r   r   )r   r3   r4   r5   )vr   r*   r   s    r   r9   z1average_shortest_path_length.<locals>.path_length  s]    \!88A>>z!88AfMM~%<<Q&QQ &r-   c              3   X   K   | ]!  } |      j                         D ]  }|  # y wN)values).0ulr9   s      r   	<genexpr>z/average_shortest_path_length.<locals>.<genexpr>  s*     >ak!n&;&;&=>>>s   '*r   c              3   N   K   | ]  }t        |j                                 y wr?   )sumr@   )rA   ts     r   rD   z/average_shortest_path_length.<locals>.<genexpr>  s     @C
O@s   #%)r   r6   r   NetworkXPointlessConceptr    is_strongly_connectedNetworkXErroris_connectedrF   floyd_warshallr@   floatfloyd_warshall_numpy)r   r   r*   single_source_methodsall_pairs_methodssupported_methodsnmsgs	all_pairsr9   s   ```       @r   r   r   B  sg   H G)+AB-0AA~!'Z&&1&:;;AA 	AvX 	 ))#..Av}}r77:ABB==?2??1#5899R &&>1>>%%))!F;I@Y-=-=-?@@A--b--a?CCEFAQUr-   c                    |dn|}|dk(  rt        j                  | |      }nP|dk(  rt        j                  | ||      \  }}n/|dk(  rt        j                  | ||      \  }}nt	        d|       t        |h||      S )a  Compute all shortest simple paths in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    target : node
       Ending node for path.

    weight : None, string or function, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.
        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.

    method : string, optional (default = 'dijkstra')
       The algorithm to use to compute the path lengths.
       Supported options: 'dijkstra', 'bellman-ford'.
       Other inputs produce a ValueError.
       If `weight` is None, unweighted graph methods are used, and this
       suggestion is ignored.

    Returns
    -------
    paths : generator of lists
        A generator of all paths between source and target.

    Raises
    ------
    ValueError
        If `method` is not among the supported options.

    NetworkXNoPath
        If `target` cannot be reached from `source`.

    Examples
    --------
    >>> G = nx.Graph()
    >>> nx.add_path(G, [0, 1, 2])
    >>> nx.add_path(G, [0, 10, 2])
    >>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)])
    [[0, 1, 2], [0, 10, 2]]

    Notes
    -----
    There may be many shortest paths between the source and target.  If G
    contains zero-weight cycles, this function will not produce all shortest
    paths because doing so would produce infinitely many paths of unbounded
    length -- instead, we only produce the shortest simple paths.

    See Also
    --------
    shortest_path
    single_source_shortest_path
    all_pairs_shortest_path
    r   r   r   r   r   )r   predecessor!dijkstra_predecessor_and_distance%bellman_ford_predecessor_and_distancer   _build_paths_from_predecessors)r   r   r   r   r*   preddists          r   r   r     s    B $^\F~~a(	:	99!VFS
d	>	!==aPVW
d1&:;;)6(FDAAr-   c           	   #   4  K   |dn|}|dk(  rt        j                  | |      }nP|dk(  rt        j                  | ||      \  }}n/|dk(  rt        j                  | ||      \  }}nt	        d|       |D ]  }|t        t        |h||            f  yw)a  Compute all shortest simple paths from the given source in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    weight : None, string or function, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.
        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.

    method : string, optional (default = 'dijkstra')
       The algorithm to use to compute the path lengths.
       Supported options: 'dijkstra', 'bellman-ford'.
       Other inputs produce a ValueError.
       If `weight` is None, unweighted graph methods are used, and this
       suggestion is ignored.

    Returns
    -------
    paths : generator of dictionary
        A generator of all paths between source and all nodes in the graph.

    Raises
    ------
    ValueError
        If `method` is not among the supported options.

    Examples
    --------
    >>> G = nx.Graph()
    >>> nx.add_path(G, [0, 1, 2, 3, 0])
    >>> dict(nx.single_source_all_shortest_paths(G, source=0))
    {0: [[0]], 1: [[0, 1]], 3: [[0, 3]], 2: [[0, 1, 2], [0, 3, 2]]}

    Notes
    -----
    There may be many shortest paths between the source and target.  If G
    contains zero-weight cycles, this function will not produce all shortest
    paths because doing so would produce infinitely many paths of unbounded
    length -- instead, we only produce the shortest simple paths.

    See Also
    --------
    shortest_path
    all_shortest_paths
    single_source_shortest_path
    all_pairs_shortest_path
    all_pairs_all_shortest_paths
    Nr   r   r   r   r   )r   rW   rX   rY   r   r%   rZ   )r   r   r   r*   r[   r\   rR   s          r   r   r     s     x $^\F~~a(	:	99!VFS
d	>	!==aPVW
d1&:;; I4fXq$GHHHIs   BBc           
   #   R   K   | D ]  }|t        t        | |||            f   yw)aq  Compute all shortest paths between all nodes.

    Parameters
    ----------
    G : NetworkX graph

    weight : None, string or function, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.
        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.

    method : string, optional (default = 'dijkstra')
       The algorithm to use to compute the path lengths.
       Supported options: 'dijkstra', 'bellman-ford'.
       Other inputs produce a ValueError.
       If `weight` is None, unweighted graph methods are used, and this
       suggestion is ignored.

    Returns
    -------
    paths : generator of dictionary
        Dictionary of arrays, keyed by source and target, of all shortest paths.

    Raises
    ------
    ValueError
        If `method` is not among the supported options.

    Examples
    --------
    >>> G = nx.cycle_graph(4)
    >>> dict(nx.all_pairs_all_shortest_paths(G))[0][2]
    [[0, 1, 2], [0, 3, 2]]
    >>> dict(nx.all_pairs_all_shortest_paths(G))[0][3]
    [[0, 3]]

    Notes
    -----
    There may be multiple shortest paths with equal lengths. Unlike
    all_pairs_shortest_path, this method returns all shortest paths.

    See Also
    --------
    all_pairs_shortest_path
    single_source_all_shortest_paths
    )r   r*   N)dictr   )r   r   r*   rR   s       r   r   r   M  s9     j  
1!QvfUV
 	

s   %'c              #     K   ||vrt        j                  d| d      |h}|dgg}d}|dk\  r||   \  }}|| v r&t        |d|dz          D 	cg c]  \  }}	|	 c}	} t        ||         |kD  r[|dz   ||   d<   ||   |   }
|
|v r`|j	                  |
       |dz  }|t        |      k(  r|j                  |
dg       n!|
dg||   dd n|j                  |       |dz  }|dk\  ryyc c}	}w w)a  Compute all simple paths to target, given the predecessors found in
    pred, terminating when any source in sources is found.

    Parameters
    ----------
    sources : set
       Starting nodes for path.

    target : node
       Ending node for path.

    pred : dict
       A dictionary of predecessor lists, keyed by node

    Returns
    -------
    paths : generator of lists
        A generator of all paths between source and target.

    Raises
    ------
    NetworkXNoPath
        If `target` cannot be reached from `source`.

    Notes
    -----
    There may be many paths between the sources and target.  If there are
    cycles among the predecessors, this function will not produce all
    possible paths because doing so would produce infinitely many paths
    of unbounded length -- instead, we only produce simple paths.

    See Also
    --------
    shortest_path
    single_source_shortest_path
    all_pairs_shortest_path
    all_shortest_paths
    bellman_ford_path
    zTarget z% cannot be reached from given sourcesr   Nr/   )r   r   r&   r6   addappenddiscard)sourcesr   r[   seenstacktopnodeir:   rR   nexts              r   rZ   rZ     s    P T'&1V WXX8Da[ME
C
(*a7?!)%	#'*:!;<A1<<tDz?QEE#JqM:a=Dt|1HCc%j dAY'!%q	c
1LL1HC% ( =s   AC1C+BC1)C1)NNNr   )NN)Nr   )__doc__networkxr   __all___dispatchabler	   r   r   r   r   r   r   rZ    r-   r   <module>rp      s     ( X&D 'DN X&L 'L^ X&p 'pf X&JB 'JBZ X&EI 'EIP X&8
 '8
v@r-   