
    -it                        S r SSKrSSKJrJr  SSKrSSKJr  SSK	J
r
  SSKJr  SSKJrJr  SS	KJrJr  SS
KJr  SSKJrJr  SSKJrJrJr  SSKJr  SSKJrJ r J!r!  SSK"J#r#  SSK$J%r&  SSK$J'r'J(r(  SSK)J*r*  S r+S r,S r-\!" SS/\" \SSSS9/\ " 1 Sk5      S/S/\" \SSSS9\ " S15      /S/S/S.S S!9S"SSSS S S#.S$ j5       r.S"SSSS S S#.S% jr/ " S& S'\5      r0g)(zSpectral Embedding.    N)IntegralReal)sparse)eigh)connected_components)eigshlobpcg   )BaseEstimator_fit_context)
rbf_kernel)NearestNeighborskneighbors_graph)check_arraycheck_random_statecheck_symmetric)_init_arpack_v0)Interval
StrOptionsvalidate_params)_deterministic_vector_sign_flip)	laplacian)parse_version
sp_version)validate_datac                    U R                   S   n[        R                  " U 5      (       a  U R                  5       n [        R
                  " U[        S9n[        R
                  " U[        S9nSXA'   [        U5       H  nUR                  5       n[        R                  " X4US9  XcR                  5       :  a    U$ [        R                  " U5      S   nUR                  S5        U H]  n[        R                  " U 5      (       a&  X/SS24   R                  5       R                  5       n	OX   n	[        R                  " XIUS9  M_     M     U$ )a  Find the largest graph connected components that contains one
given node.

Parameters
----------
graph : array-like of shape (n_samples, n_samples)
    Adjacency matrix of the graph, non-zero weight means an edge
    between the nodes.

node_id : int
    The index of the query node of the graph.

Returns
-------
connected_components_matrix : array-like of shape (n_samples,)
    An array of bool value indicating the indexes of the nodes
    belonging to the largest connected components of the given query
    node.
r   )dtypeT)outFN)shaper   issparsetocsrnpzerosboolrangesum
logical_orwherefilltoarrayravel)
graphnode_idn_nodeconnected_nodesnodes_to_explore_last_num_componentindicesi	neighborss
             W/var/www/html/venv/lib/python3.13/site-packages/sklearn/manifold/_spectral_embedding.py_graph_connected_componentr7      s   ( [[^FuhhvT2Oxxd3 $6],002
o_M!4!4!66  ((+,Q/e$Au%% "#q&M11399;	!H	MM*;KL       c                     [         R                  " U 5      (       a/  [        [        S5      :  n[	        U SUS9n [        U 5      u  p#US:H  $ [        U S5      R                  5       U R                  S   :H  $ )aV  Return whether the graph is connected (True) or Not (False).

Parameters
----------
graph : {array-like, sparse matrix} of shape (n_samples, n_samples)
    Adjacency matrix of the graph, non-zero weight means an edge
    between the nodes.

Returns
-------
is_connected : bool
    True means the graph is fully connected and False means not.
z1.11.3Taccept_sparseaccept_large_sparse   r   )	r   r    r   r   r   r   r7   r&   r   )r,   r<   n_connected_componentsr1   s       r6   _graph_is_connectedr?   L   sw     u )M(,CC;N
 %9$?!%** *%3779U[[^KKr8   c                    U R                   S   n[        R                  " U 5      (       d  U(       a  XR                  SSUS-   2'   U $ U R	                  5       n U(       a'  U R
                  U R                  :H  nXR                  U'   [        R                  " U R
                  U R                  -
  5      R                  nUS::  a  U R                  5       n U $ U R                  5       n U $ )a  Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition.

Parameters
----------
laplacian : {ndarray, sparse matrix}
    The graph laplacian.

value : float
    The value of the diagonal.

norm_laplacian : bool
    Whether the value of the diagonal should be changed or not.

Returns
-------
laplacian : {array, sparse matrix}
    An array of matrix in a form that is well suited to fast
    eigenvalue decomposition, depending on the band width of the
    matrix.
r   Nr=      )r   r   r    flattocoorowcoldatar"   uniquesizetodiar!   )r   valuenorm_laplaciann_nodesdiag_idxn_diagss         r6   	_set_diagrO   l   s    , ooa G??9%%-2NN>gk>*"  OO%	 }}	5H',NN8$ ))IMMIMM9:??a<!)I
  ")Ir8   z
array-likezsparse matrixr=   leftclosed>   amgarpackr	   random_stateautoboolean	adjacencyn_componentseigen_solverrU   	eigen_tolrK   
drop_firstTprefer_skip_nested_validation   rZ   r[   rU   r\   rK   r]   c          
      6    [        U5      n[        U UUUUUUS9$ )aS  Project the sample on the first eigenvectors of the graph Laplacian.

The adjacency matrix is used to compute a normalized graph Laplacian
whose spectrum (especially the eigenvectors associated to the
smallest eigenvalues) has an interpretation in terms of minimal
number of cuts necessary to split the graph into comparably sized
components.

This embedding can also 'work' even if the ``adjacency`` variable is
not strictly the adjacency matrix of a graph but more generally
an affinity or similarity matrix between samples (for instance the
heat kernel of a euclidean distance matrix or a k-NN matrix).

However care must taken to always make the affinity matrix symmetric
so that the eigenvector decomposition works as expected.

Note : Laplacian Eigenmaps is the actual algorithm implemented here.

Read more in the :ref:`User Guide <spectral_embedding>`.

Parameters
----------
adjacency : {array-like, sparse graph} of shape (n_samples, n_samples)
    The adjacency matrix of the graph to embed.

n_components : int, default=8
    The dimension of the projection subspace.

eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None
    The eigenvalue decomposition strategy to use. AMG requires pyamg
    to be installed. It can be faster on very large, sparse problems,
    but may also lead to instabilities. If None, then ``'arpack'`` is
    used.

random_state : int, RandomState instance or None, default=None
    A pseudo random number generator used for the initialization
    of the lobpcg eigen vectors decomposition when `eigen_solver ==
    'amg'`, and for the K-Means initialization. Use an int to make
    the results deterministic across calls (See
    :term:`Glossary <random_state>`).

    .. note::
        When using `eigen_solver == 'amg'`,
        it is necessary to also fix the global numpy seed with
        `np.random.seed(int)` to get deterministic results. See
        https://github.com/pyamg/pyamg/issues/139 for further
        information.

eigen_tol : float, default="auto"
    Stopping criterion for eigendecomposition of the Laplacian matrix.
    If `eigen_tol="auto"` then the passed tolerance will depend on the
    `eigen_solver`:

    - If `eigen_solver="arpack"`, then `eigen_tol=0.0`;
    - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then
      `eigen_tol=None` which configures the underlying `lobpcg` solver to
      automatically resolve the value according to their heuristics. See,
      :func:`scipy.sparse.linalg.lobpcg` for details.

    Note that when using `eigen_solver="amg"` values of `tol<1e-5` may lead
    to convergence issues and should be avoided.

    .. versionadded:: 1.2
       Added 'auto' option.

norm_laplacian : bool, default=True
    If True, then compute symmetric normalized Laplacian.

drop_first : bool, default=True
    Whether to drop the first eigenvector. For spectral embedding, this
    should be True as the first eigenvector should be constant vector for
    connected graph, but for spectral clustering, this should be kept as
    False to retain the first eigenvector.

Returns
-------
embedding : ndarray of shape (n_samples, n_components)
    The reduced samples.

Notes
-----
Spectral Embedding (Laplacian Eigenmaps) is most useful when the graph
has one connected component. If there graph has many components, the first
few eigenvectors will simply uncover the connected components of the graph.

References
----------
* https://en.wikipedia.org/wiki/LOBPCG

* :doi:`"Toward the Optimal Preconditioned Eigensolver: Locally Optimal
  Block Preconditioned Conjugate Gradient Method",
  Andrew V. Knyazev
  <10.1137/S1064827500366124>`

Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.neighbors import kneighbors_graph
>>> from sklearn.manifold import spectral_embedding
>>> X, _ = load_digits(return_X_y=True)
>>> X = X[:100]
>>> affinity_matrix = kneighbors_graph(
...     X, n_neighbors=int(X.shape[0] / 10), include_self=True
... )
>>> # make the matrix symmetric
>>> affinity_matrix = 0.5 * (affinity_matrix + affinity_matrix.T)
>>> embedding = spectral_embedding(affinity_matrix, n_components=2, random_state=42)
>>> embedding.shape
(100, 2)
ra   )r   _spectral_embeddingrX   s          r6   spectral_embeddingrd      s1    H &l3L!!!% r8   c          	         [        U 5      n US:X  a   SSKJn  Uc  SnU R
                  S   n	U(       a  US-   n[        U 5      (       d  [        R                  " S5        [        XSS	9u  pUS:X  d*  US
:w  a  [        R                  " U
5      (       a	  U	SU-  :  ao  [        U
SU5      n
 US:X  a  SOUnU
S-  n
[        U
R
                  S   U5      n[        U
SSS9n
[        XSSXS9u  pUR                   US S2   nU(       a  UU-  nGOUS:X  Ga  [        R                  " U
5      (       d  [        R                  " S5        [        U
[$        R&                  [$        R(                  /SS9n
[        U
SU5      n
S[        R*                  " U
R
                  S   5      -  nU
U-  n
[-        [        S5      (       a5  [/        U
[        R0                  5      (       a  [        R2                  " U
5      n
W" [        U
SS95      nU
U-  n
UR5                  5       nUR7                  U
R
                  S   US-   4S9nUR9                  5       US S 2S4'   UR;                  U
R<                  5      nUS:X  a  S OUn[?        U
UUUSS9u  pUR                   nU(       a  UU-  nUR
                  S   S:X  a  [        eUS
:X  Ga5  [        U
[$        R&                  [$        R(                  /SS9n
U	SU-  S-   :  aS  [        R                  " U
5      (       a  U
RA                  5       n
[C        U
SS9u  pUR                   S U nU(       a  UU-  nO[        U
SU5      n
UR7                  U
R
                  S   US-   4S9nUR9                  5       US S 2S4'   UR;                  U
R<                  5      nUS:X  a  S OUn[?        U
UUSSS9u  pUR                   S U nU(       a  UU-  nUR
                  S   S:X  a  [        e[E        W5      nU(       a  USU R                   $ US U R                   $ ! [         a  n[	        S5      UeS nAff = f! ["         a    S
nU
S-  n
 GNf = f)NrS   r   )smoothed_aggregation_solverz>The eigen_solver was set to 'amg', but pyamg is not available.rT   r=   zJGraph is not fully connected, spectral embedding may not work as expected.T)normedreturn_diagr	      rV   csrFr:         ?LM)ksigmawhichtolv0z$AMG works better for sparse matrices)r   r;   gh㈵>	csr_array)r;   )rH   )Mrq   largest)check_finitei  )rq   ru   maxiter)#r   pyamgrf   ImportError
ValueErrorr   r?   warningswarncsgraph_laplacianr   r    rO   r   r   r   TRuntimeErrorr"   float64float32eyehasattr
isinstancers   
csr_matrixaspreconditionerstandard_normalr+   astyper   r	   r*   r   r   )rY   rZ   r[   rU   r\   rK   r]   rf   erL   r   ddrq   rr   r1   diffusion_map	embedding
diag_shiftmlrt   Xs                        r6   rc   rc   +  s`     	*Iu	9 ooa G#a'y))X	
 &dMI x ++w\9I/I iN;	 	 !F*!	COI !3\BB#EI  %Dc A &(8b(89I%N	 
	 y))MM@Abjj"**5T
	 iN;	 FJJyq'9::
Z	6;''Jy&BRBR,S,S )))4I(Ye)TUZ	!((yq/A<RSCS.T(U((*!Q$HHY__%6)dy!)Q!eL!OO	!BI??1"xbjj"**5T
	 Q%)) y))%--/	#IEBA%6I%N	!)Q?I ,,ooa(,*:; - A hhjAadG)A#v-$9C%1#ud A &6I%N	q!Q&  /	:I<(***,')))s  	P	~  	 $LOI	s*   P )AP9 
P6%P11P69QQc                      ^  \ rS rSr% Sr\" \SSSS9/\" 1 Sk5      \/\" \	SSSS9S/S	/\" 1 S
k5      S/\" \	SSSS9\" S15      /\" \SSSS9S/S\/S.r
\\S'    SSSSSSSSS.S jjrU 4S jrSS jr\" SS9SS j5       rSS jrSrU =r$ )SpectralEmbeddingi  a$  Spectral embedding for non-linear dimensionality reduction.

Forms an affinity matrix given by the specified function and
applies spectral decomposition to the corresponding graph laplacian.
The resulting transformation is given by the value of the
eigenvectors for each data point.

Note : Laplacian Eigenmaps is the actual algorithm implemented here.

Read more in the :ref:`User Guide <spectral_embedding>`.

Parameters
----------
n_components : int, default=2
    The dimension of the projected subspace.

affinity : {'nearest_neighbors', 'rbf', 'precomputed',                 'precomputed_nearest_neighbors'} or callable,                 default='nearest_neighbors'
    How to construct the affinity matrix.
     - 'nearest_neighbors' : construct the affinity matrix by computing a
       graph of nearest neighbors.
     - 'rbf' : construct the affinity matrix by computing a radial basis
       function (RBF) kernel.
     - 'precomputed' : interpret ``X`` as a precomputed affinity matrix.
     - 'precomputed_nearest_neighbors' : interpret ``X`` as a sparse graph
       of precomputed nearest neighbors, and constructs the affinity matrix
       by selecting the ``n_neighbors`` nearest neighbors.
     - callable : use passed in function as affinity
       the function takes in data matrix (n_samples, n_features)
       and return affinity matrix (n_samples, n_samples).

gamma : float, default=None
    Kernel coefficient for rbf kernel. If None, gamma will be set to
    1/n_features.

random_state : int, RandomState instance or None, default=None
    A pseudo random number generator used for the initialization
    of the lobpcg eigen vectors decomposition when `eigen_solver ==
    'amg'`, and for the K-Means initialization. Use an int to make
    the results deterministic across calls (See
    :term:`Glossary <random_state>`).

    .. note::
        When using `eigen_solver == 'amg'`,
        it is necessary to also fix the global numpy seed with
        `np.random.seed(int)` to get deterministic results. See
        https://github.com/pyamg/pyamg/issues/139 for further
        information.

eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None
    The eigenvalue decomposition strategy to use. AMG requires pyamg
    to be installed. It can be faster on very large, sparse problems.
    If None, then ``'arpack'`` is used.

eigen_tol : float, default="auto"
    Stopping criterion for eigendecomposition of the Laplacian matrix.
    If `eigen_tol="auto"` then the passed tolerance will depend on the
    `eigen_solver`:

    - If `eigen_solver="arpack"`, then `eigen_tol=0.0`;
    - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then
      `eigen_tol=None` which configures the underlying `lobpcg` solver to
      automatically resolve the value according to their heuristics. See,
      :func:`scipy.sparse.linalg.lobpcg` for details.

    Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"`
    values of `tol<1e-5` may lead to convergence issues and should be
    avoided.

    .. versionadded:: 1.2

n_neighbors : int, default=None
    Number of nearest neighbors for nearest_neighbors graph building.
    If None, n_neighbors will be set to max(n_samples/10, 1).

n_jobs : int, default=None
    The number of parallel jobs to run.
    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

Attributes
----------
embedding_ : ndarray of shape (n_samples, n_components)
    Spectral embedding of the training matrix.

affinity_matrix_ : ndarray of shape (n_samples, n_samples)
    Affinity_matrix constructed from samples or precomputed.

n_features_in_ : int
    Number of features seen during :term:`fit`.

    .. versionadded:: 0.24

feature_names_in_ : ndarray of shape (`n_features_in_`,)
    Names of features seen during :term:`fit`. Defined only when `X`
    has feature names that are all strings.

    .. versionadded:: 1.0

n_neighbors_ : int
    Number of nearest neighbors effectively used.

See Also
--------
Isomap : Non-linear dimensionality reduction through Isometric Mapping.

References
----------

- :doi:`A Tutorial on Spectral Clustering, 2007
  Ulrike von Luxburg
  <10.1007/s11222-007-9033-z>`

- `On Spectral Clustering: Analysis and an algorithm, 2001
  Andrew Y. Ng, Michael I. Jordan, Yair Weiss
  <https://citeseerx.ist.psu.edu/doc_view/pid/796c5d6336fc52aa84db575fb821c78918b65f58>`_

- :doi:`Normalized cuts and image segmentation, 2000
  Jianbo Shi, Jitendra Malik
  <10.1109/34.868688>`

Examples
--------
>>> from sklearn.datasets import load_digits
>>> from sklearn.manifold import SpectralEmbedding
>>> X, _ = load_digits(return_X_y=True)
>>> X.shape
(1797, 64)
>>> embedding = SpectralEmbedding(n_components=2)
>>> X_transformed = embedding.fit_transform(X[:100])
>>> X_transformed.shape
(100, 2)
r=   NrP   rQ   >   rbfprecomputednearest_neighborsprecomputed_nearest_neighborsr   rU   >   rS   rT   r	   rV   rZ   affinitygammarU   r[   r\   n_neighborsn_jobs_parameter_constraintsr   )r   r   rU   r[   r\   r   r   c                d    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        g Nr   )	selfrZ   r   r   rU   r[   r\   r   r   s	            r6   __init__SpectralEmbedding.__init__t  s0     ) 
(("&r8   c                    > [         TU ]  5       nSUR                  l        U R                  S;   UR                  l        U$ )NT)r   r   )super__sklearn_tags__
input_tagsr   r   pairwise)r   tags	__class__s     r6   r   "SpectralEmbedding.__sklearn_tags__  s=    w')!%#'== 5
 $
  r8   c                     U R                   S:X  a  Xl        U R                  $ U R                   S:X  a`  [        U R                  U R                  SS9R                  U5      nUR                  USS9nSXDR                  -   -  U l        U R                  $ U R                   S:X  a  [        R                  " U5      (       a  [        R                  " S5        S	U l         OU R                  b  U R                  O$[        [        UR                  S
   S-  5      S5      U l        [        XR                  SU R                  S9U l        SU R                  U R                  R                  -   -  U l        U R                  $ U R                   S	:X  aT  U R                   b  U R                   OSUR                  S   -  U l        [%        XR"                  S9U l        U R                  $ U R                  U5      U l        U R                  $ )a  Calculate the affinity matrix from data
Parameters
----------
X : array-like of shape (n_samples, n_features)
    Training vector, where `n_samples` is the number of samples
    and `n_features` is the number of features.

    If affinity is "precomputed"
    X : array-like of shape (n_samples, n_samples),
    Interpret X as precomputed adjacency graph computed from
    samples.

Y: Ignored

Returns
-------
affinity_matrix of shape (n_samples, n_samples)
r   r   )r   r   metricconnectivity)r   modeg      ?r   z`Nearest neighbors affinity currently does not support sparse input, falling back to rbf affinityr   r   
   r=   T)include_selfr   rl   )r   )r   affinity_matrix_r   r   r   fitr   r~   r   r    r{   r|   maxintr   n_neighbors_r   gamma_r   )r   r   Y	estimatorr   s        r6   _get_affinity_matrix&SpectralEmbedding._get_affinity_matrix  s   & ==M)$%!(((==;;( ,,T[[c!f  %555OL$'<..+H$ID!(((==//q!!#
 !& ''3 $$Sb115 !
 )9((tDKK)% ),))D,A,A,C,CC)% ,,,==E!(,

(>$**C!''RS*DTDK$.q$DD!((( $a 0$$$r8   Tr^   c                     [        XSSS9n[        U R                  5      nU R                  U5      n[	        UU R
                  U R                  U R                  US9U l        U $ )a  Fit the model from data in X.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Training vector, where `n_samples` is the number of samples
    and `n_features` is the number of features.

    If affinity is "precomputed"
    X : {array-like, sparse matrix}, shape (n_samples, n_samples),
    Interpret X as precomputed adjacency graph computed from
    samples.

y : Ignored
    Not used, present for API consistency by convention.

Returns
-------
self : object
    Returns the instance itself.
rk   r
   )r;   ensure_min_samples)rZ   r[   r\   rU   )	r   r   rU   r   rc   rZ   r[   r\   
embedding_)r   r   yrU   affinity_matrixs        r6   r   SpectralEmbedding.fit  sd    . $1M)$*;*;<33A6-****nn%
 r8   c                 <    U R                  U5        U R                  $ )ac  Fit the model from data in X and transform X.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Training vector, where `n_samples` is the number of samples
    and `n_features` is the number of features.

    If affinity is "precomputed"
    X : {array-like, sparse matrix} of shape (n_samples, n_samples),
    Interpret X as precomputed adjacency graph computed from
    samples.

y : Ignored
    Not used, present for API consistency by convention.

Returns
-------
X_new : array-like of shape (n_samples, n_components)
    Spectral embedding of the training matrix.
)r   r   )r   r   r   s      r6   fit_transformSpectralEmbedding.fit_transform  s    , 	r8   )r   r   r[   r\   r   r   r   rZ   r   r   r   rU   )r
   r   )__name__
__module____qualname____firstlineno____doc__r   r   r   callabler   r   dict__annotations__r   r   r   r   r   r   __static_attributes____classcell__)r   s   @r6   r   r     s    FR "(AtFCD 

 4D8$?'(#$?@$GtQV<j&>RS 1d6BDI"%$D .  %*8%t 5" 6"H r8   r   )1r   r{   numbersr   r   numpyr"   scipyr   scipy.linalgr   scipy.sparse.csgraphr   scipy.sparse.linalgr   r	   baser   r   metrics.pairwiser   r5   r   r   utilsr   r   r   utils._arpackr   utils._param_validationr   r   r   utils.extmathr   utils.fixesr   r}   r   r   utils.validationr   r7   r?   rO   rd   rc   r    r8   r6   <module>r      s   
  "    5 - . ) : 
 , K K ; 8 3 ,*ZL@+\ "O4!(AtFCD#$?@$G'(tQV<j&>RS$+ k #' BBP h*Vr rr8   