
    0Ph                     D   d dl Z d dlmZ d dlmZmZ d dlmZ d dlZd dl	m
Z
 ddlmZmZ ddl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 ddlmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.  edg d          Z/d Z0 G d de-          Z1dS )    N)
namedtuple)IntegralReal)time)stats   )_fit_contextclone)ConvergenceWarning)	normalize)_safe_indexingcheck_arraycheck_random_state)_safe_assign)	_get_mask)is_scalar_nan)
HasMethodsInterval
StrOptions)MetadataRouterMethodMapping_raise_for_paramsprocess_routing)FLOAT_DTYPES_check_feature_names_in_num_samplescheck_is_fittedvalidate_data   )SimpleImputer_BaseImputer_check_inputs_dtype_ImputerTriplet)feat_idxneighbor_feat_idx	estimatorc                 p    t          | d          r|                     ||d           dS ||         | |<   dS )a>  Assign X2 to X1 where cond is True.

    Parameters
    ----------
    X1 : ndarray or dataframe of shape (n_samples, n_features)
        Data.

    X2 : ndarray of shape (n_samples, n_features)
        Data to be assigned.

    cond : ndarray of shape (n_samples, n_features)
        Boolean mask to assign data.
    maskT)condotherinplaceN)hasattrr(   )X1X2r)   s      Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/impute/_iterative.py_assign_wherer0   (   sE     r6 
TT22222d84    c                       e Zd ZU dZi ej        d eddg          gdg eeddd          g ee	ddd          gd eed	dd          g e
h d
          gd e
h d          gdgd ee	ddd          dgd ee	ddd          dgdgdgdZeed<   	 d(ej        ddddddddej         ej        ddddd fdZ	 	 	 d)dZd Zd Zd*dZd+d Zed!             Z ed"          d( fd#	            Z fd$Zd(d%Zd(d&Zd' Z x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`.

    fill_value : str or numerical value, default=None
        When `strategy="constant"`, `fill_value` is used to replace all
        occurrences of missing_values. For string or object data types,
        `fill_value` must be a string.
        If `None`, `fill_value` will be 0 when imputing numerical
        data and "missing_value" for strings or object data types.

        .. versionadded:: 1.3

    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.

    keep_empty_features : bool, default=False
        If True, features that consist exclusively of missing values when
        `fit` is called are returned in results when `transform` is called.
        The imputed value is always `0` except when
        `initial_strategy="constant"` in which case `fill_value` will be
        used instead.

        .. versionadded:: 1.2

    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 imputer for completing missing values
        with simple strategies.
    KNNImputer : Multivariate imputer that estimates missing features using
        nearest samples.

    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`.

    Using defaults, the imputer scales in :math:`\mathcal{O}(knp^3\min(n,p))`
    where :math:`k` = `max_iter`, :math:`n` the number of samples and
    :math:`p` the number of features. It thus becomes prohibitively costly when
    the number of features increases. Setting
    `n_nearest_features << n_features`, `skip_complete=True` or increasing `tol`
    can help to reduce its computational cost.

    Depending on the nature of missing values, simple imputers can be
    preferable in a prediction context.

    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.        ]])

    For a more detailed example see
    :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py` or
    :ref:`sphx_glr_auto_examples_impute_plot_iterative_imputer_variants_comparison.py`.
    Nfitpredictbooleanr   left)closedr   >   meanmedianconstantmost_frequentno_validation>   romanarabicrandom	ascending
descendingbothz
array-likeverboserandom_state)r&   sample_posteriormax_itertoln_nearest_featuresinitial_strategy
fill_valueimputation_orderskip_complete	min_value	max_valuerD   rE   _parameter_constraintsF
   gMbP?r9   rA   )missing_valuesrF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rD   rE   add_indicatorkeep_empty_featuresc                   t                                          |||           || _        || _        || _        || _        || _        || _        || _        |	| _	        |
| _
        || _        || _        || _        || _        d S )N)rR   rS   rT   )super__init__r&   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rD   rE   )selfr&   rR   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rD   rE   rS   rT   	__class__s                    r/   rW   zIterativeImputer.__init__:  s    ( 	)' 3 	 	
 	
 	
 # 0 "4 0$ 0*""(r1   Tc                 f   ||du rt          d          |t          | j                  }|dd|f         }|rUt          t          ||d          | d          }	t          t          ||d          | d          }
 |j        |	|
fi | t          j        |          dk    r||fS t          t          ||d          |d          }| j        r|                    |d          \  }}t          j	        |j
        |j        	          }|dk    }||          || <   || j        |         k     }| j        |         ||<   || j        |         k    }| j        |         ||<   || z  | z  }||         }||         }| j        |         |z
  |z  }| j        |         |z
  |z  }t          j        ||||
          }|                    | j                  ||<   nA|                    |          }t          j        || j        |         | j        |                   }t'          ||||           ||fS )a  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.

        params : dict
            Additional params routed to the individual estimator.

        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   axisr   T)
return_std)dtype)ablocscale)rE   )row_indexercolumn_indexer)
ValueErrorr
   
_estimatorr   r4   npsumrF   r5   zerosshaper^   
_min_value
_max_valuer   	truncnormrvsrandom_state_clipr   )rX   X_filledmask_missing_valuesr$   r%   r&   fit_modeparamsmissing_row_maskX_trainy_trainX_testmussigmasimputed_valuespositive_sigmasmus_too_lowmus_too_highinrange_maskr_   r`   truncated_normals                         r/   _impute_one_featurez$IterativeImputer._impute_one_featureb  s   h U!2!21  
 do..I.qqq({; 	6$x):CCC!!  G
 %x:::!!  G
 IM'755f555 6"##q((Y&&  8%6Q???
 
 

   	#++Ft+DDKCXcix~FFFN %qjO/2O3C/DNO+, 99K*./(*CN;'!::L+/?8+DN<(*k\9\MILl#CL)F*S0F:A*S0F:A$aSOOO+;+?+?!/ ,@ , ,N<(( '..v66NW 94?8;T N
 	(#		
 	
 	
 	
 ""r1   c                 2   | j         M| j         |k     rB|dd|f         }| j                            t          j        |          | j         d|          }nBt          j        |          }t          j        |dz   |          }t          j        ||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   )rI   ro   choicerg   arangeconcatenate)rX   
n_featuresr$   abs_corr_matr   r%   	inds_left
inds_rights           r/   _get_neighbor_feat_idxz'IterativeImputer._get_neighbor_feat_idx  s    2 ".43JZ3W3WQQQ[)A $ 2 9 9	*%%t'>QR !: ! ! 	(++I8a<<<J "	:/F G G  r1   c                    |                     d          }| j        rt          j        |          }n,t          j        t          j        |          d                   }| j        dk    r|}n| j        dk    r|ddd         }n| j        dk    r>t          |          t          |          z
  }t          j        |d	          |d         }ny| j        d
k    rGt          |          t          |          z
  }t          j        |d	          |d         ddd         }n'| j        dk    r|}| j	        
                    |           |S )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   r[   r>   r?   NrA   	mergesort)kindrB   r@   )r9   rM   rg   flatnonzeror   rj   rL   lenargsortro   shuffle)rX   rr   frac_of_missing_valuesmissing_values_idxordered_idxns         r/   _get_ordered_idxz!IterativeImputer._get_ordered_idx  sc   ( "5!9!9q!9!A!A 	P!#0F!G!G!#284J+K+KA+N!O!O G++,KK"h..,TTrT2KK"k11*++c2D.E.EEA*%;+NNNqrrRKK"l22*++c2D.E.EEA*%;+NNNqrrRSWSWUWSWXKK"h..,K&&{333r1   ư>c                    |j         d         }| j        | j        |k    rdS t          j        d          5  t          j        t          j        |j                            }ddd           n# 1 swxY w Y   ||t          j        |          <   t          j        ||d|           t          j	        |d           t          |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)rj   rI   rg   errstateabscorrcoefTisnanrp   fill_diagonalr   )rX   rq   	tolerancer   r   s        r/   _get_abs_corr_matz"IterativeImputer._get_abs_corr_mat)  s   ( ^A&
"*d.E.S.S4[*** 	; 	; 6"+hj"9"9::L		; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 09RXl++,
i<@@@@
q))) DquMMMs   ,A//A36A3c                    t          | j                  rd}nd}t          | |t          d||          }t	          || j                   t          || j                  }|                                }| j        dk    o| j         }| j	        t          | j        | j        | j        | j                                      d	          | _	        |r`t          j                    5  t          j        d
t                      | j	                            |          }ddd           n# 1 swxY w Y   n| j	                            |          }n||r`t          j                    5  t          j        d
t                      | j	                            |          }ddd           n# 1 swxY w Y   n| j	                            |          }|rt'          j        |d          | _        | j        sZ|dd| j         f         }|dd| j         f         }| j	                                        d         dk    r|dd| j         f         }n-d|dd| j        f<   |}|dd| j        f         |dd| j        f<   ||||fS )a  Perform initial imputation for input `X`.

        Parameters
        ----------
        X : ndarray of 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 of 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 of shape (n_samples, n_features)
            Input data with the most recent imputations.

        mask_missing_values : ndarray of 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,
            masked by non-missing 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)r^   orderresetensure_all_finiter;   N)rR   strategyrK   rT   default)	transformr   r   r[   r   F)r   rR   r   r   r"   r   r   rJ   rT   initial_imputer_r    rK   
set_outputwarningscatch_warningssimplefilterFutureWarningfit_transformr   rg   all_is_empty_feature
get_params)	rX   Xin_fitr   X_missing_maskrr   catch_warningrq   Xts	            r/   _initial_imputationz$IterativeImputer._initial_imputationO  se   > ,-- 	% + $/
 
 
 	At2333"1d&9::,1133
 !Z/P8P4P 	  ($1#2.?$($<	% % %
 j9j-- !  B,.. F F)(MBBB#4BB1EEHF F F F F F F F F F F F F F F  0>>qAA  >,.. B B)(MBBB#4>>qAAHB B B B B B B B B B B B B B B  0::1== 	I%'V,?a%H%H%HD"' 	P111t---.B"5aaa$:P9P6P"Q$//11*=KK $AAA(>'>$>?
 >C4#9 9:B,4QQQ8N5N,OBqqq$(()80.@@s$   !5D""D&)D&5FF#&F#c           
         t          |          }| Mt          j        |           s9t          |           |k    r&t          d| d| dt	          |            d          |dk    rt          j        nt          j         }| |n| } t          j        |           rt          j        ||           } t          | ddd          } |s)t	          |           t	          |          k    r	| |          } | 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.
        is_empty_feature: ndarray, shape (n_features, )
            Mask array indicating empty feature imputer has seen during fit.
        keep_empty_feature: bool
            If False, remove empty-feature indices from the limit.

        Returns
        -------
        limit: ndarray, shape(n_features,)
            Array of limits, one for each feature.
        N'z_value' should be of shape (z',) when an array-like is provided. Got z
, instead.maxF)r   r   	ensure_2d)r   rg   isscalarre   r   inffullr   )limit
limit_typer   is_empty_featurekeep_empty_featuren_features_inlimit_bounds          r/   _validate_limitz IterativeImputer._validate_limit  s$   4 %%566K&& U##}44GJ G GM G G03E

G G G  
 !+e 3 3bff"&$}%;u 	/GJ..EEURWXXX " 	-c%jjC8H4I4I&I&I++,Er1   )prefer_skip_nested_validationc                 	   t          || d           t          | dfi |}t          | dt          | j                            | _        | j        ddlm}  |            | _	        nt          | j                  | _	        g | _        d| _        |                     |d          \  }}}}t                                          |           t                                          |          }	| j        dk    st%          j        |          r)d| _        t                                          ||	          S |j        d	         d	k    r)d| _        t                                          ||	          S |                     | j        d
|j        d	         | j        | j                  | _        |                     | j        d|j        d	         | j        | j                  | _        t%          j        t%          j        | j        | j                            st?          d          |                      |          }
tC          |
          | _"        | #                    |          }|j        \  }}| j$        dk    rtK          d|j                   tM                      }| j'        sI|(                                }| j)        t%          j*        t%          j+        ||                              z  }tY          d	| j        d	z             D ]k| _        | j-        dk    r|                      |          }
|
D ]m}| .                    |||          }| /                    ||||dd|j        j0                  \  }}tc          |||          }| j        2                    |           n| j$        d	k    r.tK          d| j        | j        tM                      |z
  fz             | j'        st$          j3        4                    ||z
  t$          j5        d          }| j$        dk    r#tK          d6                    ||                     ||k     r| j$        dk    rtK          d            n7|(                                }m| j'        sto          j8        dtr                     tu          |||            t                                          ||	          S )ag  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.

        **params : dict
            Parameters routed to the `fit` method of the sub-estimator via the
            metadata routing API.

            .. versionadded:: 1.5
              Only available if
              `sklearn.set_config(enable_metadata_routing=True)` is set. See
              :ref:`Metadata Routing User Guide <metadata_routing>` for more
              details.

        Returns
        -------
        Xt : array-like, shape (n_samples, n_features)
            The imputed input data.
        r4   ro   Nr   )BayesianRidgeTr   r   r   minr   z3One (or more) features have min_value >= max_value.0[IterativeImputer] Completing matrix with shape r@   )r&   rs   rt   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.r)   );r   r   getattrr   rE   ro   r&   linear_modelr   rf   r
   imputation_sequence_r   r   rV   _fit_indicator_transform_indicatorrG   rg   r   n_iter__concatenate_indicatorrj   r   rN   r   rT   rk   rO   rl   greaterre   r   r   n_features_with_missing_r   rD   printr   rF   r   rH   r   r   rangerL   r   r   r4   r#   appendlinalgr   r   formatr   warnr   r0   )rX   r   yrt   routed_paramsr   r   rr   complete_maskX_indicatorr   r   	n_samplesr   start_tXt_previousnormalized_tolr$   r%   r&   estimator_tripletinf_normrY   s                         r/   r   zIterativeImputer.fit_transform  s   > 	&$...'
 
 
 
 %/#5d6G#H#H
 
 >!444444+mooDOO#DN33DO$&! $484L4Ld 5M 5
 5
12"M 	}---gg22=AA=A(;!<!<DL7711"kBBB 8A;!DL7711"kBBB..NGAJ"$
 
 ..NGAJ"$
 
 vbj$/BBCC 	TRSSS ++,?@@(+K(8(8%--b11 "	:<!E!''STTT&&$ 	P''))K!Xrva9L8L6M/N/N(O(OON!!T]Q%677 /	 /	DL$00"334GHH' D D$($?$?,% %! !% 8 8'%"!(26 !9 ! !I %4/% %! )001BCCCC|a0|T]DFFW4DEF   ( (9>>"{*:T>RR<!##NUU$n   
 n,,|a''TUUUE ggii( N&   	b!#6"67777ww--b+>>>r1   c           	      :   t          |            |                     |d          \  }}}}t                                          |          }| j        dk    st          j        |          r"t                                          ||          S t          | j	                  | j        z  }d}| j
        dk    rt          d|j                   t                      }t          | j	                  D ]v\  }	}
|                     |||
j        |
j        |
j        d          \  }}|	dz   |z  s<| j
        dk    r,t          d|dz   | j        t                      |z
  fz             |dz  }wt'          |||            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.
        Fr   r   r   )r&   rs   r   r   r   )r   r   rV   r   r   rg   r   r   r   r   rD   r   rj   r   	enumerater   r$   r%   r&   r0   )rX   r   r   rr   r   r   imputations_per_roundi_rndr   itr   _rY   s               r/   r   zIterativeImputer.transform  s     	484L4Le 5M 5
 5
12"M gg22=AA<1': ; ;7711"kBBB #D$= > >$, N<!E!''STTT&&%.t/H%I%I 	 	!B!,,#!*!3+5 -  EB F33 <!##4 19dlDFFW4DEF  
 
b!#6"67777ww--b+>>>r1   c                 "     | j         |fi | | S )a5  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.

        **fit_params : dict
            Parameters routed to the `fit` method of the sub-estimator via the
            metadata routing API.

            .. versionadded:: 1.5
              Only available if
              `sklearn.set_config(enable_metadata_routing=True)` is set. See
              :ref:`Metadata Routing User Guide <metadata_routing>` for more
              details.

        Returns
        -------
        self : object
            Fitted estimator.
        )r   )rX   r   r   
fit_paramss       r/   r4   zIterativeImputer.fit  s$    6 	1++
+++r1   c                     t          | d           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.
        n_features_in_)r   r   r   get_feature_names_out(_concatenate_indicator_feature_names_out)rX   input_featuresnamess      r/   r   z&IterativeImputer.get_feature_names_out  sP    ( 	.///0~FF%;;NKK<<UNSSSr1   c                     t          | j        j                                      | j        t                                          dd                    }|S )aj  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.5

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        )ownerr4   )calleecaller)r&   method_mapping)r   rY   __name__addr&   r   )rX   routers     r/   get_metadata_routingz%IterativeImputer.get_metadata_routing  sU      dn&=>>>BBn(??..eE.JJ C 
 
 r1   )N)NTN)r   )F)r  
__module____qualname____doc__r!   rP   r   r   r   r   r   dict__annotations__rg   nanr   rW   r   r   r   r   r   staticmethodr   r	   r   r   r4   r   r  __classcell__)rY   s   @r/   r3   r3   <   s        f fP$

-$JJy'9::;&KXh4???@q$v6667#XXh4%O%O%OPJFFFGG
 &JOOOPP
 $HHT4fEEE|THHT4fEEE|T;'(%$ $ $D   . &) v$6'&!%&) &) &) &) &) &) &)\ y# y# y# y#v"! "! "!H& & &P$ $ $ $LiA iA iA iAV . . \.` \&+  V? V? V? V? V?	 V?p4? 4? 4? 4? 4?l   <T T T T2      r1   r3   )2r   collectionsr   numbersr   r   r   numpyrg   scipyr   baser	   r
   
exceptionsr   preprocessingr   utilsr   r   r   utils._indexingr   utils._maskr   utils._missingr   utils._param_validationr   r   r   utils.metadata_routingr   r   r   r   utils.validationr   r   r   r   r   _baser    r!   r"   r#   r0   r3    r1   r/   <module>r!     s%    " " " " " " " " " " " " " "                 & & & & & & & & + + + + + + % % % % % % C C C C C C C C C C * * * * * * # # # # # # * * * * * * F F F F F F F F F F                         D C C C C C C C C C*EEE 
  (J J J J J| J J J J Jr1   