o
    ˷eY                     @   s   d Z ddlZddlmZ g dZdddZddd	Zdd
dZdddZ	dddZ
dddZdddZdddZdd Zedd ddZdS )!z:Graph diameter, radius, eccentricity and other properties.    N)not_implemented_for)extrema_boundingeccentricitydiameterradius	peripherycenter
barycenterresistance_distancer   c                 C   sP   ddl }d}|dv r|d| d7 }|dkr|d7 }|j|td	d
 t| |dS )a  Compute requested extreme distance metric of undirected graph G

    .. deprecated:: 2.8

       extrema_bounding is deprecated and will be removed in NetworkX 3.0.
       Use the corresponding distance measure with the `usebounds=True` option
       instead.

    Computation is based on smart lower and upper bounds, and in practice
    linear in the number of nodes, rather than quadratic (except for some
    border cases such as complete graphs or circle shaped graphs).

    Parameters
    ----------
    G : NetworkX graph
       An undirected graph

    compute : string denoting the requesting metric
       "diameter" for the maximal eccentricity value,
       "radius" for the minimal eccentricity value,
       "periphery" for the set of nodes with eccentricity equal to the diameter,
       "center" for the set of nodes with eccentricity equal to the radius,
       "eccentricities" for the maximum distance from each node to all other nodes in G

    Returns
    -------
    value : value of the requested metric
       int for "diameter" and "radius" or
       list of nodes for "center" and "periphery" or
       dictionary of eccentricity values keyed by node for "eccentricities"

    Raises
    ------
    NetworkXError
        If the graph consists of multiple components
    ValueError
        If `compute` is not one of "diameter", "radius", "periphery", "center",
        or "eccentricities".

    Notes
    -----
    This algorithm was proposed in the following papers:

    F.W. Takes and W.A. Kosters, Determining the Diameter of Small World
    Networks, in Proceedings of the 20th ACM International Conference on
    Information and Knowledge Management (CIKM 2011), pp. 1191-1196, 2011.
    doi: https://doi.org/10.1145/2063576.2063748

    F.W. Takes and W.A. Kosters, Computing the Eccentricity Distribution of
    Large Graphs, Algorithms 6(1): 100-118, 2013.
    doi: https://doi.org/10.3390/a6010100

    M. Borassi, P. Crescenzi, M. Habib, W.A. Kosters, A. Marino and F.W. Takes,
    Fast Graph Diameter and Radius BFS-Based Computation in (Weakly Connected)
    Real-World Graphs, Theoretical Computer Science 586: 59-80, 2015.
    doi: https://doi.org/10.1016/j.tcs.2015.02.033
    r   NzCextrema_bounding is deprecated and will be removed in networkx 3.0
>   r   r   r   r   zUse nx.z(G, usebounds=True) instead.eccentricitieszUse nx.eccentricity(G) instead.   )
stacklevelcompute)warningswarnDeprecationWarning_extrema_bounding)Gr   r   msg r   \/var/www/ideatree/venv/lib/python3.10/site-packages/networkx/algorithms/distance_measures.pyr      s   :r   c                    s   t |  }t||jd}t|}d}t | d t | |t| }|d|d|rG|r3|}n|}| }t t| |}	t|	|krMd}
t	|
t|	
 }d}d}|D ]?}|	| }t | t|||   |< }t| ||  |< }t | t | t| t| qY|dkr fdd|D }nA|d	kr fd
d|D }n0|dkṙ fdd|D }n|dkr݇ fdd|D }n|dkrt }nd}
t|
| fdd|D  ||8 }|D ]F}|du s  |  | kr|| || ks  |  | k r"|}|du sB| | kr9|| || ksB| | krD|}q|s.|dkrNS |d	krUS |dkrf fdd| D }|S |dkrwfdd| D }|S |dkr~ S dS )a  Compute requested extreme distance metric of undirected graph G

    Computation is based on smart lower and upper bounds, and in practice
    linear in the number of nodes, rather than quadratic (except for some
    border cases such as complete graphs or circle shaped graphs).

    Parameters
    ----------
    G : NetworkX graph
       An undirected graph

    compute : string denoting the requesting metric
       "diameter" for the maximal eccentricity value,
       "radius" for the minimal eccentricity value,
       "periphery" for the set of nodes with eccentricity equal to the diameter,
       "center" for the set of nodes with eccentricity equal to the radius,
       "eccentricities" for the maximum distance from each node to all other nodes in G

    Returns
    -------
    value : value of the requested metric
       int for "diameter" and "radius" or
       list of nodes for "center" and "periphery" or
       dictionary of eccentricity values keyed by node for "eccentricities"

    Raises
    ------
    NetworkXError
        If the graph consists of multiple components
    ValueError
        If `compute` is not one of "diameter", "radius", "periphery", "center", or "eccentricities".
    Notes
    -----
    This algorithm was proposed in the following papers:

    F.W. Takes and W.A. Kosters, Determining the Diameter of Small World
    Networks, in Proceedings of the 20th ACM International Conference on
    Information and Knowledge Management (CIKM 2011), pp. 1191-1196, 2011.
    doi: https://doi.org/10.1145/2063576.2063748

    F.W. Takes and W.A. Kosters, Computing the Eccentricity Distribution of
    Large Graphs, Algorithms 6(1): 100-118, 2013.
    doi: https://doi.org/10.3390/a6010100

    M. Borassi, P. Crescenzi, M. Habib, W.A. Kosters, A. Marino and F.W. Takes,
    Fast Graph Diameter and Radius BFS-Based Computation in (Weakly Connected)
    Real-World Graphs, Theoretical Computer Science 586: 59-80, 2015.
    doi: https://doi.org/10.1016/j.tcs.2015.02.033
    )keyFr   z5Cannot compute metric because graph is not connected.Nr   c                    s,   h | ]}| krd  |  kr|qS )r   r   .0i	ecc_lower	ecc_uppermaxlowermaxupperr   r   	<setcomp>   s
    z$_extrema_bounding.<locals>.<setcomp>r   c                    s0   h | ]} | kr| d  d kr|qS    r   r   r   r   r   minlowerminupperr   r   r!      s
     r   c                    s0   h | ]}| k rks | kr|qS r   r   r   r   r   r   r!      s    r   c                    s8   h | ]} | krks| d  d k r|qS r"   r   r   r$   r   r   r!      s    r   zTcompute must be one of 'diameter', 'radius', 'periphery', 'center', 'eccentricities'c                 3   s$    | ]} | | kr|V  qd S )Nr   r   )r   r   r   r   	<genexpr>   s   " z$_extrema_bounding.<locals>.<genexpr>c                       g | ]
} | kr|qS r   r   r   v)r   r   r   r   
<listcomp>      z%_extrema_bounding.<locals>.<listcomp>c                    r(   r   r   r)   )r   r&   r   r   r+     r,   )dictdegreemaxgetlenfromkeyssetnx"single_source_shortest_path_lengthNetworkXErrorvaluesmin
ValueErrorupdate)r   r   degreesminlowernodeNhigh
candidatesmaxuppernodecurrentdistr   current_eccr   dlowupp	ruled_outpcr   )r   r   r   r    r%   r&   r   r   Y   s   4
	 


s



r   c           
      C   s   |   }i }| |D ]H}|du rt| |}t|}nz
|| }t|}W n ty8 } ztd|d}~ww ||krK|  rDd}	nd}	t|	t|	 ||< q|| v r\|| S |S )a  Returns the eccentricity of nodes in G.

    The eccentricity of a node v is the maximum distance from v to
    all other nodes in G.

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

    v : node, optional
       Return value of specified node

    sp : dict of dicts, optional
       All pairs shortest path lengths as a dictionary of dictionaries

    Returns
    -------
    ecc : dictionary
       A dictionary of eccentricity values keyed by node.

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> dict(nx.eccentricity(G))
    {1: 2, 2: 3, 3: 2, 4: 2, 5: 3}

    >>> dict(nx.eccentricity(G, v=[1, 5]))  # This returns the eccentrity of node 1 & 5
    {1: 2, 5: 3}

    NzFormat of "sp" is invalid.zHFound infinite path length because the digraph is not strongly connectedz=Found infinite path length because the graph is not connected)
ordernbunch_iterr4   r5   r1   	TypeErrorr6   is_directedr/   r7   )
r   r*   sprJ   enlengthLerrr   r   r   r   r      s.   &

r   Fc                 C   @   |du r|du r|   st| ddS |du rt| }t| S )a  Returns the diameter of the graph G.

    The diameter is the maximum eccentricity.

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

    e : eccentricity dictionary, optional
      A precomputed dictionary of eccentricities.

    Returns
    -------
    d : integer
       Diameter of graph

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> nx.diameter(G)
    3

    See Also
    --------
    eccentricity
    TNr   r   rM   r   r   r/   r7   r   rO   	useboundsr   r   r   r   e  s
   c                    sX   |du rdu r|   st| ddS du rt| t   fddD }|S )a  Returns the periphery of the graph G.

    The periphery is the set of nodes with eccentricity equal to the diameter.

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

    e : eccentricity dictionary, optional
      A precomputed dictionary of eccentricities.

    Returns
    -------
    p : list
       List of nodes in periphery

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> nx.periphery(G)
    [2, 5]

    See Also
    --------
    barycenter
    center
    TNr   r   c                    s   g | ]
}|  kr|qS r   r   r)   r   rO   r   r   r+     r,   zperiphery.<locals>.<listcomp>rU   r   rO   rW   rH   r   rX   r   r        r   c                 C   rT   )a  Returns the radius of the graph G.

    The radius is the minimum eccentricity.

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

    e : eccentricity dictionary, optional
      A precomputed dictionary of eccentricities.

    Returns
    -------
    r : integer
       Radius of graph

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> nx.radius(G)
    2

    TNr   r   rM   r   r   r8   r7   rV   r   r   r   r     s
   r   c                    sX   |du r du r|   st| ddS  du rt|  t   fdd D }|S )a  Returns the center of the graph G.

    The center is the set of nodes with eccentricity equal to radius.

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

    e : eccentricity dictionary, optional
      A precomputed dictionary of eccentricities.

    Returns
    -------
    c : list
       List of nodes in center

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> list(nx.center(G))
    [1, 3, 4]

    See Also
    --------
    barycenter
    periphery
    TNr   r   c                    r(   r   r   r)   rO   r   r   r   r+     r,   zcenter.<locals>.<listcomp>r[   rY   r   r\   r   r     rZ   r   c           
      C   s   |du rt j| |d}n| }|durtdtdg t| }}}|D ]7\}}t||k r9t d|  dt| }	|durJ|	| j	| |< |	|k rT|	}|g}q&|	|kr]|
| q&|S )aZ  Calculate barycenter of a connected graph, optionally with edge weights.

    The :dfn:`barycenter` a
    :func:`connected <networkx.algorithms.components.is_connected>` graph
    :math:`G` is the subgraph induced by the set of its nodes :math:`v`
    minimizing the objective function

    .. math::

        \sum_{u \in V(G)} d_G(u, v),

    where :math:`d_G` is the (possibly weighted) :func:`path length
    <networkx.algorithms.shortest_paths.generic.shortest_path_length>`.
    The barycenter is also called the :dfn:`median`. See [West01]_, p. 78.

    Parameters
    ----------
    G : :class:`networkx.Graph`
        The connected graph :math:`G`.
    weight : :class:`str`, optional
        Passed through to
        :func:`~networkx.algorithms.shortest_paths.generic.shortest_path_length`.
    attr : :class:`str`, optional
        If given, write the value of the objective function to each node's
        `attr` attribute. Otherwise do not store the value.
    sp : dict of dicts, optional
       All pairs shortest path lengths as a dictionary of dictionaries

    Returns
    -------
    list
        Nodes of `G` that induce the barycenter of `G`.

    Raises
    ------
    NetworkXNoPath
        If `G` is disconnected. `G` may appear disconnected to
        :func:`barycenter` if `sp` is given but is missing shortest path
        lengths for any pairs.
    ValueError
        If `sp` and `weight` are both given.

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> nx.barycenter(G)
    [1, 3, 4]

    See Also
    --------
    center
    periphery
    Nweightz-Cannot use both sp, weight arguments togetherinfzInput graph zH is disconnected, so every induced subgraph has infinite barycentricity.)r4   shortest_path_lengthitemsr9   floatr1   NetworkXNoPathsumr7   nodesappend)
r   r^   attrrN   smallestbarycenter_verticesrP   r*   distsbarycentricityr   r   r   r	     s*   6

r	   c                 C   sT   d}|   }tt|D ]}||| kr'|d7 }||}|| ||< |||< q|S )z=Counts the number of permutations in SuperLU perm_c or perm_rr   r#   )tolistranger1   index)
perm_arrayperm_cntarrr   rP   r   r   r   _count_lu_permutationsB  s   
rr   directedTc                 C   s  ddl }ddl}ddl}t| sd}t||| vr#d}t||| vr.d}t|||kr9d}t||  } t| }	|rv|durv|  rb| j	dddD ]\}
}}}d	||  ||< qRn| j	dd
D ]\}
}}d	||  ||< qhtj
| |	|dd}tt|jd }||	| ||ddf dd|f }||	| ||ddf dd|f }|jjj|tddd}|j }|||||j  }|dt|j 9 }|dt|j 9 }||}||}|jjj|tddd}|j }|||||j  }|dt|j 9 }|dt|j 9 }||}||}||||d	g|}|| | }|S )un  Returns the resistance distance between node A and node B on graph G.

    The resistance distance between two nodes of a graph is akin to treating
    the graph as a grid of resistorses with a resistance equal to the provided
    weight.

    If weight is not provided, then a weight of 1 is used for all edges.

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

    nodeA : node
      A node within graph G.

    nodeB : node
      A node within graph G, exclusive of Node A.

    weight : string or None, optional (default=None)
       The edge data key used to compute the resistance distance.
       If None, then each edge has weight 1.

    invert_weight : boolean (default=True)
        Proper calculation of resistance distance requires building the
        Laplacian matrix with the reciprocal of the weight. Not required
        if the weight is already inverted. Weight cannot be zero.

    Returns
    -------
    rd : float
       Value of effective resistance distance

    Examples
    --------
    >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
    >>> nx.resistance_distance(G, 1, 3)
    0.625

    Notes
    -----
    Overview discussion:
    * https://en.wikipedia.org/wiki/Resistance_distance
    * http://mathworld.wolfram.com/ResistanceDistance.html

    Additional details:
    Vaya Sapobi Samui Vos, “Methods for determining the effective resistance,” M.S.,
    Mathematisch Instituut, Universiteit Leiden, Leiden, Netherlands, 2016
    Available: `Link to thesis <https://www.universiteitleiden.nl/binaries/content/assets/science/mi/scripties/master/vos_vaya_master.pdf>`_
    r   Nz#Graph G must be strongly connected.zNode A is not in graph G.zNode B is not in graph G.z%Node A and Node B cannot be the same.T)keysdatar#   )ru   r]   csc)SymmetricMode)options) numpyscipyscipy.sparse.linalgr4   is_connectedr6   copylistis_multigraphedgeslaplacian_matrixasformatrm   shaperemovern   sparselinalgsplur-   UdiagonalproductsignrR   rr   perm_rperm_cabsolutesortdividerf   )r   nodeAnodeBr^   invert_weightnprN   r{   r   	node_listur*   krD   rR   indicesL_aL_ablu_aLdiagALdiagA_slu_abLdiagAB	LdiagAB_sLdetrdr   r   r   r
   P  s^   4





 


 

r
   )r   )NN)NF)NNN)NT)__doc__networkxr4   networkx.utilsr   __all__r   r   r   r   r   r   r   r	   rr   r
   r   r   r   r   <module>   s     

G 
H
E
#
&
 
&N