o
    tBhp|                     @   s   d dl m Z  d dlmZ d dlZd dl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mZmZ dd
lmZm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 edg dZG dd deZdS )    )time)
namedtupleN)stats   )clone)ConvergenceWarning)	normalize)check_arraycheck_random_state_safe_indexingis_scalar_nan)FLOAT_DTYPEScheck_is_fitted)_check_feature_names_in)	_get_mask   )_BaseImputer)SimpleImputer)_check_inputs_dtype_ImputerTriplet)feat_idxneighbor_feat_idx	estimatorc                       s   e Zd ZdZ	d"ejdddddddej ejdddd	 fd
dZ		d#ddZdd Z	dd Z
d$ddZd%ddZedd Zd" fdd	Z fddZd"ddZd"d d!Z  ZS )&IterativeImputera."  Multivariate imputer that estimates each feature from all the others.

    A strategy for imputing missing values by modeling each feature with
    missing values as a function of other features in a round-robin fashion.

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

    .. versionadded:: 0.21

    .. note::

      This estimator is still **experimental** for now: the predictions
      and the API might change without any deprecation cycle. To use it,
      you need to explicitly import `enable_iterative_imputer`::

        >>> # explicitly require this experimental feature
        >>> from sklearn.experimental import enable_iterative_imputer  # noqa
        >>> # now you can import normally from sklearn.impute
        >>> from sklearn.impute import IterativeImputer

    Parameters
    ----------
    estimator : estimator object, default=BayesianRidge()
        The estimator to use at each step of the round-robin imputation.
        If `sample_posterior=True`, the estimator must support
        `return_std` in its `predict` method.

    missing_values : int or np.nan, default=np.nan
        The placeholder for the missing values. All occurrences of
        `missing_values` will be imputed. For pandas' dataframes with
        nullable integer dtypes with missing values, `missing_values`
        should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.

    sample_posterior : bool, default=False
        Whether to sample from the (Gaussian) predictive posterior of the
        fitted estimator for each imputation. Estimator must support
        `return_std` in its `predict` method if set to `True`. Set to
        `True` if using `IterativeImputer` for multiple imputations.

    max_iter : int, default=10
        Maximum number of imputation rounds to perform before returning the
        imputations computed during the final round. A round is a single
        imputation of each feature with missing values. The stopping criterion
        is met once `max(abs(X_t - X_{t-1}))/max(abs(X[known_vals])) < tol`,
        where `X_t` is `X` at iteration `t`. Note that early stopping is only
        applied if `sample_posterior=False`.

    tol : float, default=1e-3
        Tolerance of the stopping condition.

    n_nearest_features : int, default=None
        Number of other features to use to estimate the missing values of
        each feature column. Nearness between features is measured using
        the absolute correlation coefficient between each feature pair (after
        initial imputation). To ensure coverage of features throughout the
        imputation process, the neighbor features are not necessarily nearest,
        but are drawn with probability proportional to correlation for each
        imputed target feature. Can provide significant speed-up when the
        number of features is huge. If `None`, all features will be used.

    initial_strategy : {'mean', 'median', 'most_frequent', 'constant'},             default='mean'
        Which strategy to use to initialize the missing values. Same as the
        `strategy` parameter in :class:`~sklearn.impute.SimpleImputer`.

    imputation_order : {'ascending', 'descending', 'roman', 'arabic',             'random'}, default='ascending'
        The order in which the features will be imputed. Possible values:

        - `'ascending'`: From features with fewest missing values to most.
        - `'descending'`: From features with most missing values to fewest.
        - `'roman'`: Left to right.
        - `'arabic'`: Right to left.
        - `'random'`: A random order for each round.

    skip_complete : bool, default=False
        If `True` then features with missing values during :meth:`transform`
        which did not have any missing values during :meth:`fit` will be
        imputed with the initial imputation method only. Set to `True` if you
        have many features with no missing values at both :meth:`fit` and
        :meth:`transform` time to save compute.

    min_value : float or array-like of shape (n_features,), default=-np.inf
        Minimum possible imputed value. Broadcast to shape `(n_features,)` if
        scalar. If array-like, expects shape `(n_features,)`, one min value for
        each feature. The default is `-np.inf`.

        .. versionchanged:: 0.23
           Added support for array-like.

    max_value : float or array-like of shape (n_features,), default=np.inf
        Maximum possible imputed value. Broadcast to shape `(n_features,)` if
        scalar. If array-like, expects shape `(n_features,)`, one max value for
        each feature. The default is `np.inf`.

        .. versionchanged:: 0.23
           Added support for array-like.

    verbose : int, default=0
        Verbosity flag, controls the debug messages that are issued
        as functions are evaluated. The higher, the more verbose. Can be 0, 1,
        or 2.

    random_state : int, RandomState instance or None, default=None
        The seed of the pseudo random number generator to use. Randomizes
        selection of estimator features if `n_nearest_features` is not `None`,
        the `imputation_order` if `random`, and the sampling from posterior if
        `sample_posterior=True`. Use an integer for determinism.
        See :term:`the Glossary <random_state>`.

    add_indicator : bool, default=False
        If `True`, a :class:`MissingIndicator` transform will stack onto output
        of the imputer's transform. This allows a predictive estimator
        to account for missingness despite imputation. If a feature has no
        missing values at fit/train time, the feature won't appear on
        the missing indicator even if there are missing values at
        transform/test time.

    Attributes
    ----------
    initial_imputer_ : object of type :class:`~sklearn.impute.SimpleImputer`
        Imputer used to initialize the missing values.

    imputation_sequence_ : list of tuples
        Each tuple has `(feat_idx, neighbor_feat_idx, estimator)`, where
        `feat_idx` is the current feature to be imputed,
        `neighbor_feat_idx` is the array of other features used to impute the
        current feature, and `estimator` is the trained estimator used for
        the imputation. Length is `self.n_features_with_missing_ *
        self.n_iter_`.

    n_iter_ : int
        Number of iteration rounds that occurred. Will be less than
        `self.max_iter` if early stopping criterion was reached.

    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_features_with_missing_ : int
        Number of features with missing values.

    indicator_ : :class:`~sklearn.impute.MissingIndicator`
        Indicator used to add binary indicators for missing values.
        `None` if `add_indicator=False`.

    random_state_ : RandomState instance
        RandomState instance that is generated either from a seed, the random
        number generator or by `np.random`.

    See Also
    --------
    SimpleImputer : Univariate imputation of missing values.

    Notes
    -----
    To support imputation in inductive mode we store each feature's estimator
    during the :meth:`fit` phase, and predict without refitting (in order)
    during the :meth:`transform` phase.

    Features which contain all missing values at :meth:`fit` are discarded upon
    :meth:`transform`.

    References
    ----------
    .. [1] `Stef van Buuren, Karin Groothuis-Oudshoorn (2011). "mice:
        Multivariate Imputation by Chained Equations in R". Journal of
        Statistical Software 45: 1-67.
        <https://www.jstatsoft.org/article/view/v045i03>`_

    .. [2] `S. F. Buck, (1960). "A Method of Estimation of Missing Values in
        Multivariate Data Suitable for use with an Electronic Computer".
        Journal of the Royal Statistical Society 22(2): 302-306.
        <https://www.jstor.org/stable/2984099>`_

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.experimental import enable_iterative_imputer
    >>> from sklearn.impute import IterativeImputer
    >>> imp_mean = IterativeImputer(random_state=0)
    >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])
    IterativeImputer(random_state=0)
    >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]
    >>> imp_mean.transform(X)
    array([[ 6.9584...,  2.       ,  3.        ],
           [ 4.       ,  2.6000...,  6.        ],
           [10.       ,  4.9999...,  9.        ]])
    NF
   gMbP?mean	ascendingr   )missing_valuessample_posteriormax_itertoln_nearest_featuresinitial_strategyimputation_orderskip_complete	min_value	max_valueverboserandom_stateadd_indicatorc                   s\   t  j||d || _|| _|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _|| _d S )N)r   r)   )super__init__r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   )selfr   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   	__class__ p/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/sklearn/impute/_iterative.pyr+      s   
zIterativeImputer.__init__Tc                 C   s  |du r|du rt d|du rt| j}|dd|f }|r=t|dd|f | }t|dd|f | }	|||	 t|dkrH||fS t|dd|f |}
| jr|j|
dd\}}tj	|j
|jd}|dk}||  || < || j| k }| j| ||< || j| k}| j| ||< || @ | @ }|| }|| }| j| | | }| j| | | }tj||||d}|j| jd	||< n||
}t|| j| | j| }||||f< ||fS )
at  Impute a single feature from the others provided.

        This function predicts the missing values of one of the features using
        the current estimates of all the other features. The `estimator` must
        support `return_std=True` in its `predict` method for this function
        to work.

        Parameters
        ----------
        X_filled : ndarray
            Input data with the most recent imputations.

        mask_missing_values : ndarray
            Input data's missing indicator matrix.

        feat_idx : int
            Index of the feature currently being imputed.

        neighbor_feat_idx : ndarray
            Indices of the features to be used in imputing `feat_idx`.

        estimator : object
            The estimator to use at this step of the round-robin imputation.
            If `sample_posterior=True`, the estimator must support
            `return_std` in its `predict` method.
            If None, it will be cloned from self._estimator.

        fit_mode : boolean, default=True
            Whether to fit and predict with the estimator or just predict.

        Returns
        -------
        X_filled : ndarray
            Input data with `X_filled[missing_row_mask, feat_idx]` updated.

        estimator : estimator with sklearn API
            The fitted estimator used to impute
            `X_filled[missing_row_mask, feat_idx]`.
        NFzKIf fit_mode is False, then an already-fitted estimator should be passed in.r   T)
return_std)dtype)ablocscale)r(   )
ValueErrorr   
_estimatorr   fitnpsumr   predictzerosshaper2   
_min_value
_max_valuer   	truncnormrvsrandom_state_clip)r,   X_filledmask_missing_valuesr   r   r   fit_modemissing_row_maskX_trainy_trainX_testmussigmasimputed_valuespositive_sigmasmus_too_lowmus_too_highinrange_maskr3   r4   truncated_normalr/   r/   r0   _impute_one_feature  sL   0

z$IterativeImputer._impute_one_featurec                 C   sp   | j dur"| j |k r"|dd|f }| jjt|| j d|d}|S t|}t|d |}t||f}|S )az  Get a list of other features to predict `feat_idx`.

        If `self.n_nearest_features` is less than or equal to the total
        number of features, then use a probability proportional to the absolute
        correlation between `feat_idx` and each other feature to randomly
        choose a subsample of the other features (without replacement).

        Parameters
        ----------
        n_features : int
            Number of features in `X`.

        feat_idx : int
            Index of the feature currently being imputed.

        abs_corr_mat : ndarray, shape (n_features, n_features)
            Absolute correlation matrix of `X`. The diagonal has been zeroed
            out and each feature has been normalized to sum to 1. Can be None.

        Returns
        -------
        neighbor_feat_idx : array-like
            The features to use to impute `feat_idx`.
        NF)replacepr   )r!   rC   choicer:   arangeconcatenate)r,   
n_featuresr   abs_corr_matrV   r   	inds_left
inds_rightr/   r/   r0   _get_neighbor_feat_idxg  s   
z'IterativeImputer._get_neighbor_feat_idxc                 C   s   |j dd}| jrt|}n
tt|d }| jdkr"|}|S | jdkr0|ddd }|S | jdkrJt|t| }tj|dd	|d }|S | jd
krit|t| }tj|dd	|d ddd }|S | jdkrx|}| j	
| |S td| j)a  Decide in what order we will update the features.

        As a homage to the MICE R package, we will have 4 main options of
        how to order the updates, and use a random order if anything else
        is specified.

        Also, this function skips features which have no missing values.

        Parameters
        ----------
        mask_missing_values : array-like, shape (n_samples, n_features)
            Input data's missing indicator matrix, where `n_samples` is the
            number of samples and `n_features` is the number of features.

        Returns
        -------
        ordered_idx : ndarray, shape (n_features,)
            The order in which to impute the features.
        r   )axisromanarabicNr   	mergesort)kind
descendingrandomzGot an invalid imputation order: '{0}'. It must be one of the following: 'roman', 'arabic', 'ascending', 'descending', or 'random'.)r   r$   r:   flatnonzerorX   r>   r#   lenargsortrC   shuffler7   format)r,   rF   frac_of_missing_valuesmissing_values_idxordered_idxnr/   r/   r0   _get_ordered_idx  s4   



 
z!IterativeImputer._get_ordered_idxư>c                 C   s   |j d }| jdu s| j|krdS tjdd tt|j}W d   n1 s+w   Y  ||t|< tj||d|d t	|d t
|dddd	}|S )
a  Get absolute correlation matrix between features.

        Parameters
        ----------
        X_filled : ndarray, shape (n_samples, n_features)
            Input data with the most recent imputations.

        tolerance : float, default=1e-6
            `abs_corr_mat` can have nans, which will be replaced
            with `tolerance`.

        Returns
        -------
        abs_corr_mat : ndarray, shape (n_features, n_features)
            Absolute correlation matrix of `X` at the beginning of the
            current round. The diagonal has been zeroed out and each feature's
            absolute correlations with all others have been normalized to sum
            to 1.
        r   Nignore)invalid)outr   l1F)normr_   copy)r>   r!   r:   errstateabscorrcoefTisnanrD   fill_diagonalr   )r,   rE   	tolerancerZ   r[   r/   r/   r0   _get_abs_corr_mat  s   
z"IterativeImputer._get_abs_corr_matc           	      C   s   t | jrd}nd}| j|td||d}t|| j t|| j}| }| jdu r9t| j| j	d| _| j
|}n| j|}ttt| jj}|dd|f }|dd|f }||||fS )ax  Perform initial imputation for input `X`.

        Parameters
        ----------
        X : ndarray, shape (n_samples, n_features)
            Input data, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        in_fit : bool, default=False
            Whether function is called in :meth:`fit`.

        Returns
        -------
        Xt : ndarray, shape (n_samples, n_features)
            Input data, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        X_filled : ndarray, shape (n_samples, n_features)
            Input data with the most recent imputations.

        mask_missing_values : ndarray, shape (n_samples, n_features)
            Input data's missing indicator matrix, where `n_samples` is the
            number of samples and `n_features` is the number of features.

        X_missing_mask : ndarray, shape (n_samples, n_features)
            Input data's mask matrix indicating missing datapoints, where
            `n_samples` is the number of samples and `n_features` is the
            number of features.
        z	allow-nanTF)r2   orderresetforce_all_finiteN)r   strategy)r   r   _validate_datar   r   r   rw   initial_imputer_r   r"   fit_transform	transformr:   rg   logical_notr|   statistics_)	r,   Xin_fitr   X_missing_maskrF   rE   
valid_maskXtr/   r/   r0   _initial_imputation  s2   

z$IterativeImputer._initial_imputationc                 C   s|   |dkrt jnt j }| du r|n| } t | rt || } t| dddd} | jd |ks<td| d| d| j d	| S )
a)  Validate the limits (min/max) of the feature values.

        Converts scalar min/max limits to vectors of shape `(n_features,)`.

        Parameters
        ----------
        limit: scalar or array-like
            The user-specified limit (i.e, min_value or max_value).
        limit_type: {'max', 'min'}
            Type of limit to validate.
        n_features: int
            Number of features in the dataset.

        Returns
        -------
        limit: ndarray, shape(n_features,)
            Array of limits, one for each feature.
        maxNF)r   rw   	ensure_2dr   'z_value' should be of shape (z',) when an array-like is provided. Got z
, instead.)r:   infisscalarfullr	   r>   r7   )limit
limit_typerZ   limit_boundr/   r/   r0   _validate_limit  s   
z IterativeImputer._validate_limitc              
      s  t | dt| j| _| jdk rtd| j| jdk r$td| j| jdu r4ddl	m
} | | _nt| j| _g | _d| _| j|dd	\}}}}t | t |}| jdksat|rkd| _t ||S |jd
 d
kr|d| _t ||S | | jd|jd
 | _| | jd|jd
 | _tt| j| jstd| |}t|| _ | !|}	|j\}
}| j"dkrt#d|jf  t$ }| j%s|& }| jt't(||   }t)d
| jd
 D ]y| _| j*dkr| |}|D ]"}| +|||	}| j,||||ddd\}}t-|||}| j.| q| j"d
kr*t#d| j| jt$ | f  | j%s]tj/j0|| tj1dd}| j"dkrHt#d|| ||k rY| j"dkrWt#d  n|& }q| j%sht23dt4 ||  || < t ||S )a  Fit the imputer on `X` and return the transformed `X`.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Input data, where `n_samples` is the number of samples and
            `n_features` is the number of features.

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

        Returns
        -------
        Xt : array-like, shape (n_samples, n_features)
            The imputed input data.
        rC   r   z8'max_iter' should be a positive integer. Got {} instead.z5'tol' should be a non-negative float. Got {} instead.Nr   )BayesianRidgeT)r   r   minr   z3One (or more) features have min_value >= max_value.2[IterativeImputer] Completing matrix with shape %srf   r   rG   D[IterativeImputer] Ending imputation round %d/%d, elapsed time %0.2f)ordr_   z4[IterativeImputer] Change: {}, scaled tolerance: {} z4[IterativeImputer] Early stopping criterion reached.z8[IterativeImputer] Early stopping criterion not reached.)5getattrr
   r(   rC   r   r7   rk   r    r   linear_modelr   r8   r   imputation_sequence_r   r   r*   _fit_indicator_transform_indicatorr:   alln_iter__concatenate_indicatorr>   r   r%   r?   r&   r@   greaterrp   rh   n_features_with_missing_r   r'   printr   r   rw   r   ry   ranger#   r^   rT   r   appendlinalgrv   r   warningswarnr   )r,   r   yr   r   rF   complete_maskX_indicatorrn   r[   	n_samplesrZ   start_tXt_previousnormalized_tolr   r   r   estimator_tripletinf_normr-   r/   r0   r   ?  s   













zIterativeImputer.fit_transformc              	      s
  t |  | |\}}}}t |}| jdkst|r$t ||S t| j	| j }d}| j
dkr;td|jf  t }t| j	D ]2\}	}
| j|||
j|
j|
jdd\}}|	d | su| j
dkrqtd|d | jt | f  |d7 }qC||  || < t ||S )a  Impute all missing values in `X`.

        Note that this is stochastic, and that if `random_state` is not fixed,
        repeated calls, or permuted input, results will differ.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The input data to complete.

        Returns
        -------
        Xt : array-like, shape (n_samples, n_features)
             The imputed input data.
        r   r   Fr   r   r   )r   r   r*   r   r   r:   r   r   rh   r   r'   r   r>   r   	enumeraterT   r   r   r   )r,   r   r   rF   r   r   imputations_per_roundi_rndr   itr   _r-   r/   r0   r     s<   


zIterativeImputer.transformc                 C   s   |  | | S )a  Fit the imputer on `X` and return self.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Input data, where `n_samples` is the number of samples and
            `n_features` is the number of features.

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

        Returns
        -------
        self : object
            Fitted estimator.
        )r   )r,   r   r   r/   r/   r0   r9     s   
zIterativeImputer.fitc                 C   s"   t | |}| j|}| ||S )a  Get output feature names for transformation.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Input features.

            - If `input_features` is `None`, then `feature_names_in_` is
              used as feature names in. If `feature_names_in_` is not defined,
              then the following input feature names are generated:
              `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
            - If `input_features` is an array-like, then `input_features` must
              match `feature_names_in_` if `feature_names_in_` is defined.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Transformed feature names.
        )r   r   get_feature_names_out(_concatenate_indicator_feature_names_out)r,   input_featuresnamesr/   r/   r0   r     s   
z&IterativeImputer.get_feature_names_out)N)NT)rq   )F)__name__
__module____qualname____doc__r:   nanr   r+   rT   r^   rp   r   r   staticmethodr   r   r   r9   r   __classcell__r/   r/   r-   r0   r      sB     H'
f$
/
&>
  
4r   )r   collectionsr   r   scipyr   numpyr:   baser   
exceptionsr   preprocessingr   utilsr	   r
   r   r   utils.validationr   r   r   utils._maskr   _baser   r   r   r   r   r/   r/   r/   r0   <module>   s&    