o
    3ήc-                  	   @   s   d Z ddlZddlmZmZmZmZ ddlm	Z	m
Z
mZ g dZe
de	ddded	d
ddfddZe	ddded	fddZe	ddded	fddZdS )z-Current-flow betweenness centrality measures.    N)CGInverseLaplacianFullInverseLaplacianSuperLUInverseLaplacianflow_matrix_row)not_implemented_forpy_random_statereverse_cuthill_mckee_ordering)#current_flow_betweenness_centrality/approximate_current_flow_betweenness_centrality(edge_current_flow_betweenness_centrality   directedTfullg      ?i'  c                    s  ddl }t| stdtttd}	|  }
tt	| t
| ttt|
}tj|t|
|dd}||}|	| ||d}t|d}|
d	 |
d
  }|
|
d  | }d}|t||| d ||
  }||krd| d| d}t|d|d|  }t|D ]R}|t|
d \}}}|j|
|d}d||< d||< ||}|D ]-}||v rq|| D ]!}|| | |d	}||  |||| ||   | 7  < qqq|rd	 n|d
   fdd| D S )a  Compute the approximate current-flow betweenness centrality for nodes.

    Approximates the current-flow betweenness centrality within absolute
    error of epsilon with high probability [1]_.


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

    normalized : bool, optional (default=True)
      If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
      n is the number of nodes in G.

    weight : string or None, optional (default=None)
      Key for edge data used as the edge weight.
      If None, then use 1 as each edge weight.
      The weight reflects the capacity or the strength of the
      edge.

    dtype : data type (float)
      Default data type for internal matrices.
      Set to np.float32 for lower memory consumption.

    solver : string (default='full')
       Type of linear solver to use for computing the flow matrix.
       Options are "full" (uses most memory), "lu" (recommended), and
       "cg" (uses least memory).

    epsilon: float
        Absolute error tolerance.

    kmax: int
       Maximum number of sample node pairs to use for approximation.

    seed : integer, random_state, or None (default)
        Indicator of random number generation state.
        See :ref:`Randomness<randomness>`.

    Returns
    -------
    nodes : dictionary
       Dictionary of nodes with betweenness centrality as the value.

    See Also
    --------
    current_flow_betweenness_centrality

    Notes
    -----
    The running time is $O((1/\epsilon^2)m{\sqrt k} \log n)$
    and the space required is $O(m)$ for $n$ nodes and $m$ edges.

    If the edges have a 'weight' attribute they will be used as
    weights in this algorithm.  Unspecified weights are set to 1.

    References
    ----------
    .. [1] Ulrik Brandes and Daniel Fleischer:
       Centrality Measures Based on Current Flow.
       Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
       LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
       https://doi.org/10.1007/978-3-540-31856-9_44
    r   NGraph not connected.)r   lucg)nodelistweightcsc)dtype              ?       @      zNumber random pairs k>kmax (>z) zIncrease kmax or epsilonc                    s   i | ]\}}| |  qS  r   .0kvfactororderingr   ^/tmp/pip-target-vg8gfxp4/lib/python/networkx/algorithms/centrality/current_flow_betweenness.py
<dictcomp>   s    zCapproximate_current_flow_betweenness_centrality.<locals>.<dictcomp>)numpynxis_connectedNetworkXErrorr   r   r   number_of_nodeslistr   relabel_nodesdictziprangelaplacian_matrixasformatastypefromkeysintceillogsamplezerossolvegetabsitems)G
normalizedr   r   solverepsilonkmaxseednp
solvernamenHLCbetweennessnbcstarlr    msgcstar2k_stpairbpr!   nbrwr   r"   r%   r
      sP   M


$
,r
   c                    s8  t | s
t d|  }tt|  t | tt t	|}t
|d}t||||dD ]A\}\}	}
tt| ddd t	|}t	|D ]&}||	  |||  ||  7  < ||
  || d ||  ||  7  < qIq/|r||d |d  }nd}|D ]}t|| | d | ||< q fd	d
| D S )a	  Compute current-flow betweenness centrality for nodes.

    Current-flow betweenness centrality uses an electrical current
    model for information spreading in contrast to betweenness
    centrality which uses shortest paths.

    Current-flow betweenness centrality is also known as
    random-walk betweenness centrality [2]_.

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

    normalized : bool, optional (default=True)
      If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
      n is the number of nodes in G.

    weight : string or None, optional (default=None)
      Key for edge data used as the edge weight.
      If None, then use 1 as each edge weight.
      The weight reflects the capacity or the strength of the
      edge.

    dtype : data type (float)
      Default data type for internal matrices.
      Set to np.float32 for lower memory consumption.

    solver : string (default='full')
       Type of linear solver to use for computing the flow matrix.
       Options are "full" (uses most memory), "lu" (recommended), and
       "cg" (uses least memory).

    Returns
    -------
    nodes : dictionary
       Dictionary of nodes with betweenness centrality as the value.

    See Also
    --------
    approximate_current_flow_betweenness_centrality
    betweenness_centrality
    edge_betweenness_centrality
    edge_current_flow_betweenness_centrality

    Notes
    -----
    Current-flow betweenness can be computed in  $O(I(n-1)+mn \log n)$
    time [1]_, where $I(n-1)$ is the time needed to compute the
    inverse Laplacian.  For a full matrix this is $O(n^3)$ but using
    sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
    Laplacian matrix condition number.

    The space required is $O(nw)$ where $w$ is the width of the sparse
    Laplacian matrix.  Worse case is $w=n$ for $O(n^2)$.

    If the edges have a 'weight' attribute they will be used as
    weights in this algorithm.  Unspecified weights are set to 1.

    References
    ----------
    .. [1] Centrality Measures Based on Current Flow.
       Ulrik Brandes and Daniel Fleischer,
       Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
       LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
       https://doi.org/10.1007/978-3-540-31856-9_44

    .. [2] A measure of betweenness centrality based on random walks,
       M. E. J. Newman, Social Networks 27, 39-54 (2005).
    r   r   r   r   r@   Nr   r   r   r   c                    s   i | ]	\}} | |qS r   r   r   r$   r   r%   r&      s    z7current_flow_betweenness_centrality.<locals>.<dictcomp>)r(   r)   r*   r+   r,   r   r-   r.   r/   r0   r4   r   argsortfloatr=   )r>   r?   r   r   r@   rF   rG   rJ   rowrQ   rR   posirK   r!   r   rY   r%   r	      s$   
J
  *r	   c                    s6  t | s
t d|  }tt|  t | tt t	|}dd |
 D }t|d}|r;|d |d  }	nd}	t||||dD ]J\}
}tt|
 ddd	 t	d
|d
 }t	|D ]&}||  |d
 ||  |
|  7  < ||  || ||  |
|  7  < q`||  |	  < qE fdd| D S )a(
  Compute current-flow betweenness centrality for edges.

    Current-flow betweenness centrality uses an electrical current
    model for information spreading in contrast to betweenness
    centrality which uses shortest paths.

    Current-flow betweenness centrality is also known as
    random-walk betweenness centrality [2]_.

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

    normalized : bool, optional (default=True)
      If True the betweenness values are normalized by 2/[(n-1)(n-2)] where
      n is the number of nodes in G.

    weight : string or None, optional (default=None)
      Key for edge data used as the edge weight.
      If None, then use 1 as each edge weight.
      The weight reflects the capacity or the strength of the
      edge.

    dtype : data type (default=float)
      Default data type for internal matrices.
      Set to np.float32 for lower memory consumption.

    solver : string (default='full')
       Type of linear solver to use for computing the flow matrix.
       Options are "full" (uses most memory), "lu" (recommended), and
       "cg" (uses least memory).

    Returns
    -------
    nodes : dictionary
       Dictionary of edge tuples with betweenness centrality as the value.

    Raises
    ------
    NetworkXError
        The algorithm does not support DiGraphs.
        If the input graph is an instance of DiGraph class, NetworkXError
        is raised.

    See Also
    --------
    betweenness_centrality
    edge_betweenness_centrality
    current_flow_betweenness_centrality

    Notes
    -----
    Current-flow betweenness can be computed in $O(I(n-1)+mn \log n)$
    time [1]_, where $I(n-1)$ is the time needed to compute the
    inverse Laplacian.  For a full matrix this is $O(n^3)$ but using
    sparse methods you can achieve $O(nm{\sqrt k})$ where $k$ is the
    Laplacian matrix condition number.

    The space required is $O(nw)$ where $w$ is the width of the sparse
    Laplacian matrix.  Worse case is $w=n$ for $O(n^2)$.

    If the edges have a 'weight' attribute they will be used as
    weights in this algorithm.  Unspecified weights are set to 1.

    References
    ----------
    .. [1] Centrality Measures Based on Current Flow.
       Ulrik Brandes and Daniel Fleischer,
       Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05).
       LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
       https://doi.org/10.1007/978-3-540-31856-9_44

    .. [2] A measure of betweenness centrality based on random walks,
       M. E. J. Newman, Social Networks 27, 39-54 (2005).
    r   c                 s   s$    | ]\}}t t||fV  qd S )N)tuplesorted)r   ur!   r   r   r%   	<genexpr>H  s   " z;edge_current_flow_betweenness_centrality.<locals>.<genexpr>r   r   r   rX   Nr   r   c                    s&   i | ]\\}}} |  | f|qS r   r   )r   rQ   rR   r!   rY   r   r%   r&   T  s   & z<edge_current_flow_betweenness_centrality.<locals>.<dictcomp>)r(   r)   r*   r+   r,   r   r-   r.   r/   r0   edgesr4   r   rZ   r=   )r>   r?   r   r   r@   rF   rG   rc   rJ   rK   r\   er]   r^   r   rY   r%   r      s"   
P
&$&r   )__doc__networkxr(   *networkx.algorithms.centrality.flow_matrixr   r   r   r   networkx.utilsr   r   r   __all__r[   r
   r	   r   r   r   r   r%   <module>   s*    y_