
    KiRR                         S r SSK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
  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  SSKJr  SSKJrJrJrJrJrJr  SSK J!r!J"r"  SSK#J$r$J%r%  S r& " S S\\\S9r'g)zBase class for mixture models.    N)ABCMetaabstractmethod)nullcontext)IntegralReal)time)cluster)BaseEstimatorDensityMixin_fit_context)kmeans_plusplus)ConvergenceWarning)check_random_state)_convert_to_numpy_is_numpy_namespace
_logsumexp_max_precision_float_dtypeget_namespaceget_namespace_and_device)Interval
StrOptions)check_is_fittedvalidate_datac                 f    U R                   U:w  a!  [        SU< SU< SU R                   < 35      eg)zyValidate the shape of the input parameter 'param'.

Parameters
----------
param : array

param_shape : tuple

name : str
zThe parameter 'z' should have the shape of z
, but got N)shape
ValueError)paramparam_shapenames      W/var/www/html/dynamic-report/venv/lib/python3.13/site-packages/sklearn/mixture/_base.py_check_shaper!      s2     {{k![%++/
 	
 "    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9/\" \SSSS9/\" 1 S	k5      /S
/S/S/\" \SSSS9/S.
r	\
\S'   S r\S(S j5       rS(S jr\S 5       rS(S jr\" SS9S(S j5       rS(S jr\S 5       r\S 5       r\S 5       rS rS(S jrS rS rS)S jrS(S  jr\S(S! j5       r\S(S" j5       rS(S# jr S$ r!S% r"S& r#S'r$g)*BaseMixture1   zBase class for mixture models.

This abstract class specifies an interface for all mixture classes and
provides basic common methods for mixture models.
   Nleft)closedg        r   >   kmeansrandomrandom_from_data	k-means++random_statebooleanverbose
n_componentstol	reg_covarmax_itern_initinit_paramsr-   
warm_startr/   verbose_interval_parameter_constraintsc                 |    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        g Nr0   )selfr1   r2   r3   r4   r5   r6   r-   r7   r/   r8   s              r    __init__BaseMixture.__init__G   s:     )" &($ 0r"   c                     g)zwCheck initial parameters of the derived class.

Parameters
----------
X : array-like of shape  (n_samples, n_features)
N r<   Xxps      r    _check_parametersBaseMixture._check_parameters_        	r"   c                 
   [        XS9u  p4nUR                  u  pdU R                  S:X  a  [        R                  " X`R
                  4UR                  S9n[        R                  " U R
                  SUS9R                  U5      R                  nSU[        R                  " U5      U4'   GOGU R                  S:X  aW  UR                  UR                  X`R
                  4S9UR                  US9nXsR                  USS	9S
S
2UR                  4   -  nOU R                  S:X  a[  UR	                  X`R
                  4UR                  US9nUR!                  X`R
                  SS9n	[#        U	5       H  u  pSX{U
4'   M     OuU R                  S:X  ae  [        R                  " X`R
                  4UR                  S9n[%        UU R
                  US9u  pISXy[        R                  " U R
                  5      4'   U R'                  UW5        g
)a  Initialize the model parameters.

Parameters
----------
X : array-like of shape  (n_samples, n_features)

random_state : RandomState
    A random number generator instance that controls the random seed
    used for the method chosen to initialize the parameters.
rC   r)   )dtyper&   )
n_clustersr5   r-   r*   sizerI   deviceaxisNr+   F)rL   replacer,   )r-   )r   r   r6   npzerosr1   rI   r	   KMeansfitlabels_arangeasarrayuniformsumnewaxischoice	enumerater   _initialize)r<   rB   r-   rC   _rN   	n_samplesresplabelindicescolindexs               r    _initialize_parameters"BaseMixture._initialize_parametersi   s    1:vww	x'88Y(9(9:!''JD#00 Q  12D9%u,-)::$$96G6G*H$Igg  D
 FF4aF(BJJ77D!3388--.aggf  D #)) 1 15 * G (0
#$CZ  1,88Y(9(9:!''JD(!!)JA
 ;<D"))D$5$5667D!r"   c                     g)zInitialize the model parameters of the derived class.

Parameters
----------
X : array-like of shape  (n_samples, n_features)

resp : array-like of shape (n_samples, n_components)
Nr@   )r<   rB   ra   s      r    r^   BaseMixture._initialize   s     	r"   c                 (    U R                  X5        U $ )aX  Estimate model parameters with the EM algorithm.

The method fits the model ``n_init`` times and sets the parameters with
which the model has the largest likelihood or lower bound. Within each
trial, the method iterates between E-step and M-step for ``max_iter``
times until the change of likelihood or lower bound is less than
``tol``, otherwise, a ``ConvergenceWarning`` is raised.
If ``warm_start`` is ``True``, then ``n_init`` is ignored and a single
initialization is performed upon the first call. Upon consecutive
calls, training starts where it left off.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    List of n_features-dimensional data points. Each row
    corresponds to a single data point.

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

Returns
-------
self : object
    The fitted mixture.
)fit_predict)r<   rB   ys      r    rU   BaseMixture.fit   s    6 	r"   T)prefer_skip_nested_validationc                    [        U5      u  p4[        XUR                  UR                  /SS9nUR                  S   U R
                  :  a(  [        SU R
                   SUR                  S    35      eU R                  XS9  U R                  =(       a    [        U S5      (       + nU(       a  U R                  OSnUR                  * n/ nS	U l        [        U R                  5      n	UR                  u  p[        U5       GHW  nU R!                  U5        U(       a  U R#                  XUS9  U(       a  UR                  * OU R$                  n/ nU R&                  S:X  a  U R)                  5       nSnMr  S	n[        SU R&                  S-   5       H  nUnU R+                  XS9u  nnU R-                  UUUS9  U R/                  UU5      nUR1                  U5        UU-
  nU R3                  UU5        [5        U5      U R6                  :  d  M}  S
n  O   U R9                  UU5        X:  d  XsR                  * :X  d  GM:  UnU R)                  5       nWnUnUU l        GMZ     U R                  (       d+  U R&                  S:  a  [:        R<                  " S[>        5        U RA                  WUS9  WU l!        Xpl        Xl"        U R+                  XS9u  nnURG                  USS9$ )aB  Estimate model parameters using X and predict the labels for X.

The method fits the model ``n_init`` times and sets the parameters with
which the model has the largest likelihood or lower bound. Within each
trial, the method iterates between E-step and M-step for `max_iter`
times until the change of likelihood or lower bound is less than
`tol`, otherwise, a :class:`~sklearn.exceptions.ConvergenceWarning` is
raised. After fitting, it predicts the most probable label for the
input data points.

.. versionadded:: 0.20

Parameters
----------
X : array-like of shape (n_samples, n_features)
    List of n_features-dimensional data points. Each row
    corresponds to a single data point.

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

Returns
-------
labels : array, shape (n_samples,)
    Component labels.
   )rI   ensure_min_samplesr   z:Expected n_samples >= n_components but got n_components = z, n_samples = rH   
converged_r&   FTzBest performing initialization did not converge. Try different init parameters, or increase max_iter, tol, or check for degenerate data.rO   )$r   r   float64float32r   r1   r   rD   r7   hasattrr5   infrr   r   r-   range_print_verbose_msg_init_begrf   lower_bound_r4   _get_parameters_e_step_m_step_compute_lower_boundappend_print_verbose_msg_iter_endabsr2   _print_verbose_msg_init_endwarningswarnr   _set_parametersn_iter_lower_bounds_argmax)r<   rB   rl   rC   r_   do_initr5   max_lower_boundbest_lower_boundsr-   r`   initlower_boundcurrent_lower_boundsbest_paramsbest_n_iter	convergedn_iterprev_lower_boundlog_prob_normlog_respchanges                         r    rk   BaseMixture.fit_predict   s   8 a $"**bjj)AVWX771:)))**.*;*;)< = wwqzl, 
 	q( F74+FG 'Q66')$*;*;<ww	&MD,,T2++A+C%,266'$2C2CK#% }}!"224!	#At}}q'89F'2$.2ll1l.D+M8LLHL4"&";";Hm"TK(//<(+;;F44VVD6{TXX-$(	 : 00iH0Ow4N&1O"&"6"6"8K"(K(<%&/DOI "R 4==1#4MM9 # 	[R0"+.
 ll1l,8yyy**r"   c                 `    [        XS9u  p#U R                  XS9u  pEUR                  U5      U4$ )a`  E step.

Parameters
----------
X : array-like of shape (n_samples, n_features)

Returns
-------
log_prob_norm : float
    Mean of the logarithms of the probabilities of each sample in X

log_responsibility : array, shape (n_samples, n_components)
    Logarithm of the posterior probabilities (or responsibilities) of
    the point of each sample in X.
rH   )r   _estimate_log_prob_respmean)r<   rB   rC   r_   r   r   s         r    r{   BaseMixture._e_step:  s:      a'"&">">q">"Hww}%x//r"   c                     g)zM step.

Parameters
----------
X : array-like of shape (n_samples, n_features)

log_resp : array-like of shape (n_samples, n_components)
    Logarithm of the posterior probabilities (or responsibilities) of
    the point of each sample in X.
Nr@   )r<   rB   r   s      r    r|   BaseMixture._m_stepN  s     	r"   c                     g r;   r@   )r<   s    r    rz   BaseMixture._get_parameters\      r"   c                     g r;   r@   )r<   paramss     r    r   BaseMixture._set_parameters`  r   r"   c                 ^    [        U 5        [        XSS9n[        U R                  U5      SS9$ )aK  Compute the log-likelihood of each sample.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    List of n_features-dimensional data points. Each row
    corresponds to a single data point.

Returns
-------
log_prob : array, shape (n_samples,)
    Log-likelihood of each sample in `X` under the current model.
Fresetr&   rO   )r   r   r   _estimate_weighted_log_prob)r<   rB   s     r    score_samplesBaseMixture.score_samplesd  s0     	$/$::1=AFFr"   c                 n    [        U5      u  p4[        UR                  U R                  U5      5      5      $ )a  Compute the per-sample average log-likelihood of the given data X.

Parameters
----------
X : array-like of shape (n_samples, n_dimensions)
    List of n_features-dimensional data points. Each row
    corresponds to a single data point.

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

Returns
-------
log_likelihood : float
    Log-likelihood of `X` under the Gaussian mixture model.
)r   floatr   r   )r<   rB   rl   rC   r_   s        r    scoreBaseMixture.scorew  s/    " a RWWT//2344r"   c                     [        U 5        [        U5      u  p#[        XSS9nUR                  U R	                  U5      SS9$ )a4  Predict the labels for the data samples in X using trained model.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    List of n_features-dimensional data points. Each row
    corresponds to a single data point.

Returns
-------
labels : array, shape (n_samples,)
    Component labels.
Fr   r&   rO   )r   r   r   r   r   )r<   rB   rC   r_   s       r    predictBaseMixture.predict  sB     	a $/yy99!<1yEEr"   c                     [        U 5        [        XSS9n[        U5      u  p#U R                  XS9u  p4UR	                  U5      $ )aV  Evaluate the components' density for each sample.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    List of n_features-dimensional data points. Each row
    corresponds to a single data point.

Returns
-------
resp : array, shape (n_samples, n_components)
    Density of each Gaussian component for each sample in X.
Fr   rH   )r   r   r   r   exp)r<   rB   rC   r_   r   s        r    predict_probaBaseMixture.predict_proba  sH     	$/a 2212<vvhr"   c                 |   [        U 5        [        U R                  5      u  p#nUS:  a  [        SU R                  -  5      eU R                  R
                  u  p5[        U R                  5      nUR                  U[        U R                  U5      5      nU R                  S:X  a|  [        R                  " [        [        U R                  U5      [        U R                  U5      U5       VV	V
s/ s H!  u  pn
UR!                  X[#        U
5      5      PM#     sn
n	n5      nGOU R                  S:X  ax  [        R                  " [        [        U R                  U5      U5       VV
s/ s H5  u  pUR!                  U[        U R                  U5      [#        U
5      5      PM7     sn
n5      nO[        R                  " [        [        U R                  U5      [        U R                  U5      U5       VV	V
s/ s H0  u  pn
UUR%                  X4S9[        R&                  " U	5      -  -   PM2     sn
n	n5      nUR)                  [+        [-        U5      5       Vs/ s H)  nUR/                  [#        X|   5      XR0                  US9PM+     sn5      n[3        X$S9nUR5                  XUS9U4$ s  sn
n	nf s  sn
nf s  sn
n	nf s  snf )a!  Generate random samples from the fitted Gaussian distribution.

Parameters
----------
n_samples : int, default=1
    Number of samples to generate.

Returns
-------
X : array, shape (n_samples, n_features)
    Randomly generated sample.

y : array, shape (nsamples,)
    Component labels.
r&   zNInvalid value for 'n_samples': %d . The sampling requires at least one sample.fulltiedrK   rM   )rC   rN   )r   r   means_r   r1   r   r   r-   multinomialr   weights_covariance_typerR   vstackzipcovariances_multivariate_normalintstandard_normalsqrtconcatrw   lenr   int64r   rX   )r<   r`   rC   r_   device_
n_featuresrngn_samples_compr   
covariancesamplerB   irl   max_float_dtypes                  r    r   BaseMixture.sample  s     	1$++>wq=$'+'8'8: 
 )) !2!23(;
 6)		 7:)$++r:)$*;*;R@&7726 ++Dc&kJ7	A !!V+		
 +.)$++r:N+	+ ++/0A0A2FF+		A 		
 7:)$++r:)$*;*;R@&7		726 ))/C)Dggj)**7		A II s>233A N-.'R3
 5Kzz!7zCQFFU	s   .(J%$<J,
27J20J9c                 @    U R                  XS9U R                  US9-   $ )zEstimate the weighted log-probabilities, log P(X | Z) + log weights.

Parameters
----------
X : array-like of shape (n_samples, n_features)

Returns
-------
weighted_log_prob : array, shape (n_samples, n_component)
rH   )_estimate_log_prob_estimate_log_weightsrA   s      r    r   'BaseMixture._estimate_weighted_log_prob  s,     &&q&043M3MQS3M3TTTr"   c                     g)zEstimate log-weights in EM algorithm, E[ log pi ] in VB algorithm.

Returns
-------
log_weight : array, shape (n_components, )
Nr@   )r<   rC   s     r    r   !BaseMixture._estimate_log_weights  rF   r"   c                     g)zEstimate the log-probabilities log P(X | Z).

Compute the log-probabilities per each component for each sample.

Parameters
----------
X : array-like of shape (n_samples, n_features)

Returns
-------
log_prob : array, shape (n_samples, n_component)
Nr@   rA   s      r    r   BaseMixture._estimate_log_prob  s     	r"   c                    [        XS9u  p#U R                  XS9n[        USUS9n[        U5      (       a  [        R
                  " SS9O	[        5       nU   XESS2UR                  4   -
  nSSS5        XW4$ ! , (       d  f       UW4$ = f)a  Estimate log probabilities and responsibilities for each sample.

Compute the log probabilities, weighted log probabilities per
component and responsibilities for each sample in X with respect to
the current state of the model.

Parameters
----------
X : array-like of shape (n_samples, n_features)

Returns
-------
log_prob_norm : array, shape (n_samples,)
    log p(X)

log_responsibilities : array, shape (n_samples, n_components)
    logarithm of the responsibilities
rH   r&   )rP   rC   ignore)underN)r   r   r   r   rR   errstater   r[   )r<   rB   rC   r_   weighted_log_probr   context_managerr   s           r    r   #BaseMixture._estimate_log_prob_resp&  s    & a' <<Q<F"#41D ,?r+B+BBKKh' 	 (BJJ+GGH  && _ h&&s   A77
Bc                     U R                   S:X  a  [        SU-  5        gU R                   S:  a/  [        SU-  5        [        5       U l        U R                  U l        gg)(Print verbose message on initialization.r&   zInitialization %drp   N)r/   printr   _init_prev_time_iter_prev_time)r<   r5   s     r    rx   'BaseMixture._print_verbose_msg_init_begF  sS    <<1%./\\Q%./#'6D #'#7#7D  r"   c                     XR                   -  S:X  a^  U R                  S:X  a  [        SU-  5        gU R                  S:  a.  [        5       n[        SXU R                  -
  U4-  5        X0l        ggg)r   r   r&   z  Iteration %drp   z0  Iteration %d	 time lapse %.5fs	 ll change %.5fN)r8   r/   r   r   r   )r<   r   diff_llcur_times       r    r   'BaseMixture._print_verbose_msg_iter_endO  sv    )))Q.||q &/0"6H$*>*>>HI (0$ # /r"   c           	          U(       a  SOSnU R                   S:X  a  [        SU S35        g
U R                   S:  a/  [        5       U R                  -
  n[        SU SUS S	US S35        g
g
)z.Print verbose message on the end of iteration.r   zdid not converger&   zInitialization .rp   z. time lapse z.5fzs	 lower bound N)r/   r   r   r   )r<   lbinit_has_convergedconverged_msgts        r    r   'BaseMixture._print_verbose_msg_init_end\  sw    '9?Q<<1OM?!45\\Q---A!-aW Es81 r"   )r   r   rr   r6   ry   r   r4   r1   r5   r   r-   r3   r2   r/   r8   r7   r;   )r&   )%__name__
__module____qualname____firstlineno____doc__r   r   r   r   r9   dict__annotations__r=   r   rD   rf   r^   rU   r   rk   r{   r|   rz   r   r   r   r   r   r   r   r   r   r   rx   r   r   __static_attributes__r@   r"   r    r$   r$   1   s    "(AtFCDsD89tS$v>?h4?@Haf=>LM
 (( k;%h4GH$D 10  5"n 	 	< 5m+ 6m+^0(      G&5(F& (KGZU    '@80
r"   r$   )	metaclass)(r   r   abcr   r   
contextlibr   numbersr   r   r   numpyrR   sklearnr	   sklearn.baser
   r   r   sklearn.clusterr   sklearn.exceptionsr   sklearn.utilsr   sklearn.utils._array_apir   r   r   r   r   r   sklearn.utils._param_validationr   r   sklearn.utils.validationr   r   r!   r$   r@   r"   r    <module>r     sX    $
  ' " "    B B + 1 ,  A C
$u, ur"   