
    wgR                        d Z ddlmZ ddlZddlmZmZmZ g dZ	 G d d      Z
 G d d	      Zd
 Zd Zd Zd Z ed       ed       ej                   d      	 dd                     Z ed       ed       ej                   d      	 dd                     Z ed       ej                   d      	 dd              Z ej                   d      	 dd       Zy)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                   "    e Zd ZdZd Zd Zd Zy)
_PCGSolvera  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                      || _         || _        y N)_A_M)selfAMs      j/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/linalg/algebraicconnectivity.py__init__z_PCGSolver.__init__&   s        c                     dd l }|j                  |      }|j                  |j                  d      }t	        |j                  d         D ]"  }| j                  |d d |f   |      |d d |f<   $ |S Nr   Forder   )numpyasarrayndarrayshaperange_solver   BtolnpXjs         r   solvez_PCGSolver.solve*   sk     JJqMJJqwwcJ*qwwqz" 	0Akk!AqD'3/AadG	0r   c                 |   dd l }dd l}| j                  }| j                  }||j                  j
                  j                  |      z  }|j                  |j                        }|j                         } ||      }	|j                  j
                  j                  ||	      }
|	j                         }	  ||      }|
|j                  j
                  j                  ||      z  }|j                  j
                  j                  |||      }|j                  j
                  j                  |||       }|j                  j
                  j                  |      |k  r|S  ||      }	|j                  j
                  j                  ||	      }||
z  |}
}|j                  j
                  j                  ||	|      })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"   z_PCGSolver._solve4   sa   GGGGryy~~##A&&HHQWWFFHaDYY^^  A&FFH1B,,Q33E		$$QU$3A		$$Ruf$5Ayy~~##A&,!A99>>&&q!,Dby$"D		$$QT$2A r   N)__name__
__module____qualname____doc__r   r)   r"    r   r   r   r      s    3r   r   c                       e Zd ZdZd ZddZy)	_LUSolverzLU 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                 n    dd l }|j                  j                  j                  |ddddd      | _        y )Nr   MMD_AT_PLUS_A        T)EquilSymmetricMode)
permc_specdiag_pivot_threshoptions)r,   sparser-   splu_LU)r   r   r5   s      r   r   z_LUSolver.__init__Z   s7    99##((&!"T:	 ) 
r   Nc                     dd l }|j                  |      }|j                  |j                  d      }t	        |j                  d         D ]+  }| j
                  j                  |d d |f         |d d |f<   - |S r   )r   r   r   r    r!   rO   r)   r#   s         r   r)   z_LUSolver.solved   sk    JJqMJJqwwcJ*qwwqz" 	.AhhnnQq!tW-AadG	.r   r   )r>   r?   r@   rA   r   r)   rB   r   r   rD   rD   O   s    
r   rD   c                      j                         rSt        j                         }|j                          |j	                  fd j                  d      D               |  j                         sfd j                  d      D        }n fd j                         D        }t        j                         }|j                          |j	                  d |D               |S )z5Compute edge weights and eliminate zero-weight edges.c              3   \   K   | ]#  \  }}}||k7  s|||j                  d       f % yw      ?N)get.0uveweights       r   	<genexpr>z$_preprocess_graph.<locals>.<genexpr>t   s0     TGAq!QRSVaAEE&#&'Ts   ,,T)data)r[   c           	   3   n   K   | ],  \  }}}||k7  s||t        |j                  d             f . ywrS   absrU   rV   s       r   r\   z$_preprocess_graph.<locals>.<genexpr>y   s<      
071aQRVWQWQ3quuVS)*+
s   5#5c              3      K   | ]7  \  }}||k7  r-||t        fd |   |   j                         D              f 9 yw)c              3   T   K   | ]  }t        |j                  d              ! ywrS   r_   )rW   rZ   r[   s     r   r\   z._preprocess_graph.<locals>.<genexpr>.<genexpr>~   s!     I1s155-.Is   %(N)sumvalues)rW   rX   rY   Gr[   s      r   r\   z$_preprocess_graph.<locals>.<genexpr>}   sE      
1Av 3I!Q8HIIJ
s   =A c              3   :   K   | ]  \  }}}|d k7  s|||f  yw)r   NrB   )rW   rX   rY   rZ   s       r   r\   z$_preprocess_graph.<locals>.<genexpr>   s"     GGAq!Qq!QiGs   
)is_directednx
MultiGraphadd_nodes_fromadd_weighted_edges_fromedgesis_multigraphGraph)re   r[   Hrl   s   ``  r   _preprocess_graphrp   n   s    }}MMO		!!TqwwDw7IT 	" 	
 ??
;<777;M

	

 	
AQGuGGHr   c                    ddl }| j                  |      } t        |       }t        |      }t	        t        |t        |                  }|j                  |t              }t        |      D ]  \  }}||||   <    ||dz
  dz  z  }|S )zEEstimate the Fiedler vector using the reverse Cuthill-McKee ordering.r   Ndtyper          @)
r   subgraphr   lendictzipr!   r   float	enumerate)	re   nodelistr&   r   nindexr6   irX   s	            r   _rcm_estimater      s    	

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


1E
"A%  1%(!a%3AHr   c           	          ddl ddl}|j                  d   |rj                   j	                               |j
                  j                  |j
                  j                  dz  dd             z  z   dj                  j                  d      z  z  |rfd}nfd	}|d
k(  r6 j	                         j                  t              t         fdfd      }n|dk(  rl|j
                  j                   t        d      }|j                  dd |j                  dd z
  j                         }	j                   ||	|	f<   t#        |      }nt%        j&                  d|       t)               j+                  d      j-                         j/                         }
 ||       j1                  |j                  d      }	 j                  j3                  |      d   } |z  |ddddf<   |j4                  |z  }|j                  j7                  |d      \  }}||z  }|j                  j8                  j;                  ||dddf   z  |d   |dddf   z  z
        |
z  }||k  rnd|j=                  ||      |ddddf<   |j                  j?                  |j4                  |z        |j4                  z  j4                  } ||       |jA                  |      fS )a  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formatrT      c                     j                  |       } t        | j                  d         D ]   }| dd|fxx   | dd|f   z  z  z  cc<   " yz(Make X orthogonal to the nullspace of L.r   N)r   r!   r    )r'   r(   rZ   r&   s     r   projectz"_tracemin_fiedler.<locals>.project   sO    

1A1771:& -!Q$AadGaK1,,-r   c                     j                  |       } t        | j                  d         D ]+  }| dd|fxx   | dd|f   j                         z  z  cc<   - yr   )r   r!   r    rc   )r'   r(   r|   r&   s     r   r   z"_tracemin_fiedler.<locals>.project   sQ    

1A1771:& -!Q$1QT7;;=1,,-r   tracemin_pcgc                     | z  S r   rB   )r6   Ls    r   <lambda>z#_tracemin_fiedler.<locals>.<lambda>   s    a!e r   c                     | z  S r   rB   )r6   Ds    r   r   z#_tracemin_fiedler.<locals>.<lambda>   s    q1u r   tracemin_luT)rs   r1   zUnknown linear system solver: )axisr   r   )overwrite_a)!r   r,   r    sqrtdiagonalrM   	csr_arrayspdiagsr-   normastypery   r   	csc_arrayindptrargmaxinfrD   rh   NetworkXErrorr`   rc   flattenmaxr   qrTeighr.   r/   r)   invr   )r   r'   
normalizedr%   methodr5   r   solverr   r~   LnormWro   sigmaYresr   rZ   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qEiinn""1qAw;qAadG1C#CDuL9 ,,q#&!Q$YY]]1337#acc),,
% ( "**Q-r   c                      ddl  dk(  rd  dv r fd}|S  dk(  s dk(  r fd	}|S t        j                  d
 d      )z>Returns a function that solves the Fiedler eigenvalue problem.r   Ntraceminr   )r   r   c                     dk(  rdnt        d| j                  d   dz
        }	j                  |j                  || j                  d   f            j                  }t        | |||      \  }}|d   |d d df   fS )Nr   r      r   )size)minr    r   normalr   r   )
r   r6   r   r%   seedqr'   r   r   r&   s
           r   find_fiedlerz'_get_fiedler_func.<locals>.find_fiedler  s|    ~-3q!''!*q.3IA

4;;Q
O;<=??A(Az3GHE18Qq!tW$$r   lanczoslobpcgc           	         dd l }|j                  j                  | t              } | j                  d   }|rb|j                  j                  |j                  j                  dj                  | j                               z  dg||d            }|| z  |z  } dk(  s|dk  r;|j                  j                  j                  | dd	|d
      \  }}	|d   |	d d df   fS j                  j                  |      j                        }	|j                  j                  |j                  j                  d| j                         z  d||            }
j                  |      }|r|j                         z  }|j                  j                  j                  | |	|
j                  |      j                  ||d      \  }}	|d   |	d d df   fS )Nr   rr   rT   cscr   r   
   r   SMT)whichr%   return_eigenvectorsr   F)r   r   r%   maxiterlargest)r,   rM   r   ry   r    r   r   r   r-   eigshr   
atleast_2dr   r   onesr   )r   r6   r   r%   r   r5   r|   r   r   r'   r   r   r   r&   s               r   r   z'_get_fiedler_func.<locals>.find_fiedler  s   		##AU#3A
AII''II%%bggajjl33aS!Qu & 
 EAI"a"f 99++11q#4 2 q Qx1a4((JJr}}Q/112II''		(9(9#

:LaQRTU(VWGGAJ%A99++22qAq!1!3!3aQV 3 q Qx1a4((r   zunknown method .)r   rh   r   )r   r   r&   s   ` @r   _get_fiedler_funcr     sf    00	%X M 
9	( 2	)H  
!<==r   directed   r[   )
edge_attrsc                 t   t        |       dk  rt        j                  d      t        | |      } t        j                  |       syt        j
                  |       }|j                  d   dk(  r|sdt        |d         z  S dS t        |      }|dk7  rdnt        | |       } ||||||      \  }	}
t        |	      S )	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.rG   r   rt   )r   r   r   N)
rv   rh   r   rp   is_connectedlaplacian_matrixr    ry   r   r   )re   r[   r   r%   r   r   r   r   r6   r   fiedlers              r   r   r   :  s    ` 1vz?@@!V$A??1
AAwwqzQ+5sU1T7^#>3>$V,L("a(;A!!Q
C>NE7<r   c                    ddl }t        |       dk  rt        j                  d      t	        | |      } t        j
                  |       st        j                  d      t        |       dk(  r|j                  ddg      S t        |      }t        j                  |       }|dk7  rdnt        | |       }	 |||	|||      \  }
}|S )	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.rT   g      r   )
r   rv   rh   r   rp   r   arrayr   r   r   )re   r[   r   r%   r   r   r&   r   r   r6   r   r   s               r   r   r     s    ` 
1vz?@@!V$A??1899
1v{xxd$$$V,L
AA("a(;A!!Q
C>NE7Nr   c                    t        |       dk(  rt        j                  d      t        | |      } t	        |      }g }t        j
                  |       D ]  }t        |      }	|	dkD  rpt        j                  | |      }
|dk7  rdnt        | |      } ||
||||      \  }}t        |t        |	      |      }|j                  d t        |      D               |j                  |        |S )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   (   K   | ]
  \  }}}|  y wr   rB   )rW   r6   crX   s       r   r\   z$spectral_ordering.<locals>.<genexpr>I  s     <wq!Q<s   )rv   rh   r   rp   r   connected_componentsr   r   rx   r!   extendsorted)re   r[   r   r%   r   r   r   r   	componentr   r   r6   r   r   	sort_infos                  r   r	   r	     s    @ 1v{011!V$A$V,LE,,Q/ 	$	9~!8##Ay1A(*a0KA)!Q
CFNE7GU4[)<ILL<&*;<<LL#	$ Lr   c                     ddl }t        j                  | |||||      }|j                  t	        |             }|dk\  }	t        ||	    j                               t        ||	   j                               fS )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   rh   r   r   listsettolist)
re   r[   r   r%   r   r   r&   rY   nodespos_valss
             r   r
   r
   P  so    v 
!VZfdCAHHT!WEAvHuhY&&()3uX/E/E/G+HHHr   )r[   Fg:0yE>r   N)rA   	functoolsr   networkxrh   networkx.utilsr   r   r   __all__r   rD   rp   r   r   r   _dispatchabler   r   r	   r
   rB   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   