
    -i                     6   S SK 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  SSKJ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  SSK J!r!J"r"J#r#J$r$  SSK%J&r&J'r'J(r(J)r)J*r*  SSK+J,r,J-r-J.r.  \" S/ SQ5      r/S r0 " S S\-5      r1g)    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                 T    [        U S5      (       a  U R                  X!SS9  gX   X'   g)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      L/var/www/html/venv/lib/python3.13/site-packages/sklearn/impute/_iterative.py_assign_wherer0   (   s*     r6
TT28    c                     ^  \ rS rSr% Sr0 \R                  ES\" SS/5      /S/\" \	SSSS	9/\" \
SSSS	9/S\" \	S
SSS	9/\" 1 Sk5      /S\" 1 Sk5      /S/S\" \
SSSS	9S/S\" \
SSSS	9S/S/S/S.Er\\S'    S(\R                  SSSSSSSS\R                   * \R                   SSSSS.U 4S jjjr   S)S jrS rS rS*S jrS+S jr\S  5       r\" SS!9S(U 4S" jj5       rU 4S# jrS(S$ jrS(S% jrS& rS'rU =r $ ),IterativeImputer<   a%  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_valuerE   rF   _parameter_constraintsF
   gMbP?r:   rB   )missing_valuesrG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rE   rF   add_indicatorkeep_empty_featuresc                   > [         TU ]  UUUS9  Xl        X0l        X@l        XPl        X`l        Xpl        Xl        Xl	        Xl
        Xl        Xl        Xl        Xl        g )N)rS   rT   rU   )super__init__r&   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rE   rF   )selfr&   rS   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rE   rF   rT   rU   	__class__s                    r/   rX   IterativeImputer.__init__:  si    ( 	)' 3 	 	
 # 0 "4 0$ 0*""(r1   c                    Uc  USL a  [        S5      eUc  [        U R                  5      nUSS2U4   nU(       a;  [        [        XSS9U) SS9n	[        [        XSS9U) SS9n
UR                  " X40 UD6  [
        R                  " U5      S:X  a  X4$ [        [        XSS9USS9nU R                  (       a  UR                  USS9u  p[
        R                  " UR                  UR                  S	9nUS:  nX)    X) '   XR                  U   :  nU R                  U   UU'   XR                  U   :  nU R                  U   UU'   UU) -  U) -  nUU   nUU   nU R                  U   U-
  U-  nU R                  U   U-
  U-  n[        R                  " UUXS
9nUR!                  U R"                  S9UU'   OBUR                  U5      n[
        R$                  " XR                  U   U R                  U   5      n['        UUUUS9  X4$ )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)rF   )row_indexercolumn_indexer)
ValueErrorr
   
_estimatorr   r5   npsumrG   r6   zerosshaper`   
_min_value
_max_valuer   	truncnormrvsrandom_state_clipr   )rY   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_maskra   rb   truncated_normals                         r/   _impute_one_feature$IterativeImputer._impute_one_featureb  sX   h U!21 
 doo.I.q({;$xC!!G
 %x:!!G
 MM'5f5 66"#q(&&  8Q?

   #++Ft+DKCXXciix~~FN %qjO/23C/DN+, 99K*.//(*CN;'!::L+/??8+DN<(*k\9\MILl#CL)F*S0F:A*S0F:A$aSO+;+?+?!// ,@ ,N<( '..v6NWW 94??8;TN
 	(#		
 ""r1   c                 X   U R                   bU  U R                   U:  aE  USS2U4   nU R                  R                  [        R                  " U5      U R                   SUS9nU$ [        R                  " U5      n[        R                  " US-   U5      n[        R
                  " Xg45      nU$ )a  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   )rJ   rq   choiceri   arangeconcatenate)rY   
n_featuresr$   abs_corr_matr   r%   	inds_left
inds_rights           r/   _get_neighbor_feat_idx'IterativeImputer._get_neighbor_feat_idx  s    2 "".43J3JZ3WQ[)A $ 2 2 9 9		*%t'>'>QR !: ! !  		(+I8a<<J "	/F G  r1   c                    UR                  SS9nU R                  (       a  [        R                  " U5      nO-[        R                  " [        R
                  " U5      S   5      nU R                  S:X  a  UnU$ U R                  S:X  a
  USSS2   nU$ U R                  S:X  a1  [        U5      [        U5      -
  n[        R                  " USS	9US nU$ U R                  S
:X  a7  [        U5      [        U5      -
  n[        R                  " USS	9US SSS2   nU$ U R                  S:X  a  UnU R                  R                  U5        W$ )aO  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@   NrB   	mergesort)kindrC   rA   )r:   rN   ri   flatnonzeror   rl   rM   lenargsortrq   shuffle)rY   rt   frac_of_missing_valuesmissing_values_idxordered_idxns         r/   _get_ordered_idx!IterativeImputer._get_ordered_idx  sW   ( "5!9!9q!9!A!#0F!G!#2884J+KA+N!O  G+,K  ""h.,TrT2K  ""k1*+c2D.EEA**%;+NqrRK  ""l2*+c2D.EEA**%;+NqrRSWUWSWXK  ""h.,K&&{3r1   c                    UR                   S   nU R                  b  U R                  U:  a  g[        R                  " SS9   [        R                  " [        R
                  " UR                  5      5      nSSS5        UW[        R                  " U5      '   [        R                  " XBSUS9  [        R                  " US5        [        USSSS	9nU$ ! , (       d  f       Nb= f)
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)rl   rJ   ri   errstateabscorrcoefTisnanrr   fill_diagonalr   )rY   rs   	tolerancer   r   s        r/   _get_abs_corr_mat"IterativeImputer._get_abs_corr_mat)  s    ( ^^A&
""*d.E.E.S[[* 66"++hjj"9:L	 + 09RXXl+,
<@
q) DquM +*s   5C
C!c           	         [        U R                  5      (       a  SnOSn[        U U[        SUUS9n[	        XR                  5        [        XR                  5      nUR                  5       nU R                  S:H  =(       a    U R                  (       + nU R                  c  [        U R                  U R                  U R                  U R                  S9R                  SS	9U l	        U(       aU  [        R                  " 5          [        R                  " S
[         5        U R                  R#                  U5      nSSS5        OU R                  R#                  U5      nOwU(       aU  [        R                  " 5          [        R                  " S
[         5        U R                  R%                  U5      nSSS5        OU R                  R%                  U5      nU(       a  [&        R(                  " USS9U l        U R                  (       d^  USS2U R*                  ) 4   nUSS2U R*                  ) 4   nU R                  R-                  5       S   S:X  a  WSS2U R*                  ) 4   nO9SUSS2U R*                  4'   UnWSS2U R*                  4   USS2U R*                  4'   UWXT4$ ! , (       d  f       N= f! , (       d  f       N= f)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)rS   strategyrL   rU   default)	transformr   r   r]   r   F)r   rS   r   r   r"   r   r   rK   rU   initial_imputer_r    rL   
set_outputwarningscatch_warningssimplefilterFutureWarningfit_transformr   ri   all_is_empty_feature
get_params)	rY   Xin_fitr   X_missing_maskrt   catch_warningrs   Xts	            r/   _initial_imputation$IterativeImputer._initial_imputationO  sw   > ,,-- + $/
 	A223"1&9&9:,113
 !!Z/P8P8P4P 	   ($1#22..??$($<$<	%
 j9j- ! ,,.))(MB#44BB1EH /.  00>>qA ,,.))(MB#44>>qAH /.  00::1=%'VV,?a%HD"''1t----.B"5a$:P:P9P6P"Q$$//1*=K $A(>(>'>$>?
 >C4#9#9 9:B,4Q8N8N5N,OBq$((()80@@O /. /.s   7J#:7J4#
J14
Kc           
         [        U5      nU bH  [        R                  " U 5      (       d-  [        U 5      U:w  a  [        SU SU S[	        U 5       S35      eUS:X  a  [        R
                  O[        R
                  * nU c  UOU n [        R                  " U 5      (       a  [        R                  " X 5      n [        U SSSS9n U(       d  [	        U 5      [	        U5      :X  a  X)    n U $ )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.
'z_value' should be of shape (z',) when an array-like is provided. Got z
, instead.maxF)r   r   	ensure_2d)r   ri   isscalarrg   r   inffullr   )limit
limit_typer   is_empty_featurekeep_empty_featuren_features_inlimit_bounds          r/   _validate_limit IterativeImputer._validate_limit  s    4 %%56KK&&U#}4J<;M? K003E
|:G 
 !+e 3bff"&&$}%;;uGGJ.EEURWX "c%jC8H4I&I+,Er1   )prefer_skip_nested_validationc                 R	  > [        X0S5        [        U S40 UD6n[        U S[        U R                  5      5      U l        U R                  c  SSKJn  U" 5       U l	        O[        U R                  5      U l	        / U l        SU l        U R                  USS9u  ppx[        TU ]=  U5        [        TU ]A  U5      n	U R"                  S:X  d  [$        R&                  " U5      (       a  SU l        [        TU ]U  Xi5      $ UR,                  S	   S	:X  a  SU l        [        TU ]U  Xi5      $ U R/                  U R0                  S
UR,                  S	   U R2                  U R4                  5      U l        U R/                  U R8                  SUR,                  S	   U R2                  U R4                  5      U l        [$        R&                  " [$        R<                  " U R:                  U R6                  5      5      (       d  [?        S5      eU RA                  U5      n
[C        U
5      U l"        U RG                  U5      nUR,                  u  pU RH                  S:  a  [K        SUR,                  < 35        [M        5       nU RN                  (       dJ  URQ                  5       nU RR                  [$        RT                  " [$        RV                  " X)    5      5      -  n[Y        S	U R"                  S	-   5       GH{  U l        U RZ                  S:X  a  U RA                  U5      n
U
 Hj  nU R]                  UUU5      nU R_                  UUUUSSUR                  R`                  S9u  nn[c        UUU5      nU R                  Re                  U5        Ml     U RH                  S	:  a0  [K        SU R(                  U R"                  [M        5       U-
  4-  5        U RN                  (       a  M  [$        Rf                  Ri                  UW-
  [$        Rj                  SS9nU RH                  S:  a  [K        SRm                  UW5      5        UW:  a  U RH                  S:  a  [K        S5          OAURQ                  5       nGM~     U RN                  (       d  [n        Rp                  " S[r        5        [u        XaU) S9  [        TU ]U  Xi5      $ )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.

**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.
r5   rq   Nr   )BayesianRidgeTr   r   r   minr   z3One (or more) features have min_value >= max_value.0[IterativeImputer] Completing matrix with shape rA   )r&   ru   rv   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   rF   rq   r&   linear_modelr   rh   r
   imputation_sequence_r   r   rW   _fit_indicator_transform_indicatorrH   ri   r   n_iter__concatenate_indicatorrl   r   rO   r   rU   rm   rP   rn   greaterrg   r   r   n_features_with_missing_r   rE   printr   rG   r   rI   r   r   rangerM   r   r   r5   r#   appendlinalgr   r   formatr   warnr   r0   )rY   r   yrv   routed_paramsr   r   rt   complete_maskX_indicatorr   r   	n_samplesr   start_tXt_previousnormalized_tolr$   r%   r&   estimator_tripletinf_normrZ   s                         r/   r   IterativeImputer.fit_transform  s   > 	&.'
 
 %/#5d6G6G#H
 >>!4+oDO#DNN3DO$&! $484L4Ld 5M 5
1" 	}-g2=A==A(;!<!<DL71"BB 88A;!DL71"BB..NNGGAJ""$$
 ..NNGGAJ""$$
 vvbjj$//BCCRSS ++,?@(+K(8%--b1 "	<<!!''ST&$$'')K!XXrvva8L6M/N(OON!!T]]Q%67DL$$0"334GH'$($?$?,%! !% 8 8'%"!(2266 !9 !I %4/%! ))001BC! ($ ||a0||T]]DFW4DEF (((99>>"{*:T>R<<!#NUU$n
 n,||a'TU ggiS 8V ((N& 	b#6"67w-b>>r1   c           
        > [        U 5        U R                  USS9u  pp4[        TU ]  U5      nU R                  S:X  d  [
        R                  " U5      (       a  [        TU ]  X%5      $ [        U R                  5      U R                  -  nSnU R                  S:  a  [        SUR                  < 35        [        5       n[        U R                  5       H  u  pU R                  UUU
R                   U
R"                  U
R$                  SS9u  p+U	S-   U-  (       a  MH  U R                  S:  a)  [        SUS-   U R                  [        5       U-
  4-  5        US-  nM     ['        X!U) S9  [        TU ]  X%5      $ )	af  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&   ru   r   r   r   )r   r   rW   r   r   ri   r   r   r   r   rE   r   rl   r   	enumerater   r$   r%   r&   r0   )rY   r   r   rt   r   r   imputations_per_roundi_rndr   itr   _rZ   s               r/   r   IterativeImputer.transform  st     	484L4Le 5M 5
1" g2=A<<1': ; ;71"BB #D$=$= >$,, N<<!!''ST&%.t/H/H%I!B,,#!**!33+55 - EB F333<<!#4 19dllDFW4DEF
 
! &J$ 	b#6"67w-b>>r1   c                 ,    U R                   " U40 UD6  U $ )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.

**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   )rY   r   r   
fit_paramss       r/   r5   IterativeImputer.fit  s    6 	1+
+r1   c                     [        U S5        [        X5      nU R                  R                  U5      nU R	                  X!5      $ )ao  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)rY   input_featuresnamess      r/   r  &IterativeImputer.get_feature_names_out  s@    ( 	./0F%%;;NK<<USSr1   c                     [        U R                  R                  S9R                  U R                  [        5       R                  SSS9S9nU$ )a"  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.
)ownerr5   )calleecaller)r&   method_mapping)r   rZ   __name__addr&   r   )rY   routers     r/   get_metadata_routing%IterativeImputer.get_metadata_routing  sL      dnn&=&=>BBnn(?..eE.J C 
 r1   )rh   r   rn   rm   r&   rL   rM   r   r   rK   rH   rP   rO   r   r   rJ   rF   rq   rG   rN   rI   rE   )N)NTN)gư>)F)!r  
__module____qualname____firstlineno____doc__r!   rQ   r   r   r   r   r   dict__annotations__ri   nanr   rX   r   r   r   r   r   staticmethodr   r	   r   r   r5   r  r  __static_attributes____classcell__)rZ   s   @r/   r3   r3   <   s   fP$

-
-$Jy'9:;&Kh4?@q$v67#Xh4%OPFG
 &OP
 $HT4fE|THT4fE|T;'(%$D . &) vv$66'&&!%&) &)\ y#v"!H&P$LiAV . .` &+V?	V?p4?l<T2 r1   r3   )2r   collectionsr   numbersr   r   r   numpyri   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/     sw     " "    & + % C C * # * F F   D CE
(J| Jr1   