
    hR                        S r SSKJr  SSKrSSKJrJrJr  / SQr	 " S S5      r
 " S S	5      rS
 rS rS rS r\" S5      \" S5      \R                   " SS9 SS j5       5       5       r\" S5      \" S5      \R                   " SS9 SS j5       5       5       r\" S5      \R                   " SS9 SS j5       5       r\R                   " SS9 SS j5       rg)zB
Algebraic connectivity and Fiedler vectors of undirected graphs.
    )partialN)not_implemented_fornp_random_statereverse_cuthill_mckee_ordering)algebraic_connectivityfiedler_vectorspectral_orderingspectral_bisectionc                   *    \ rS rSrSrS rS rS rSrg)
_PCGSolver   a  Preconditioned conjugate gradient method.

To solve Ax = b:
    M = A.diagonal() # or some other preconditioner
    solver = _PCGSolver(lambda x: A * x, lambda x: M * x)
    x = solver.solve(b)

The inputs A and M are functions which compute
matrix multiplication on the argument.
A - multiply by the matrix A in Ax=b
M - multiply by M, the preconditioner surrogate for A

Warning: There is no limit on number of iterations.
c                     Xl         X l        g N_A_M)selfAMs      W/var/www/html/env/lib/python3.13/site-packages/networkx/linalg/algebraicconnectivity.py__init___PCGSolver.__init__&   s        c                     SS K nUR                  U5      nUR                  UR                  SS9n[	        UR                  S   5       H#  nU R                  US S 2U4   U5      US S 2U4'   M%     U$ Nr   Forder   )numpyasarrayndarrayshaperange_solver   BtolnpXjs         r   solve_PCGSolver.solve*   sf     JJqMJJqwwcJ*qwwqz"Akk!AqD'3/AadG #r   c                 X   SS K nSS KnU R                  nU R                  nX$R                  R
                  R                  U5      -  nUR                  UR                  5      nUR                  5       nU" U5      n	UR                  R
                  R                  X5      n
U	R                  5       n U" U5      nXR                  R
                  R                  X5      -  nUR                  R
                  R                  XUS9nUR                  R
                  R                  XU* S9nUR                  R
                  R                  U5      U:  a  U$ U" U5      n	UR                  R
                  R                  X5      nX-  UpUR                  R
                  R                  XUS9nM  )Nr   )a)r    scipyr   r   linalgblasdasumzerosr#   copyddotdaxpy)r   br(   r)   spr   r   xrzrzpApalphabetas                  r   r%   _PCGSolver._solve4   sM   GGGGyy~~##A&&HHQWWFFHaDYY^^  &FFH1B,,Q33E		$$QU$3A		$$Ruf$5Ayy~~##A&,!A99>>&&q,Dy$"		$$QT$2A r   r   N)	__name__
__module____qualname____firstlineno____doc__r   r,   r%   __static_attributes__ r   r   r   r      s    3r   r   c                   (    \ rS rSrSrS rSS jrSrg)	_LUSolverO   zLU factorization.

To solve Ax = b:
    solver = _LUSolver(A)
    x = solver.solve(b)

optional argument `tol` on solve method is ignored but included
to match _PCGsolver API.
c                 h    SS K nUR                  R                  R                  USSSSS.S9U l        g )Nr   MMD_AT_PLUS_A        T)EquilSymmetricMode)
permc_specdiag_pivot_threshoptions)r0   sparser1   splu_LU)r   r   r9   s      r   r   _LUSolver.__init__Z   s7    99##((&!"T:	 ) 
r   Nc                     SS K nUR                  U5      nUR                  UR                  SS9n[	        UR                  S   5       H,  nU R
                  R                  US S 2U4   5      US S 2U4'   M.     U$ r   )r    r!   r"   r#   r$   rW   r,   r&   s         r   r,   _LUSolver.solved   sf    JJqMJJqwwcJ*qwwqz"AhhnnQq!tW-AadG #r   )rW   r   )rC   rD   rE   rF   rG   r   r,   rH   rI   r   r   rK   rK   O   s    
r   rK   c                   ^ ^ T R                  5       (       aO  [        R                  " 5       nUR                  T 5        UR	                  U4S jT R                  SS9 5       TS9  Um T R                  5       (       d  U4S jT R                  SS9 5       nOU U4S jT R                  5        5       n[        R                  " 5       nUR                  T 5        UR	                  S U 5       5        U$ )z5Compute edge weights and eliminate zero-weight edges.c              3   `   >#    U  H#  u  po1U:w  d  M  XUR                  TS 5      4v   M%     g7f      ?N)get.0uveweights       r   	<genexpr>$_preprocess_graph.<locals>.<genexpr>t   s/     T7IGA!RSV'aAEE&#&'7Is   ..T)data)re   c           	   3   r   >#    U  H,  u  po1U:w  d  M  X[        UR                  TS 5      5      4v   M.     g7fr]   absr_   r`   s       r   rf   rg   y   s7      
;MaVWQW+Q3quuVS)*+;Ms   7$7c              3      >#    U  H9  u  pX:w  d  M  X[        U4S  jTU   U   R                  5        5       5      4v   M;     g7f)c              3   Z   >#    U  H   n[        UR                  TS 5      5      v   M"     g7fr]   rj   )ra   rd   re   s     r   rf   ._preprocess_graph.<locals>.<genexpr>.<genexpr>~   s&     I8H1s155-..8Hs   (+N)sumvalues)ra   rb   rc   Gre   s      r   rf   rg   }   sA      
!v KQ3I!Q8HIIJ!s
   A2Ac              3   >   #    U  H  u  po3S :w  d  M  XU4v   M     g7f)r   NrI   )ra   rb   rc   rd   s       r   rf   rg      s     GuGA!QiqQius   )is_directednx
MultiGraphadd_nodes_fromadd_weighted_edges_fromedgesis_multigraphGraph)rq   re   Hrx   s   ``  r   _preprocess_graphr|   n   s    }}MMO		!!TqwwDw7IT 	" 	
 ??
;<777;M

	

 	
AQGuGGHr   c                    SSK nU R                  U5      n [        U 5      n[        U5      n[	        [        U[        U5      5      5      nUR                  U[        S9n[        U5       H  u  pxXvXX   '   M     XdS-
  S-  -  nU$ )zEEstimate the Fiedler vector using the reverse Cuthill-McKee ordering.r   Ndtyper          @)
r    subgraphr   lendictzipr$   r"   float	enumerate)	rq   nodelistr)   r   nindexr:   irb   s	            r   _rcm_estimater      s|    	

8A*1-EHAXuQx()E


1E
"A% %( !a%3AHr   c           
        ^ ^^^^ SSK mSSKnUR                  S   mU(       a  TR                  T R	                  5       5      mUR
                  R                  UR
                  R                  ST-  STTSS95      mTT -  T-  m TSTR                  R                  TS5      -  -  mU(       a  UU4S jnOUU4S	 jnUS
:X  a8  T R	                  5       R                  [        5      m[        U 4S jU4S j5      nOUS:X  ah  UR
                  R                  T [        SS9nUR                  SS UR                  SS -
  R                  5       n	TR                   XU	4'   [#        U5      nO[$        R&                  " SU 35      e[)        T 5      R+                  SS9R-                  5       R/                  5       n
U" U5        TR1                  UR                  SS9n TR                  R3                  U5      S   nT U-  USS2SS24'   UR4                  U-  nUR                  R7                  USS9u  pX-  nUR                  R8                  R;                  XSS2S4   -  US   USS2S4   -  -
  5      U
-  nX:  a  OdUR=                  X5      USS2SS24'   UR                  R?                  UR4                  U-  5      UR4                  -  R4                  nU" U5        GM  UTRA                  U5      4$ )au  Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.

The Fiedler vector of a connected undirected graph is the eigenvector
corresponding to the second smallest eigenvalue of the Laplacian matrix
of the graph. This function starts with the Laplacian L, not the Graph.

Parameters
----------
L : Laplacian of a possibly weighted or normalized, but undirected graph

X : Initial guess for a solution. Usually a matrix of random numbers.
    This function allows more than one column in X to identify more than
    one eigenvector if desired.

normalized : bool
    Whether the normalized Laplacian matrix is used.

tol : float
    Tolerance of relative residual in eigenvalue computation.
    Warning: There is no limit on number of iterations.

method : string
    Should be 'tracemin_pcg' or 'tracemin_lu'.
    Otherwise exception is raised.

Returns
-------
sigma, X : Two NumPy arrays of floats.
    The lowest eigenvalues and corresponding eigenvectors of L.
    The size of input X determines the size of these outputs.
    As this is for Fiedler vectors, the zero eigenvalue (and
    constant eigenvector) are avoided.
r   Nr   csrformatr^      c                    > TR                  U 5      n [        U R                  S   5       H!  nU SS2U4==   U SS2U4   T-  T-  -  ss'   M#     gz(Make X orthogonal to the nullspace of L.r   N)r!   r$   r#   )r*   r+   rd   r)   s     r   project"_tracemin_fiedler.<locals>.project   sJ    

1A1771:&!Q$AadGaK1,, 'r   c                    > TR                  U 5      n [        U R                  S   5       H,  nU SS2U4==   U SS2U4   R                  5       T-  -  ss'   M.     gr   )r!   r$   r#   ro   )r*   r+   r   r)   s     r   r   r      sL    

1A1771:&!Q$1QT7;;=1,, 'r   tracemin_pcgc                    > TU -  $ r   rI   )r:   Ls    r   <lambda>#_tracemin_fiedler.<locals>.<lambda>   s	    a!er   c                    > TU -  $ r   rI   )r:   Ds    r   r   r      s	    q1ur   tracemin_luT)r   r5   zUnknown linear system solver: )axisr   r   )overwrite_a)!r    r0   r#   sqrtdiagonalrU   	csr_arrayspdiagsr1   normastyper   r   	csc_arrayindptrargmaxinfrK   rt   NetworkXErrorrk   ro   flattenmaxr"   qrTeighr2   r3   r,   invr!   )r   r*   
normalizedr(   methodr9   r   solverr   r   LnormWr{   sigmaYresr   rd   r   r)   s   `               @@@@r   _tracemin_fiedlerr      s   D 	
A GGAJJL!II		 1 1!a%Aq 1 OPEAI	S299>>!Q'''	-	- JJL&O_=	=	 IIT:
 XXab\AHHSbM)113&&Q$1!?xHII FJJAJ&&(,,.EAJ


177#
&A
IILLOAa%!Q$CC!G99>>!>6Eiinn""1Aw;qAadG1C#CDuL9 ,,q&!Q$YY]]1337#acc),,
% ( "**Q-r   c                    ^ ^ SSK mT S:X  a  Sm T S;   a	  U U4S jnU$ T S:X  d  T S:X  a	  U U4S	 jnU$ [        R                  " S
T < S35      e)z>Returns a function that solves the Fiedler eigenvalue problem.r   Ntraceminr   )r   r   c                    > TS:X  a  SO[        SU R                  S   S-
  5      nT	R                  UR                  XPR                  S   4S95      R                  n[        XX#T5      u  pvUS   US S 2S4   4$ )Nr   r      r   )size)minr#   r!   normalr   r   )
r   r:   r   r(   seedqr*   r   r   r)   s
           r   find_fiedler'_get_fiedler_func.<locals>.find_fiedler  st    ~-3q!''!*q.3IA

4;;Q
O;<=??A(zGHE8Qq!tW$$r   lanczoslobpcgc           
        > SS K nUR                  R                  U [        S9n U R                  S   nU(       a]  UR                  R                  UR                  R                  STR                  U R                  5       5      -  S/XfSS95      nXp-  U-  n TS:X  d  US:  a7  UR                  R                  R                  U SS	US
S9u  pUS   U	S S 2S4   4$ TR                  TR                  U5      R                  5      n	UR                  R                  UR                  R                  SU R                  5       -  SXf5      5      n
TR                  U5      nU(       a  UWR                  5       -  nUR                  R                  R                  X	U
TR                  U5      R                  X6SS9u  pUS   U	S S 2S4   4$ )Nr   r~   r^   cscr   r   
   r   SMT)whichr(   return_eigenvectorsr   F)r   r   r(   maxiterlargest)r0   rU   r   r   r#   r   r   r   r1   eigshr!   
atleast_2dr   r   onesr   )r   r:   r   r(   r   r9   r   r   r   r*   r   r   r   r)   s               r   r   r     s   		##AU#3A
AII''II%%bggajjl33aS!u & 
 EAI"a"f 99++11q#4 2  Qx1a4((JJr}}Q/112II''		(9(9#

:LaQR(VWGGAJ%A99++22Aq!1!3!3QV 3  Qx1a4((r   zunknown method .)r    rt   r   )r   r   r)   s   ` @r   _get_fiedler_funcr     sf    00	%X M 
9	( 2	)H  
!<==r   directed   re   )
edge_attrsc                    [        U 5      S:  a  [        R                  " S5      e[        X5      n [        R                  " U 5      (       d  g[        R
                  " U 5      nUR                  S   S:X  a  U(       d  S[        US   5      -  $ S$ [        U5      nUS:w  a  SO
[        X 5      nU" XhX#U5      u  p[        U	5      $ )	a   Returns the algebraic connectivity of an undirected graph.

The algebraic connectivity of a connected undirected graph is the second
smallest eigenvalue of its Laplacian matrix.

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

weight : object, optional (default: None)
    The data key used to determine the weight of each edge. If None, then
    each edge has unit weight.

normalized : bool, optional (default: False)
    Whether the normalized Laplacian matrix is used.

tol : float, optional (default: 1e-8)
    Tolerance of relative residual in eigenvalue computation.

method : string, optional (default: 'tracemin_pcg')
    Method of eigenvalue computation. It must be one of the tracemin
    options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
    or 'lobpcg' (LOBPCG).

    The TraceMIN algorithm uses a linear system solver. The following
    values allow specifying the solver to be used.

    =============== ========================================
    Value           Solver
    =============== ========================================
    'tracemin_pcg'  Preconditioned conjugate gradient method
    'tracemin_lu'   LU factorization
    =============== ========================================

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

Returns
-------
algebraic_connectivity : float
    Algebraic connectivity.

Raises
------
NetworkXNotImplemented
    If G is directed.

NetworkXError
    If G has less than two nodes.

Notes
-----
Edge weights are interpreted by their absolute values. For MultiGraph's,
weights of parallel edges are summed. Zero-weighted edges are ignored.

See Also
--------
laplacian_matrix

Examples
--------
For undirected graphs algebraic connectivity can tell us if a graph is connected or not
`G` is connected iff  ``algebraic_connectivity(G) > 0``:

>>> G = nx.complete_graph(5)
>>> nx.algebraic_connectivity(G) > 0
True
>>> G.add_node(10)  # G is no longer connected
>>> nx.algebraic_connectivity(G) > 0
False

r   graph has less than two nodes.rO   r   r   )r   r   r   N)
r   rt   r   r|   is_connectedlaplacian_matrixr#   r   r   r   )rq   re   r   r(   r   r   r   r   r:   r   fiedlers              r   r   r   :  s    ` 1vz?@@!$A??1
AAwwqzQ+5sU1T7^#>3>$V,L("a(;A!!
>NE<r   c                    SSK n[        U 5      S:  a  [        R                  " S5      e[	        X5      n [        R
                  " U 5      (       d  [        R                  " S5      e[        U 5      S:X  a  UR                  SS/5      $ [        U5      n[        R                  " U 5      nUS:w  a  SO
[        X 5      n	U" XX#U5      u  pU$ )	a  Returns the Fiedler vector of a connected undirected graph.

The Fiedler vector of a connected undirected graph is the eigenvector
corresponding to the second smallest eigenvalue of the Laplacian matrix
of the graph.

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

weight : object, optional (default: None)
    The data key used to determine the weight of each edge. If None, then
    each edge has unit weight.

normalized : bool, optional (default: False)
    Whether the normalized Laplacian matrix is used.

tol : float, optional (default: 1e-8)
    Tolerance of relative residual in eigenvalue computation.

method : string, optional (default: 'tracemin_pcg')
    Method of eigenvalue computation. It must be one of the tracemin
    options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
    or 'lobpcg' (LOBPCG).

    The TraceMIN algorithm uses a linear system solver. The following
    values allow specifying the solver to be used.

    =============== ========================================
    Value           Solver
    =============== ========================================
    'tracemin_pcg'  Preconditioned conjugate gradient method
    'tracemin_lu'   LU factorization
    =============== ========================================

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

Returns
-------
fiedler_vector : NumPy array of floats.
    Fiedler vector.

Raises
------
NetworkXNotImplemented
    If G is directed.

NetworkXError
    If G has less than two nodes or is not connected.

Notes
-----
Edge weights are interpreted by their absolute values. For MultiGraph's,
weights of parallel edges are summed. Zero-weighted edges are ignored.

See Also
--------
laplacian_matrix

Examples
--------
Given a connected graph the signs of the values in the Fiedler vector can be
used to partition the graph into two components.

>>> G = nx.barbell_graph(5, 0)
>>> nx.fiedler_vector(G, normalized=True, seed=1)
array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899,
        0.26072899,  0.32864129,  0.32864129,  0.32864129,  0.32864129])

The connected components are the two 5-node cliques of the barbell graph.
r   Nr   r   zgraph is not connected.r^   g      r   )
r    r   rt   r   r|   r   arrayr   r   r   )rq   re   r   r(   r   r   r)   r   r   r:   r   r   s               r   r   r     s    ` 
1vz?@@!$A??1899
1v{xxd$$$V,L
AA("a(;A!!
>NENr   c                    [        U 5      S:X  a  [        R                  " S5      e[        X5      n [	        U5      n/ n[        R
                  " U 5       H  n[        U5      n	U	S:  an  [        R                  " X5      n
US:w  a  SO
[        X5      nU" XX#U5      u  p[        U[        U	5      U5      nUR                  S [        U5       5       5        M  UR                  U5        M     U$ )a  Compute the spectral_ordering of a graph.

The spectral ordering of a graph is an ordering of its nodes where nodes
in the same weakly connected components appear contiguous and ordered by
their corresponding elements in the Fiedler vector of the component.

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

weight : object, optional (default: None)
    The data key used to determine the weight of each edge. If None, then
    each edge has unit weight.

normalized : bool, optional (default: False)
    Whether the normalized Laplacian matrix is used.

tol : float, optional (default: 1e-8)
    Tolerance of relative residual in eigenvalue computation.

method : string, optional (default: 'tracemin_pcg')
    Method of eigenvalue computation. It must be one of the tracemin
    options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
    or 'lobpcg' (LOBPCG).

    The TraceMIN algorithm uses a linear system solver. The following
    values allow specifying the solver to be used.

    =============== ========================================
    Value           Solver
    =============== ========================================
    'tracemin_pcg'  Preconditioned conjugate gradient method
    'tracemin_lu'   LU factorization
    =============== ========================================

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

Returns
-------
spectral_ordering : NumPy array of floats.
    Spectral ordering of nodes.

Raises
------
NetworkXError
    If G is empty.

Notes
-----
Edge weights are interpreted by their absolute values. For MultiGraph's,
weights of parallel edges are summed. Zero-weighted edges are ignored.

See Also
--------
laplacian_matrix
r   zgraph is empty.r   r   Nc              3   *   #    U  H	  u  po3v   M     g 7fr   rI   )ra   r:   crb   s       r   rf   $spectral_ordering.<locals>.<genexpr>I  s     <*;wqQ*;s   )r   rt   r   r|   r   connected_componentsr   r   r   r$   extendsorted)rq   re   r   r(   r   r   r   r   	componentr   r   r:   r   r   	sort_infos                  r   r	   r	     s    @ 1v{011!$A$V,LE,,Q/	9~!8##A1A(*a0KA)!
FNEGU4[)<ILL<&*;<<LL# 0 Lr   c                     SSK n[        R                  " XX#XE5      nUR                  [	        U 5      5      nUS:  n	[        X)    R                  5       5      [        X   R                  5       5      4$ )a  Bisect the graph using the Fiedler vector.

This method uses the Fiedler vector to bisect a graph.
The partition is defined by the nodes which are associated with
either positive or negative values in the vector.

Parameters
----------
G : NetworkX Graph

weight : str, optional (default: weight)
    The data key used to determine the weight of each edge. If None, then
    each edge has unit weight.

normalized : bool, optional (default: False)
    Whether the normalized Laplacian matrix is used.

tol : float, optional (default: 1e-8)
    Tolerance of relative residual in eigenvalue computation.

method : string, optional (default: 'tracemin_pcg')
    Method of eigenvalue computation. It must be one of the tracemin
    options shown below (TraceMIN), 'lanczos' (Lanczos iteration)
    or 'lobpcg' (LOBPCG).

    The TraceMIN algorithm uses a linear system solver. The following
    values allow specifying the solver to be used.

    =============== ========================================
    Value           Solver
    =============== ========================================
    'tracemin_pcg'  Preconditioned conjugate gradient method
    'tracemin_lu'   LU factorization
    =============== ========================================

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

Returns
-------
bisection : tuple of sets
    Sets with the bisection of nodes

Examples
--------
>>> G = nx.barbell_graph(3, 0)
>>> nx.spectral_bisection(G)
({0, 1, 2}, {3, 4, 5})

References
----------
.. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370
   Oxford University Press 2011.
r   N)r    rt   r   r   listsettolist)
rq   re   r   r(   r   r   r)   rc   nodespos_valss
             r   r
   r
   P  se    v 
!ZfCAHHT!WEAvHuY&&()3u/E/E/G+HHHr   )re   Fg:0yE>r   N)rG   	functoolsr   networkxrt   networkx.utilsr   r   r   __all__r   rK   r|   r   r   r   _dispatchabler   r   r	   r
   rI   r   r   <module>r      s%     63 63r >4i X4n Z X&PTZ '  !Zz Z X&PT\ '  !\~ X&PTO ' Od X&PT@I '@Ir   