
    -iP              
           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
JrJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSKJrJr  S rS r\" S/S/S.SS9SSSSSSSSS.S j5       r " S S\\
5      rg)z*Affinity Propagation clustering algorithm.    N)IntegralReal   )config_context)BaseEstimatorClusterMixin_fit_context)ConvergenceWarning)euclidean_distancespairwise_distances_argmin)check_random_state)Interval
StrOptionsvalidate_params)check_is_fittedvalidate_datac                 H   ^ ^ U4S jnU 4S jnU" 5       =(       a    U" 5       $ )Nc                  P   > [         R                  " T T R                  S   :H  5      $ )Nr   )npallflat)
preferences   X/var/www/html/venv/lib/python3.13/site-packages/sklearn/cluster/_affinity_propagation.pyall_equal_preferencesB_equal_similarities_and_preferences.<locals>.all_equal_preferences   s     vvjJOOA$6677    c                     > [         R                  " TR                  [        S9n [         R                  " U S5        [         R
                  " TU    R                  TU    R                  S   :H  5      $ )N)dtyper   )r   onesshapeboolfill_diagonalr   r   )maskSs    r   all_equal_similaritiesC_equal_similarities_and_preferences.<locals>.all_equal_similarities   sO    wwqwwd+
q!vvagllagll1o566r    )r$   r   r   r%   s   ``  r   #_equal_similarities_and_preferencesr(      s!    87 !"?'='??r   c          	      (   U R                   S   nUS:X  d  [        X5      (       Ga  [        R                  " S5        UR                  S   U R                  US-
     :  a`  U(       a-  [
        R                  " U5      [
        R                  " U5      S4$ [
        R                  " U5      [
        R                  " U5      4$ U(       a2  [
        R                  " S/5      [
        R                  " S/U-  5      S4$ [
        R                  " S/5      [
        R                  " S/U-  5      4$ XR                  SSUS-   2'   [
        R                  " X45      n	[
        R                  " X45      n
[
        R                  " X45      nU [
        R                  " U R                  5      R                  U -  [
        R                  " U R                  5      R                  S-  -   UR                  X4S9-  -  n [
        R                  " X45      n[
        R                  " U5      n[        U5       GH  n[
        R                  " XU5        [
        R                   " USS9nXU4   n[
        R"                  * XU4'   [
        R$                  " USS9n[
        R&                  " U USS2S4   U5        XU4   U-
  XU4'   USU-
  -  nX-  n
X-  n
[
        R(                  " U
SU5        U
R                  SSUS-   2   UR                  SSUS-   2'   U[
        R*                  " USS9-  n[
        R,                  " U5      R/                  5       nUR1                  S[
        R"                  U5        UUR                  SSUS-   2'   USU-
  -  nX-  n	X-  n	[
        R,                  " U	5      [
        R,                  " U
5      -   S:  nUUSS2X-  4'   [
        R*                  " USS9nX:  d  GM  [
        R*                  " USS9n[
        R*                  " UU:H  US:H  -   5      U:g  nU(       d  US:  d  X:X  d  GM  SnU(       a  [3        S	U-  5          O   S
nU(       a  [3        S5        [
        R4                  " W5      nUR6                  nUS:  GaF  U(       a  [        R                  " S[8        5        [
        R                   " U SS2U4   SS9n[
        R                  " U5      UU'   [        U5       Hx  n[
        R:                  " UU:H  5      R=                  5       S   n[
        R                   " [
        R*                  " U USS2[
        R>                  4   U4   SS95      nUU   UU'   Mz     [
        R                   " U SS2U4   SS9n[
        R                  " U5      UU'   UU   n[
        R@                  " U5      n[
        RB                  " UU5      nO7[        R                  " S[8        5        [
        R                  " S/U-  5      n/ nU(       a  UUWS-   4$ UU4$ )z$Main affinity propagation algorithm.r      zTAll samples have mutually equal similarities. Returning arbitrary cluster center(s).Nd   )size)axisFzConverged after %d iterations.TzDid not convergezcAffinity propagation did not converge, this model may return degenerate cluster centers and labels.zWAffinity propagation did not converge and this model will not have any cluster centers.)"r    r(   warningswarnr   r   arangearrayzerosfinfor   epstinystandard_normalrangeaddargmaxinfmaxsubtractmaximumsumdiagcopyclipprintflatnonzeror,   r
   asarraynonzeronewaxisuniquesearchsorted)r$   r   convergence_itermax_iterdampingverbosereturn_n_iterrandom_state	n_samplesARtmpeinditIYY2dAEKseunconvergednever_convergedckiijlabelscluster_centers_indicess                                 r   _affinity_propagationrf   "   sD    
IA~<QKK 	5	
 ??1y1} 55 ! 9%ryy';Q? ii	*BIIi,@A ! 1#!y 91= hhsmRXXqcIo%>? ",FFy1}
)'(A
)'(A
((I)
*C 
!BHHQWW$5$:$:S$@@$$9*@$A
B BA
 	)./A
))I
CHo
qSIIc"QKvvgFVVCa  	AqDz3'Qi"nF 	q7{		 	

1a%&VV,<y1},<%=!IM!" 	rvvc""WWS\ BFFC %'!IM!" 	q7{		 WWQZ"''!*$)&'!R"
"#FF11!"B&&"(8"8R1W!EF)SKQU"':R?@Y \ $%
qA	A1uMMH # IIa1gA&yy|!qAAF#++-a0B		"&&2am#4b#8!9BCAa5AaD 
 IIa1gA&yy|!1"$))F"3!8&A5 	
 2$*+"$&Q66&..r   
array-likeboolean)r$   rN   Fprefer_skip_nested_validation            ?T)r   rJ   rK   rL   rA   rM   rN   rO   c                    [        UUUUUSUUS9R                  U 5      n	U(       a#  U	R                  U	R                  U	R                  4$ U	R                  U	R                  4$ )a  Perform Affinity Propagation Clustering of data.

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

Parameters
----------
S : array-like of shape (n_samples, n_samples)
    Matrix of similarities between points.

preference : array-like of shape (n_samples,) or float, default=None
    Preferences for each point - points with larger values of
    preferences are more likely to be chosen as exemplars. The number of
    exemplars, i.e. of clusters, is influenced by the input preferences
    value. If the preferences are not passed as arguments, they will be
    set to the median of the input similarities (resulting in a moderate
    number of clusters). For a smaller amount of clusters, this can be set
    to the minimum value of the similarities.

convergence_iter : int, default=15
    Number of iterations with no change in the number
    of estimated clusters that stops the convergence.

max_iter : int, default=200
    Maximum number of iterations.

damping : float, default=0.5
    Damping factor between 0.5 and 1.

copy : bool, default=True
    If copy is False, the affinity matrix is modified inplace by the
    algorithm, for memory efficiency.

verbose : bool, default=False
    The verbosity level.

return_n_iter : bool, default=False
    Whether or not to return the number of iterations.

random_state : int, RandomState instance or None, default=None
    Pseudo-random number generator to control the starting state.
    Use an int for reproducible results across function calls.
    See the :term:`Glossary <random_state>`.

    .. versionadded:: 0.23
        this parameter was previously hardcoded as 0.

Returns
-------
cluster_centers_indices : ndarray of shape (n_clusters,)
    Index of clusters centers.

labels : ndarray of shape (n_samples,)
    Cluster labels for each point.

n_iter : int
    Number of iterations run. Returned only if `return_n_iter` is
    set to True.

Notes
-----
For an example usage,
see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`.
You may also check out,
:ref:`sphx_glr_auto_examples_applications_plot_stock_market.py`

When the algorithm does not converge, it will still return a arrays of
``cluster_center_indices`` and labels if there are any exemplars/clusters,
however they may be degenerate and should be used with caution.

When all training samples have equal similarities and equal preferences,
the assignment of cluster centers and labels depends on the preference.
If the preference is smaller than the similarities, a single cluster center
and label ``0`` for every sample will be returned. Otherwise, every
training sample becomes its own cluster center and is assigned a unique
label.

References
----------
Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages
Between Data Points", Science Feb. 2007

Examples
--------
>>> import numpy as np
>>> from sklearn.cluster import affinity_propagation
>>> from sklearn.metrics.pairwise import euclidean_distances
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [4, 2], [4, 4], [4, 0]])
>>> S = -euclidean_distances(X, squared=True)
>>> cluster_centers_indices, labels = affinity_propagation(S, random_state=0)
>>> cluster_centers_indices
array([0, 3])
>>> labels
array([0, 0, 0, 1, 1, 1])
precomputedrL   rK   rJ   rA   r   affinityrM   rO   )AffinityPropagationfitcluster_centers_indices_labels_n_iter_)
r$   r   rJ   rK   rL   rA   rM   rN   rO   	estimators
             r   affinity_propagationrx      sp    d $)!	 
c!f  1193D3DiFWFWWW--y/@/@@@r   c                      ^  \ rS rSr% Sr\" \SSSS9/\" \SSSS9/\" \SSSS9/S	/S
\" \SSSS9S/\" SS15      /S/S/S.r	\
\S'   SSSSSSSSS.S jrU 4S jr\" SS9SS j5       rS rSU 4S jjrSrU =r$ )rr   i8  a^  Perform Affinity Propagation Clustering of data.

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

Parameters
----------
damping : float, default=0.5
    Damping factor in the range `[0.5, 1.0)` is the extent to
    which the current value is maintained relative to
    incoming values (weighted 1 - damping). This in order
    to avoid numerical oscillations when updating these
    values (messages).

max_iter : int, default=200
    Maximum number of iterations.

convergence_iter : int, default=15
    Number of iterations with no change in the number
    of estimated clusters that stops the convergence.

copy : bool, default=True
    Make a copy of input data.

preference : array-like of shape (n_samples,) or float, default=None
    Preferences for each point - points with larger values of
    preferences are more likely to be chosen as exemplars. The number
    of exemplars, ie of clusters, is influenced by the input
    preferences value. If the preferences are not passed as arguments,
    they will be set to the median of the input similarities.

affinity : {'euclidean', 'precomputed'}, default='euclidean'
    Which affinity to use. At the moment 'precomputed' and
    ``euclidean`` are supported. 'euclidean' uses the
    negative squared euclidean distance between points.

verbose : bool, default=False
    Whether to be verbose.

random_state : int, RandomState instance or None, default=None
    Pseudo-random number generator to control the starting state.
    Use an int for reproducible results across function calls.
    See the :term:`Glossary <random_state>`.

    .. versionadded:: 0.23
        this parameter was previously hardcoded as 0.

Attributes
----------
cluster_centers_indices_ : ndarray of shape (n_clusters,)
    Indices of cluster centers.

cluster_centers_ : ndarray of shape (n_clusters, n_features)
    Cluster centers (if affinity != ``precomputed``).

labels_ : ndarray of shape (n_samples,)
    Labels of each point.

affinity_matrix_ : ndarray of shape (n_samples, n_samples)
    Stores the affinity matrix used in ``fit``.

n_iter_ : int
    Number of iterations taken to converge.

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

See Also
--------
AgglomerativeClustering : Recursively merges the pair of
    clusters that minimally increases a given linkage distance.
FeatureAgglomeration : Similar to AgglomerativeClustering,
    but recursively merges features instead of samples.
KMeans : K-Means clustering.
MiniBatchKMeans : Mini-Batch K-Means clustering.
MeanShift : Mean shift clustering using a flat kernel.
SpectralClustering : Apply clustering to a projection
    of the normalized Laplacian.

Notes
-----
The algorithmic complexity of affinity propagation is quadratic
in the number of points.

When the algorithm does not converge, it will still return a arrays of
``cluster_center_indices`` and labels if there are any exemplars/clusters,
however they may be degenerate and should be used with caution.

When ``fit`` does not converge, ``cluster_centers_`` is still populated
however it may be degenerate. In such a case, proceed with caution.
If ``fit`` does not converge and fails to produce any ``cluster_centers_``
then ``predict`` will label every sample as ``-1``.

When all training samples have equal similarities and equal preferences,
the assignment of cluster centers and labels depends on the preference.
If the preference is smaller than the similarities, ``fit`` will result in
a single cluster center and label ``0`` for every sample. Otherwise, every
training sample becomes its own cluster center and is assigned a unique
label.

References
----------

Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages
Between Data Points", Science Feb. 2007

Examples
--------
>>> from sklearn.cluster import AffinityPropagation
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [4, 2], [4, 4], [4, 0]])
>>> clustering = AffinityPropagation(random_state=5).fit(X)
>>> clustering
AffinityPropagation(random_state=5)
>>> clustering.labels_
array([0, 0, 0, 1, 1, 1])
>>> clustering.predict([[0, 0], [4, 4]])
array([0, 1])
>>> clustering.cluster_centers_
array([[1, 2],
       [4, 2]])

For an example usage,
see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`.

For a comparison of Affinity Propagation with other clustering algorithms, see
:ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py`
rm   g      ?left)closedr*   Nrh   rg   neither	euclideanro   rM   rO   rp   _parameter_constraintsrl   rk   TFc                d    Xl         X l        X0l        X@l        Xpl        XPl        X`l        Xl        g N)rL   rK   rJ   rA   rM   r   rq   rO   )	selfrL   rK   rJ   rA   r   rq   rM   rO   s	            r   __init__AffinityPropagation.__init__  s.       0	$ (r   c                    > [         TU ]  5       nU R                  S:H  UR                  l        U R                  S:g  UR                  l        U$ )Nro   )super__sklearn_tags__rq   
input_tagspairwisesparse)r   tags	__class__s     r   r   $AffinityPropagation.__sklearn_tags__  s?    w')#'==M#A !%-!?r   ri   c                    U R                   S:X  a  [        XU R                  SS9nXl        O[        XSS9n[	        USS9* U l        U R                  R
                  S   U R                  R
                  S   :w  a#  [        S	U R                  R
                   S
35      eU R                  c!  [        R                  " U R                  5      nOU R                  n[        R                  " U5      n[        U R                  5      n[        U R                  U R                  U R                  UU R                   U R"                  SUS9u  U l        U l        U l        U R                   S:w  a!  XR$                     R                  5       U l        U $ )a#  Fit the clustering from features, or affinity matrix.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), or                 array-like of shape (n_samples, n_samples)
    Training instances to cluster, or similarities / affinities between
    instances if ``affinity='precomputed'``. If a sparse feature matrix
    is provided, it will be converted into a sparse ``csr_matrix``.

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

Returns
-------
self
    Returns the instance itself.
ro   T)rA   force_writeablecsr)accept_sparse)squaredr   r*   z7The matrix of similarities must be a square array. Got z	 instead.)rK   rJ   r   rL   rM   rN   rO   )rq   r   rA   affinity_matrix_r   r    
ValueErrorr   r   medianrE   r   rO   rf   rK   rJ   rL   rM   rt   ru   rv   cluster_centers_)r   Xyr   rO   s        r   rs   AffinityPropagation.fit  s^   ( ==M)dDIItLA$%!dU;A%8D%I$ID!  &&q)T-B-B-H-H-KK,,2239> 
 ??"4#8#89JJZZ
+
)$*;*;< "!!]]!22!LLLL%	
		
)LL ==M)$%&C&C$D$I$I$KD!r   c                    [        U 5        [        XSSS9n[        U S5      (       d  [        S5      eU R                  R
                  S   S:  a(  [        SS9   [        XR                  5      sS	S	S	5        $ [        R                  " S
[        5        [        R                  " S/UR
                  S   -  5      $ ! , (       d  f       g	= f)aM  Predict the closest cluster each sample in X belongs to.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    New data to predict. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
labels : ndarray of shape (n_samples,)
    Cluster labels.
Fr   )resetr   r   z<Predict method is not supported when affinity='precomputed'.r   T)assume_finiteNzzThis model does not have any cluster centers because affinity propagation did not converge. Labeling every sample as '-1'.r.   )r   r   hasattrr   r   r    r   r   r/   r0   r
   r   r2   )r   r   s     r   predictAffinityPropagation.predict)  s     	$eDt/00N    &&q)A-d304I4IJ 43 MM5 # 88RD1771:-.. 43s   B::
Cc                 "   > [         TU ]  X5      $ )aG  Fit clustering from features/affinity matrix; return cluster labels.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), or                 array-like of shape (n_samples, n_samples)
    Training instances to cluster, or similarities / affinities between
    instances if ``affinity='precomputed'``. If a sparse feature matrix
    is provided, it will be converted into a sparse ``csr_matrix``.

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

Returns
-------
labels : ndarray of shape (n_samples,)
    Cluster labels.
)r   fit_predict)r   r   r   r   s      r   r   AffinityPropagation.fit_predictL  s    & w"1((r   )rq   r   r   rt   rJ   rA   rL   ru   rK   rv   r   rO   rM   r   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   r~   dict__annotations__r   r   r	   rs   r   r   __static_attributes____classcell__)r   s   @r   rr   rr   8  s    GT T3F;<h4?@%h4GHT4i8

  m <=>;'($D $ )* 5: 6:x!/F) )r   rr   )r   r/   numbersr   r   numpyr   _configr   baser   r   r	   
exceptionsr
   metricsr   r   utilsr   utils._param_validationr   r   r   utils.validationr   r   r(   rf   rx   rr   r'   r   r   <module>r      s    0
  "  $ < < + D & K K =@M/h ^# #( 	xAxAvg), g)r   