U
    9vfe                     @   s   d Z ddlZddlmZ dddddd	d
g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eccentricitydiameterradius	peripherycenter
barycenterresistance_distancec                    s
  t |  }t||jd}t|}d}t | d t | |t| }|d|d|r|rf|}	n|}	| }tj| |	|d}
t|
|krd}t	|t|

 }d}d}|D ]~}|
| }t | t|||   |< }t| ||  |< }t | t | t| t| q|dkrV fdd	|D }n|d
krz fdd	|D }nf|dkr fdd	|D }nB|dkr fdd	|D }n|dkrt }nd}t|| fdd|D  ||8 }|D ]}|dksJ |  | kr8|| || ksJ |  | k rN|}|dks| | kr||| || ks| | kr|}qqV|dkrS |d
krS |dkrև fdd| D }|S |dkr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

    weight : string, function, or None
        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.

        If this is None, every edge has weight/distance/cost 1.

        Weights stored as floating point values can lead to small round-off
        errors in distances. Use integer weights to avoid this.

        Weights should be positive, since they are distances.

    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 [1]_ and discussed further in [2]_ and [3]_.

    References
    ----------
    .. [1] F. W. Takes, W. A. Kosters,
       "Determining the diameter of small world networks."
       Proceedings of the 20th ACM international conference on Information and knowledge management, 2011
       https://dl.acm.org/doi/abs/10.1145/2063576.2063748
    .. [2] F. W. Takes, W. A. Kosters,
       "Computing the Eccentricity Distribution of Large Graphs."
       Algorithms, 2013
       https://www.mdpi.com/1999-4893/6/1/100
    .. [3] M. Borassi, P. Crescenzi, M. Habib, W. A. Kosters, A. Marino, F. W. Takes,
       "Fast diameter and radius BFS-based computation in (weakly connected) real-world graphs: With an application to the six degrees of separation games. "
       Theoretical Computer Science, 2015
       https://www.sciencedirect.com/science/article/pii/S0304397515001644
    )keyFr   sourceweightz5Cannot compute metric because graph is not connected.Nr   c                    s,   h | ]$}| krd  |  kr|qS )    .0i	ecc_lower	ecc_uppermaxlowermaxupperr   I/tmp/pip-unpacked-wheel-_lngutwb/networkx/algorithms/distance_measures.py	<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 | ]0} | krks0| d  d k r|qS r   r   r   r   r   r   r      s
    ZeccentricitieszTcompute 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                    s   g | ]} | kr|qS r   r   r   v)r   r   r   r   
<listcomp>   s      z%_extrema_bounding.<locals>.<listcomp>c                    s   g | ]} | kr|qS r   r   r    )r   r   r   r   r"      s      )dictZdegreemaxgetlenfromkeyssetnxshortest_path_lengthNetworkXErrorvaluesmin
ValueErrorupdate)Gcomputer   degreesZminlowernodeNhigh
candidatesZmaxuppernodecurrentdistmsgZcurrent_eccr   dlowZuppZ	ruled_outpcr   )r   r   r   r   r   r   r   _extrema_bounding   s    I
	 










r=   c                 C   s   |   }i }| |D ]}|dkr<tj| ||d}t|}nDz|| }t|}W n. tk
r~ }	 ztd|	W 5 d}	~	X Y nX ||kr|  rd}
nd}
t|
t|	 ||< q|| k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

    weight : string, function, or None (default=None)
        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.

        If this is None, every edge has weight/distance/cost 1.

        Weights stored as floating point values can lead to small round-off
        errors in distances. Use integer weights to avoid this.

        Weights should be positive, since they are distances.

    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}

    Nr   z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)
orderZnbunch_iterr)   r*   r&   	TypeErrorr+   is_directedr$   r,   )r0   r!   spr   r>   enlengthLerrr8   r   r   r   r      s*    :

Fc                 C   sF   |dkr&|dkr&|   s&t| d|dS |dkr:t| |d}t| S )aw  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.

    weight : string, function, or None
        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.

        If this is None, every edge has weight/distance/cost 1.

        Weights stored as floating point values can lead to small round-off
        errors in distances. Use integer weights to avoid this.

        Weights should be positive, since they are distances.

    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   r1   r   r   r@   r=   r   r$   r,   r0   rB   	useboundsr   r   r   r   r   F  s
    0c                    s^   |dkr&dkr&|   s&t| d|dS dkr:t| |d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.

    weight : string, function, or None
        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.

        If this is None, every edge has weight/distance/cost 1.

        Weights stored as floating point values can lead to small round-off
        errors in distances. Use integer weights to avoid this.

        Weights should be positive, since they are distances.

    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   rG   rH   c                    s   g | ]}|  kr|qS r   r   r    r   rB   r   r   r"     s      zperiphery.<locals>.<listcomp>rI   r0   rB   rK   r   r;   r   rL   r   r   }  s    1c                 C   sF   |dkr&|dkr&|   s&t| d|dS |dkr:t| |d}t| S )aD  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.

    weight : string, function, or None
        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.

        If this is None, every edge has weight/distance/cost 1.

        Weights stored as floating point values can lead to small round-off
        errors in distances. Use integer weights to avoid this.

        Weights should be positive, since they are distances.

    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   rG   rH   r@   r=   r   r-   r,   rJ   r   r   r   r     s
    -c                    s^   |dkr& dkr&|   s&t| d|dS  dkr:t| |d 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.

    weight : string, function, or None
        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.

        If this is None, every edge has weight/distance/cost 1.

        Weights stored as floating point values can lead to small round-off
        errors in distances. Use integer weights to avoid this.

        Weights should be positive, since they are distances.

    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   rG   rH   c                    s   g | ]} | kr|qS r   r   r    rB   r   r   r   r"   !  s      zcenter.<locals>.<listcomp>rN   rM   r   rO   r   r     s    1c           
      C   s   |dkrt j| |d}n| }|dk	r0tdtdg t|   }}}|D ]n\}}t||k rrt d|  dt| }	|dk	r|	| j	| |< |	|k r|	}|g}qL|	|krL|
| qL|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
    NrH   z-Cannot use both sp, weight arguments togetherinfzInput graph zH is disconnected, so every induced subgraph has infinite barycentricity.)r)   r*   itemsr.   floatr&   ZNetworkXNoPathsumr,   Znodesappend)
r0   r   attrrA   smallestZbarycenter_verticesrC   r!   distsZbarycentricityr   r   r   r   %  s(    6
c                 C   sT   d}|   }tt|D ]6}||| kr|d7 }||}|| ||< |||< q|S )z=Counts the number of permutations in SuperLU perm_c or perm_rr   r   )tolistranger&   index)Z
perm_arrayZperm_cntZarrr   rC   r   r   r   _count_lu_permutationss  s    

r[   ZdirectedTc                 C   s  ddl }ddl}ddl}t| s2d}t|nF|| krJd}t|n.|| krbd}t|n||krxd}t||  } t| }	|r|dk	r|  r| j	dddD ]\}
}}}d	||  ||< qn(| j	dd
D ]\}
}}d	||  ||< qtj
| |	|dd}tt|jd }||	| ||ddf dd|f }||	| ||ddf dd|f }|jjj|ddid}|j }|||||j  }|dt|j 9 }|dt|j 9 }||}||}|jjj|ddid}|j }|||||j  }|dt|j 9 }|dt|j 9 }||}||}||||d	g|}|| | }|S )av  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
    -----
    Overviews are provided in [1]_ and [2]_. Additional details on computational
    methods, proofs of properties, and corresponding MATLAB codes are provided
    in [3]_.

    References
    ----------
    .. [1] Wikipedia
       "Resistance distance."
       https://en.wikipedia.org/wiki/Resistance_distance
    .. [2] E. W. Weisstein
       "Resistance Distance."
       MathWorld--A Wolfram Web Resource
       https://mathworld.wolfram.com/ResistanceDistance.html
    .. [3] V. S. S. Vos,
       "Methods for determining the effective resistance."
       Mestrado, Mathematisch Instituut Universiteit Leiden, 2016
       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   )r]   rH   ZcscZSymmetricMode)options)ZnumpyscipyZscipy.sparse.linalgr)   Zis_connectedr+   copylistZis_multigraphedgesZlaplacian_matrixZasformatrY   shaperemoverZ   sparseZlinalgZspluUZdiagonalproductsignrE   r[   Zperm_rZperm_cabsolutesortdividerT   )r0   ZnodeAZnodeBr   Zinvert_weightnprA   r`   r8   Z	node_listur!   kr9   rE   indicesZL_aZL_abZlu_aZLdiagAZLdiagA_sZlu_abZLdiagABZ	LdiagAB_sZLdetrdr   r   r   r	     s\    =


 


 

)r   N)NNN)NFN)NFN)NFN)NFN)NNN)NT)__doc__Znetworkxr)   Znetworkx.utilsr   __all__r=   r   r   r   r   r   r   r[   r	   r   r   r   r   <module>   s*   
 ^
X
7
:
4
:
N