
    0Pht                        d Z ddlZddlmZmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZmZmZ ddlmZ ddlmZm Z m!Z! ddl"m#Z# ddl$m%Z& ddl$m'Z'm(Z( ddl)m*Z* d Z+d Z,d Z- e!ddg eeddd          g e h d          dgdg eeddd           e dh          gdgdgdd !          d"dddd d d#d$            Z.d"dddd d d#d%Z/ G d& d'e          Z0dS )(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                    | j         d         }t          j        |           r|                                 } t	          j        |t                    }t	          j        |t                    }d||<   t          |          D ]}|                                }t	          j	        |||           ||                                k    r nt	          j
        |          d         }|                    d           |D ]g}t          j        |           r2| |gddf                                                                         }	n| |         }	t	          j	        ||	|           h|S )aC  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
             d/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/manifold/_spectral_embedding.py_graph_connected_componentr7       sm   ( [^Fu hvT222Oxd333 $W6]] M M,0022
o'7_MMMM!4!4!6!666E(+,,Q/e$$$ 	M 	MAu%% % "1#qqq&M113399;;		!!H	M*I;KLLLLL	M     c                    t          j        |           rBt          t          d          k    }t	          | d|          } t          |           \  }}|dk    S t          | d                                          | j        d         k    S )a~  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?   M   s     u L )M(,C,CC;N
 
 
 %9$?$?!%** *%337799U[^KKr8   c                 x   | j         d         }t          j        |           s|r|| j        dd|dz   <   n|                                 } |r| j        | j        k    }|| j        |<   t          j	        | j        | j        z
            j
        }|dk    r|                                 } n|                                 } | S )aM  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   m   s    , oa G?9%% * 	3-2IN>>gk>*OO%%	 	- }	5H',IN8$ )IMIM9::?a<<!))II "))Ir8   z
array-likezsparse matrixr=   leftclosed   amgarpackr	   random_stateautoboolean	adjacencyn_componentseigen_solverrV   	eigen_tolrK   
drop_firstTprefer_skip_nested_validation   r[   r\   rV   r]   rK   r^   c          	      L    t          |          }t          | ||||||          S )a  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)
    rb   )r   _spectral_embeddingrY   s          r6   spectral_embeddingre      s>    H &l33L!!!%   r8   c                   t          |           } |dk    r*	 ddlm} n"# t          $ r}t	          d          |d }~ww xY w|d}| j        d         }	|r|dz   }t          |           st          j        d           t          | |d	          \  }
}|dk    s#|d
k    rt          j        |
          r	|	d|z  k     rt          |
d|          }
	 |dk    rdn|}|
dz  }
t          |
j        d         |          }t          |
dd          }
t          |
|dd||          \  }}|j        |d d         }|r||z  }n# t"          $ r d
}|
dz  }
Y nw xY w|dk    rt          j        |
          st          j        d           t          |
t$          j        t$          j        gd          }
t          |
d|          }
dt          j        |
j        d                   z  }|
|z  }
t-          t          d          r.t/          |
t          j                  rt          j        |
          }
 |t          |
d                    }|
|z  }
|                                }|                    |
j        d         |dz   f          }|                                |d d df<   |                    |
j                  }|dk    rd n|}t?          |
|||d          \  }}|j        }|r||z  }|j        d         dk    rt          |d
k    rBt          |
t$          j        t$          j        gd          }
|	d|z  dz   k     rSt          j        |
          r|
                                 }
tC          |
d          \  }}|j        d |         }|r||z  }nt          |
d|          }
|                    |
j        d         |dz   f          }|                                |d d df<   |                    |
j                  }|dk    rd n|}t?          |
||dd          \  }}|j        d |         }|r||z  }|j        d         dk    rt          tE          |          }|r|d|         j        S |d |         j        S )NrT   r   )smoothed_aggregation_solverz>The eigen_solver was set to 'amg', but pyamg is not available.rU   r=   zJGraph is not fully connected, spectral embedding may not work as expected.T)normedreturn_diagr	      rW   csrFr:         ?LM)ksigmawhichtolv0z$AMG works better for sparse matrices)r   r;   gh㈵>	csr_array)r;   )rH   )Mrr   largest)check_finitei  )rr   rv   maxiter)#r   pyamgrg   ImportError
ValueErrorr   r?   warningswarncsgraph_laplacianr   r    rO   r   r   r   TRuntimeErrorr"   float64float32eyehasattr
isinstancert   
csr_matrixaspreconditionerstandard_normalr+   astyper   r	   r*   r   r   )rZ   r[   r\   rV   r]   rK   r^   rg   erL   r   ddrr   rs   r1   diffusion_map	embedding
diag_shiftmlru   Xs                        r6   rd   rd   ,  ss     	**Iu	9999999 	 	 	P 	
 oa G (#a'y)) 
X	
 	
 	
 &.d  MIr 	  8##++ $/6\9I/I/I iN;;	 	 !F**!!	COI !3\BBB#E  I  %\Dcb     A} &(8b(89I +%N	 	 	 	 $LOIII	 
		 y)) 	BM@AAAbj"*5T
 
 
	 iN;;	 FJyq'9:::
Z	6;'' 	5Jy&BR,S,S 	5 ))44I((Ye)T)T)TUUZ	!!((yq/A<RSCS.T(UU((**!!!Q$HHY_%%6))ddy!)Q!eLLL=!O	 	'!BI?1""xbj"*5T
 
 
	 Q%))) y)) 0%--//	#IEBBBA}%6I +%N	!)Q??I ,,oa(,*:; -  A hhjjAaaadG))A#v--$$9C%1#ud     A} &6I +%N	q!Q&&  /	::I *<(**,'))s#    
=8=A+D8 8EEc                   `    e Zd ZU dZ eeddd          g eh d          eg eeddd          dgdg eh d	          dg eeddd           ed
h          g eeddd          dgdegdZ	e
ed<   	 dddddd
ddddZ fdZddZ ed          dd            ZddZ xZS )SpectralEmbeddinga  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   rV   rS   rW   r[   affinitygammarV   r\   r]   n_neighborsn_jobs_parameter_constraintsr
   r   )r   r   rV   r\   r]   r   r   c                v    || _         || _        || _        || _        || _        || _        || _        || _        d S Nr   )	selfr[   r   r   rV   r\   r]   r   r   s	            r6   __init__zSpectralEmbedding.__init__v  sD     ) 
(("&r8   c                     t                                                      }d|j        _        | j        dv |j        _        |S )NT)r   r   )super__sklearn_tags__
input_tagsr   r   pairwise)r   tags	__class__s     r6   r   z"SpectralEmbedding.__sklearn_tags__  s?    ww''))!%#'= 5
 $
  r8   c                 f   | j         dk    r|| _        | j        S | j         dk    r_t          | j        | j        d                              |          }|                    |d          }d||j        z   z  | _        | j        S | j         dk    rt          j	        |          rt          j        d           d	| _         n| j        | j        n*t          t          |j        d         dz            d          | _        t          || j        d| j                  | _        d| j        | j        j        z   z  | _        | j        S | j         d	k    rE| j        | j        nd|j        d         z  | _        t%          || j                  | _        | j        S |                      |          | _        | j        S )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   Nr   
   r=   T)include_selfr   rm   )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_matrixz&SpectralEmbedding._get_affinity_matrix  s   & =M))$%D!((=;;;( ,T[  c!ff  %555OOL$'<,.+H$ID!((=///q!! -#  
 !& '3 $$Sb11155 !
 )9t(tDK) ) )% ),)D,A,CC)% ,,=E!!(,
(>$**C!'RS*DTDK$.q$D$D$DD!(( $a 0 0$$r8   Tr_   c                     t          | |dd          }t          | j                  }|                     |          }t	          || j        | j        | j        |          | _        | S )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.
        rl   r
   )r;   ensure_min_samples)r[   r\   r]   rV   )	r   r   rV   r   rd   r[   r\   r]   
embedding_)r   r   yrV   affinity_matrixs        r6   r   zSpectralEmbedding.fit  sq    . $1MMM)$*;<<33A66-**n%
 
 
 r8   c                 :    |                      |           | j        S )a  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_transformzSpectralEmbedding.fit_transform  s    , 	r8   )r
   r   )__name__
__module____qualname____doc__r   r   r   callabler   r   dict__annotations__r   r   r   r   r   r   __classcell__)r   s   @r6   r   r     s        F FR "(AtFCCCDJ    

 (4D888$?'(#$?$?$?@@$GhtQV<<<jj&>R>RS 1d6BBBDI"%$ $D   .  %    *    8% 8% 8% 8%t \555" " " 65"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   re   rd   r    r8   r6   <module>r      s      " " " " " " " "                 5 5 5 5 5 5 - - - - - - - - . . . . . . . . ) ) ) ) ) ) : : : : : : : :         
 , + + + + + K K K K K K K K K K ; ; ; ; ; ; 8 8 8 8 8 8 3 3 3 3 3 3 3 3 , , , , , ,* * *ZL L L@+ + +\ "O4!(AtFCCCD#$?$?$?@@$G'(htQV<<<jj&>R>RS$+ k  #'   B B B B BP i* i* i* i* i*Xr r r r r r r r r rr8   