
    0Ph9:                         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 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  G d de          ZdS )    )IntegralN   )_fit_context)pairwise_distances_chunked)_NAN_METRICS)_get_weights)	_get_mask)is_scalar_nan)HiddenInterval
StrOptions)FLOAT_DTYPES_check_feature_names_incheck_is_fittedvalidate_data   )_BaseImputerc                   &    e Zd ZU dZi ej         eeddd          g eddh          e	 e
d          g e ee                    e	gdgd	Zeed
<   ej        ddddddd fd
Zd Z ed          d fd	            Z fdZddZ xZS )
KNNImputera  Imputation for completing missing values using k-Nearest Neighbors.

    Each sample's missing values are imputed using the mean value from
    `n_neighbors` nearest neighbors found in the training set. Two samples are
    close if the features that neither is missing are close.

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

    .. versionadded:: 0.22

    Parameters
    ----------
    missing_values : int, float, str, np.nan or None, 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.

    n_neighbors : int, default=5
        Number of neighboring samples to use for imputation.

    weights : {'uniform', 'distance'} or callable, default='uniform'
        Weight function used in prediction.  Possible values:

        - 'uniform' : uniform weights. All points in each neighborhood are
          weighted equally.
        - 'distance' : weight points by the inverse of their distance.
          in this case, closer neighbors of a query point will have a
          greater influence than neighbors which are further away.
        - callable : a user-defined function which accepts an
          array of distances, and returns an array of the same shape
          containing the weights.

    metric : {'nan_euclidean'} or callable, default='nan_euclidean'
        Distance metric for searching neighbors. Possible values:

        - 'nan_euclidean'
        - callable : a user-defined function which conforms to the definition
          of ``func_metric(x, y, *, missing_values=np.nan)``. `x` and `y`
          corresponds to a row (i.e. 1-D arrays) of `X` and `Y`, respectively.
          The callable should returns a scalar distance value.

    copy : bool, default=True
        If True, a copy of X will be created. If False, imputation will
        be done in-place whenever possible.

    add_indicator : bool, default=False
        If True, a :class:`MissingIndicator` transform will stack onto the
        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`.

        .. versionadded:: 1.2

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

    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

    See Also
    --------
    SimpleImputer : Univariate imputer for completing missing values
        with simple strategies.
    IterativeImputer : Multivariate imputer that estimates values to impute for
        each feature with missing values from all the others.

    References
    ----------
    * `Olga Troyanskaya, Michael Cantor, Gavin Sherlock, Pat Brown, Trevor
      Hastie, Robert Tibshirani, David Botstein and Russ B. Altman, Missing
      value estimation methods for DNA microarrays, BIOINFORMATICS Vol. 17
      no. 6, 2001 Pages 520-525.
      <https://academic.oup.com/bioinformatics/article/17/6/520/272365>`_

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.impute import KNNImputer
    >>> X = [[1, 2, np.nan], [3, 4, 3], [np.nan, 6, 5], [8, 8, 7]]
    >>> imputer = KNNImputer(n_neighbors=2)
    >>> imputer.fit_transform(X)
    array([[1. , 2. , 4. ],
           [3. , 4. , 3. ],
           [5.5, 6. , 5. ],
           [8. , 8. , 7. ]])

    For a more detailed example see
    :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py`.
    r   Nleft)closeduniformdistanceboolean)n_neighborsweightsmetriccopy_parameter_constraints   nan_euclideanTF)missing_valuesr   r   r   r   add_indicatorkeep_empty_featuresc                    t                                          |||           || _        || _        || _        || _        d S )N)r"   r#   r$   )super__init__r   r   r   r   )	selfr"   r   r   r   r   r#   r$   	__class__s	           S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/impute/_knn.pyr'   zKNNImputer.__init__   sR     	)' 3 	 	
 	
 	

 '			    c                 H   t          j        ||dz
  d          ddd|f         }|t          j        |j        d                   dddf         |f         }t	          || j                  }|d|t          j        |          <   n+t          j        |          }d|t          j        |          <   |                    |          }|                    |          }	t           j	        
                    ||	          }t           j	                            |d|          j        S )a  Helper function to impute a single column.

        Parameters
        ----------
        dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors)
            Distance matrix between the receivers and potential donors from
            training set. There must be at least one non-nan distance between
            a receiver and a potential donor.

        n_neighbors : int
            Number of neighbors to consider.

        fit_X_col : ndarray of shape (n_potential_donors,)
            Column of potential donors from training set.

        mask_fit_X_col : ndarray of shape (n_potential_donors,)
            Missing mask for fit_X_col.

        Returns
        -------
        imputed_values: ndarray of shape (n_receivers,)
            Imputed values for receiver.
        r   axisNr   g        mask)r.   r   )npargpartitionarangeshaper   r   isnan	ones_liketakemaarrayaveragedata)
r(   dist_pot_donorsr   	fit_X_colmask_fit_X_col
donors_idxdonors_distweight_matrixdonorsdonors_masks
             r*   _calc_imputezKNNImputer._calc_impute   s   2 __kAoANNNAA||O


 &Ij&q)**111d73Z?
 %[$,?? $58M"(=1122L55M36M"(;//0 
++$))*55V+66u}}V!]}CCHHr+   )prefer_skip_nested_validationc                 R   t          | j                  sd}nd}t          | |dt          || j                  }|| _        t          | j        | j                  | _        t          j	        | j        d           | _
        t                                          | j                   | S )a  Fit the imputer on X.

        Parameters
        ----------
        X : array-like shape of (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 here for API consistency by convention.

        Returns
        -------
        self : object
            The fitted `KNNImputer` class instance.
        T	allow-nanF)accept_sparsedtypeensure_all_finiter   r   r-   )r
   r"   r   r   r   _fit_Xr	   _mask_fit_Xr1   all_valid_maskr&   _fit_indicator)r(   XyrJ   r)   s       r*   fitzKNNImputer.fit   s    & T011 	, $ +/
 
 
 $T[$2EFFF4#3!<<<<t/000r+   c           
         	
 t                      t           j                  sd}nd}t           dt          d| j        d          t           j                  	 j        
 j        t                      
                    	          }t          j        	ddf                   sB j        r}d|dd f<   nddf         }t                                          ||          S t          j        	ddf                             d                    t          j        
          t          j        j        d         t&          	          t          j        j        d                   <   	
 fd
}t+          ddf          j         j         j        ||          }|D ]} j        r}d|dd f<   nddf         }t                                          ||          S )a  Impute all missing values in X.

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

        Returns
        -------
        X : array-like of shape (n_samples, n_output_features)
            The imputed dataset. `n_output_features` is the number of features
            that is not always missing during `fit`.
        TrG   F)rH   rI   force_writeablerJ   r   resetNr   r   r-   )rI   c           	         ||t          |           z            }t          j        d                   D ]}|         s||f         }t          j        |          s+t          j        d d |f                   \  }|t          j        |                   }| |         |z
           d d |f         }t          j        |                              d          }||         }	|	j	        rt          j
                            j        d d |f         d d |f                                                   }
|
|	|f<   t          |	          t          |          k    r,||          }| |         |z
           d d |f         }t          j        t          |                    }                    ||j        ||f         ||f                   }|||f<   d S )Nr   r-   r/   )lenranger4   r1   anynonzeroflatnonzeror5   rM   sizer8   r9   rK   meanminr   rD   )
dist_chunkstartrow_missing_chunkcolcol_maskpotential_donors_idxreceivers_idxdist_subsetall_nan_dist_maskall_nan_receivers_idxcol_meanr   valuerP   dist_idx_mapr0   
mask_fit_Xnon_missing_fix_Xrow_missing_idxr(   
valid_masks                r*   process_chunkz+KNNImputer.transform.<locals>.process_chunk:  s-    /J8O0O P QWQZ(( /. /.!#  13 67vh'' *,*5Fqqq#v5N*O*O'% !2".2J2J K )m)Du)LMAA++
 %'H[$9$9$=$=1$=$E$E!(56G(H%(- !u{{AAAsF+*QQQV2D  +    dff  5=A+S01011S5G5GGG  %23D2D$EM",\--H5-P"Q//#K "$"2C8L4M4MNN))K 4c 9:3S89	  ).-$%%_/. /.r+   )r   r"   rJ   reduce_func)r   r
   r"   r   r   r   r	   rL   rN   r&   _transform_indicatorr1   rY   r$   _concatenate_indicatorr[   logical_notzerosr4   intr3   r   rK   r   )r(   rP   rJ   X_indicatorXcrp   genchunkrk   r0   rl   rm   rn   ro   r)   s   ``      @@@@@@r*   	transformzKNNImputer.transform   ss    	T011 	, $ + /	
 	
 	
 D/00%
%
gg22488 vd111j=)** 	C' &%&111zk>""qqq*}% 7711"kBBB.aaam)<)@)@a)@)H)HIIN:66 x
#666(*	/2G2J(K(K_%3	. 3	. 3	. 3	. 3	. 3	. 3	. 3	. 3	. 3	. 3	. 3	.l )oqqq !K;./%
 
 
  	 	E# 	"B!"Bqqq:+~111j=!Bww--b+>>>r+   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   rN   (_concatenate_indicator_feature_names_out)r(   input_featuresnamess      r*   get_feature_names_outz KNNImputer.get_feature_names_out  sG    ( 	.///0~FFt/0<<UNSSSr+   )N)__name__
__module____qualname____doc__r   r   r   r   r   callabler   setr   dict__annotations__r1   nanr'   rD   r   rR   r{   r   __classcell__)r)   s   @r*   r   r      s        k kZ$

-$ 1d6BBBCJ	:67766$<<P:cc,//00(;$ $ $D    v!      *0I 0I 0Id \555& & & & & 65&PD? D? D? D? D?LT T T T T T T Tr+   r   )numbersr   numpyr1   baser   metricsr   metrics.pairwiser   neighbors._baser   utils._maskr	   utils._missingr
   utils._param_validationr   r   r   utils.validationr   r   r   r   _baser   r    r+   r*   <module>r      sG                   0 0 0 0 0 0 + + + + + + * * * * * * # # # # # # * * * * * * B B B B B B B B B B                  CT CT CT CT CT CT CT CT CT CTr+   