Ë
    5¾ªjö  ã                   óÌ   — d Z ddlmZmZ ddl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 ddlmZ d	Zd
eeej(                  f   deeej(                  f   fd„Z G d„ dee	«      Zy)z�Outlier/anomaly detection utilities for MySQL Connector/Python.

Provides a scikit-learn compatible wrapper using HeatWave to score anomalies.
é    )ÚOptionalÚUnionN)ÚOutlierMixin)ÚMyBaseMLModel)ÚML_TASK)Ú	copy_dict)ÚMySQLConnectionAbstractgñhãˆµøä>ÚprobÚreturnc                 ó|   — t        j                  | t        dt        z
  «      }t        j                  |d|z
  z  «      S )zÚ
    Compute logit (logodds) for a probability, clipping to avoid numerical overflow.

    Args:
        prob: Scalar or array of probability values in (0,1).

    Returns:
        logit-transformed probabilities.
    é   )ÚnpÚclipÚEPSÚlog)r
   Úresults     úR/var/www/html/serviGia/entorno/lib/python3.12/site-packages/mysql/ai/ml/outlier.pyÚ_get_logitsr   0   s2   € ô �W‰W�Tœ3 ¤C¡Ó(€FÜ�6‰6�&˜A ™JÑ'Ó(Ð(ó    c            
       óD  — e Zd ZdZ	 	 	 ddedee   dee   dee   fd„Zde	e
j                  ej                  f   d	ej                  fd
„Zde	e
j                  ej                  f   d	ej                  fd„Zde	e
j                  ej                  f   d	ej                  fd„Zy)ÚMyAnomalyDetectora¯  
    MySQL HeatWave scikit-learn compatible anomaly/outlier detector.

    Flags samples as outliers when the probability of being an anomaly
    exceeds a user-tunable threshold.
    Includes helpers to obtain decision scores and anomaly probabilities
    for ranking.

    Args:
        db_connection (MySQLConnectionAbstract): Active MySQL DB connection.
        model_name (str, optional): Custom model name in the database.
        fit_extra_options (dict, optional): Extra options for fitting.
        score_extra_options (dict, optional): Extra options for scoring/prediction.

    Attributes:
        boundary: Decision threshold boundary in logit space. Derived from
            trained model's catalog info

    Methods:
        predict(X): Predict outlier/inlier labels.
        score_samples(X): Compute anomaly (normal class) logit scores.
        decision_function(X): Compute signed score above/below threshold for ranking.
    NÚdb_connectionÚ
model_nameÚfit_extra_optionsÚscore_extra_optionsc                 ó‚   — t        j                  | |t        j                  ||¬«       t	        |«      | _        d| _        y)a2  
        Initialize an anomaly detector instance with threshold and extra options.

        Args:
            db_connection: Active MySQL DB connection.
            model_name: Optional model name in DB.
            fit_extra_options: Optional extra fit options.
            score_extra_options: Optional extra scoring options.

        Raises:
            ValueError: If outlier_threshold is not in (0,1).
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.
        )r   r   N)r   Ú__init__r   ÚANOMALY_DETECTIONr   r   Úboundary)Úselfr   r   r   r   s        r   r   zMyAnomalyDetector.__init__W   s>   € ô, 	×ÑØØÜ×%Ñ%Ø!Ø/õ	
ô $-Ð-@Ó#AˆÔ Ø)-ˆ�r   ÚXr   c                 óT   — t        j                  | j                  |«      dk  dd«      S )a€  
        Predict outlier/inlier binary labels for input samples.

        Args:
            X: Samples to predict on.

        Returns:
            ndarray: Values are -1 for outliers, +1 for inliers, as per scikit-learn convention.

        Raises:
            DatabaseError:
                If provided options are invalid or unsupported,
                or if the model is not initialized, i.e., fit or import has not
                been called
                If a database connection issue occurs.
                If an operational error occurs during execution.
            DatabaseError:
                If provided options are invalid or unsupported,
                or if the model is not initialized, i.e., fit or import has not
                been called
                If a database connection issue occurs.
                If an operational error occurs during execution.
        g        éÿÿÿÿr   )r   ÚwhereÚdecision_function)r    r!   s     r   ÚpredictzMyAnomalyDetector.predictw   s'   € ô6 �x‰x˜×.Ñ.¨qÓ1°CÑ7¸¸QÓ?Ð?r   c                 ó  — | j                  |«      }| j                  €U| j                  «       }|€t        d«      ‚|d   d   j	                  dd«      }|€t        d«      ‚t        d|z
  «      | _        || j                  z
  S )aŽ  
        Compute signed distance to the outlier threshold.

        Args:
            X: Samples to predict on.

        Returns:
            ndarray: Score > 0 means inlier, < 0 means outlier; |value| gives margin.

        Raises:
            DatabaseError:
                If provided options are invalid or unsupported,
                or if the model is not initialized, i.e., fit or import has not
                been called
                If a database connection issue occurs.
                If an operational error occurs during execution.
            ValueError:
                If the provided model info does not provide threshold
        Nz Model does not exist in catalog.Úmodel_metadataÚtraining_paramsÚanomaly_detection_thresholdzzTrained model is outdated and does not support threshold. Try retraining or using an existing, trained model with MyModel.g      ð?)Úscore_samplesr   Úget_model_infoÚ
ValueErrorÚgetr   )r    r!   Úsample_scoresÚ
model_infoÚ	thresholds        r   r%   z#MyAnomalyDetector.decision_function”   s›   € ð. ×*Ñ*¨1Ó-ˆà�=‰=Ð Ø×,Ñ,Ó.ˆJØÐ!Ü Ð!CÓDÐDà"Ð#3Ñ4Ð5FÑG×KÑKØ-¨tóˆIð Ð Ü ðWóð ô (¨¨i©Ó8ˆDŒMà˜tŸ}™}Ñ,Ð,r   c                 ó¨   — | j                   j                  || j                  ¬«      }t        |d   j	                  d„ «      j                  «       «      S )aJ  
        Compute normal probability logit score for each sample.
        Used for ranking, thresholding.

        Args:
            X: Samples to score.

        Returns:
            ndarray: Logit scores based on "normal" class probability.

        Raises:
            DatabaseError:
                If provided options are invalid or unsupported,
                or if the model is not initialized, i.e., fit or import has not
                been called
                If a database connection issue occurs.
                If an operational error occurs during execution.
        )ÚoptionsÚ
ml_resultsc                 ó   — | d   d   S )NÚprobabilitiesÚnormal© )Úxs    r   ú<lambda>z1MyAnomalyDetector.score_samples.<locals>.<lambda>Û   s   € ˜Q˜Ñ/°Ñ9€ r   )Ú_modelr&   r   r   ÚapplyÚto_numpy)r    r!   r   s      r   r+   zMyAnomalyDetector.score_samplesÁ   sJ   € ð, —‘×$Ñ$ Q°×0HÑ0HÐ$ÓIˆäØ�<Ñ ß‰UÑ9Ó:ß‰X‹Zó
ð 	
r   )NNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r	   r   ÚstrÚdictr   r   ÚpdÚ	DataFramer   Úndarrayr&   r%   r+   r8   r   r   r   r   >   sÕ   „ ñð6 %)Ø,0Ø.2ñ.à.ð.ð ˜S‘Mð.ð $ D™>ð	.ð
 & d™^ó.ð@@à�—‘˜rŸz™zÐ)Ñ*ð@ð 
�‰ó@ð:+-à�—‘˜rŸz™zÐ)Ñ*ð+-ð 
�‰ó+-ðZ
à�—‘˜rŸz™zÐ)Ñ*ð
ð 
�‰ô
r   r   )rA   Útypingr   r   Únumpyr   ÚpandasrD   Úsklearn.baser   Úmysql.ai.ml.baser   Úmysql.ai.ml.modelr   Úmysql.ai.utilsr   Úmysql.connector.abstractsr	   r   ÚfloatrF   r   r   r8   r   r   ú<module>rP      sh   ðñ:÷ #ã Û Ý %å *Ý %Ý $å =à
€ð)�e˜E 2§:¡:Ð-Ñ.ð )°5¸ÀÇ
Á
Ð9JÑ3Kó )ô_
˜ |õ _
r   