B
    vd                 @   s6  d Z ddlmZ ddlZddlZddlZddlZddlm	Z
 ddlmZ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 d	dlmZ ejejej fZ!d[ddddZ"d\ddZ#ddddZ$dddddZ%dd Z&dd Z'd d! Z(d"d# Z)d$d% Z*d&d' Z+d(d) Z,d*d+ Z-d,d- Z.d]dd.ddddddddd/
d0d1Z/d^d2d3Z0d_dd.ddddddddddd4d5d6Z1d`d7d8Z2dd9d:d;Z3d<d= Z4d>d? Z5d@dddAdBdCZ6dade7dDdEdFZ8dGdH Z9dddIdJdKdLZ:dbdMdNZ;dcdOdPZ<dddSdTZ=dedUdVZ>dWdX Z?dfdYdZZ@dS )gzUtilities for input validation    )wrapsN)	signatureisclass	Parameter)ComplexWarning)suppress   )_object_dtype_isnanparse_version   )
get_config)PositiveSpectrumWarning)NotFittedError)DataConversionWarningz1.1 (renaming of 0.26))versionc               s     fdd}| dk	r|| S |S )a  Decorator for methods that issues warnings for positional arguments.

    Using the keyword-only argument syntax in pep 3102, arguments after the
    * will issue a warning when passed as a positional argument.

    Parameters
    ----------
    func : callable, default=None
        Function to check arguments on.
    version : callable, default="1.1 (renaming of 0.26)"
        The version when positional arguments will result in error.
    c                sv   t g g  xDj D ]6\}}|jtjkr< | q|jtjkr| qW t fdd}|S )Nc                 s   t | t   }|dkr"| |S dd td | | | d  D }d|}td| d dt |tj|  f |S )Nr   c             S   s   g | ]\}}d  ||qS )z{}={})format).0namearg r   e/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/sklearn/utils/validation.py
<listcomp>E   s   zi_deprecate_positional_args.<locals>._inner_deprecate_positional_args.<locals>.inner_f.<locals>.<listcomp>z, zPass z as keyword args. From version z> passing these as positional arguments will result in an error)lenzipjoinwarningswarnFutureWarningupdate
parameters)argskwargs
extra_argsZargs_msg)all_argsfkwonly_argssigr   r   r   inner_f=   s    
 
zU_deprecate_positional_args.<locals>._inner_deprecate_positional_args.<locals>.inner_f)	r   r   itemskindr   POSITIONAL_OR_KEYWORDappendKEYWORD_ONLYr   )r$   r   paramr'   )r   )r#   r$   r%   r&   r    _inner_deprecate_positional_args2   s    zD_deprecate_positional_args.<locals>._inner_deprecate_positional_argsNr   )funcr   r.   r   )r   r   _deprecate_positional_args$   s    "r0   Fc             C   s   ddl m} t d rdS t| } | jjdk}|rHt|tj| rHn|rd}|rbt	| 
 st|st|  s|r|dnd}t|||dk	r|n| jn(| jtd	kr|st| 
 rtd
dS )z-Like assert_all_finite, but only for ndarray.r   )_safe_accumulator_opZassume_finiteNfcz0Input contains {} or a value too large for {!r}.infinityzNaN, infinityobjectzInput contains NaN)Zextmathr1   _get_confignpZ
asanyarraydtyper)   isfinitesumisinfanyall
ValueErrorr   r	   )X	allow_nan	msg_dtyper1   Zis_floatZmsg_errZtype_errr   r   r   _assert_all_finiteZ   s(    

rA   )r?   c            C   s   t t| r| jn| | dS )zThrow a ValueError if X contains NaN or infinity.

    Parameters
    ----------
    X : {ndarray, sparse matrix}

    allow_nan : bool, default=False
    N)rA   spissparsedata)r>   r?   r   r   r   assert_all_finite}   s    	rE   T)copyforce_all_finitec            C   s   t | tjs"t | tjs>t| s>t| dddgtj||ddS t| rj| jtj	tjgkrj|rf| 
 S | S | jtj	tjgkr|r| 
| jd rdndS | S | jjd	kr| jjd
krtj	}ntj}| |S dS )ak  Convert an array-like to an array of floats.

    The new dtype will be np.float32 or np.float64, depending on the original
    type. The function can create a copy or modify the argument depending
    on the argument copy.

    Parameters
    ----------
    X : {array-like, sparse matrix}
        The input data.

    copy : bool, default=True
        If True, a copy of X will be created. If False, a copy may still be
        returned if X's dtype is not a floating point type.

    force_all_finite : bool or 'allow-nan', default=True
        Whether to raise an error on np.inf, np.nan, pd.NA in X. The
        possibilities are:

        - True: Force all values of X to be finite.
        - False: accepts np.inf, np.nan, pd.NA in X.
        - 'allow-nan': accepts only np.nan and pd.NA values in X. Values cannot
          be infinite.

        .. versionadded:: 0.20
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`

    Returns
    -------
    XT : {ndarray, sparse matrix}
        An array of type float.
    csrcsccooF)accept_sparser7   rF   rG   	ensure_2dZF_CONTIGUOUSFCZuib   N)
isinstancer6   matrixZndarrayrB   rC   check_arrayfloat64r7   float32rF   flagsr)   itemsizeastype)r>   rF   rG   Zreturn_dtyper   r   r   as_float_array   s"    $ rX   c             C   s   t | dpt | dpt | dS )z(Returns whether the input is array-like.__len__shape	__array__)hasattr)xr   r   r   _is_arraylike   s    r^   c          
   C   s  t | }|jdkr|j}n|j d|j }d| }t| dsft| dsft| ds\t|t| } t| drt| jdrt| jdkr|d| j 7 }t|| jd S | d	 }t	|t
ttfr|d
t |j 7 }t|yt|S  tk
r } zt||W dd}~X Y nX dS )a  Return the number of features in an array-like X.

    This helper function tries hard to avoid to materialize an array version
    of X unless necessary. For instance, if X is a list of lists,
    this function will return the length of the first element, assuming
    that subsequent elements are all lists of the same length without
    checking.
    Parameters
    ----------
    X : array-like
        array-like to get the number of features.

    Returns
    -------
    features : int
        Number of features
    builtins.z5Unable to find the number of features from X of type rY   rZ   r[   r   z with shape r   z where the samples are of type N)type
__module____qualname__r\   	TypeErrorr6   asarrayrZ   r   rP   strbytesdict	Exception)r>   type_	type_namemessageZfirst_sampleerrr   r   r   _num_features   s,    





rn   c          
   C   s   dt |  }t| dr(t| jr(t|t| dsZt| dsZt| drRt| } nt|t| dr| jdk	rt| jdkrtd|  t	| jd t
jr| jd S yt| S  tk
r } zt||W dd}~X Y nX dS )	z)Return number of samples in array-like x.z'Expected sequence or array-like, got %sfitrY   rZ   r[   Nr   z;Singleton array %r cannot be considered a valid collection.)ra   r\   callablero   rd   r6   re   rZ   r   rP   numbersIntegral)r]   rl   Z
type_errorr   r   r   _num_samples   s"    


rs   c             C   s`   | dkst | trDttjtdk r4tj| dd} q\tj| dd} nt| ds\td| | S )a  Check that ``memory`` is joblib.Memory-like.

    joblib.Memory-like means that ``memory`` can be converted into a
    joblib.Memory instance (typically a str denoting the ``location``)
    or has the same interface (has a ``cache`` method).

    Parameters
    ----------
    memory : None, str or object with the joblib.Memory interface

    Returns
    -------
    memory : object with the joblib.Memory interface

    Raises
    ------
    ValueError
        If ``memory`` is not joblib.Memory-like.
    Nz0.12r   )Zcachedirverbose)locationrt   cachezg'memory' should be None, a string or have the same interface as joblib.Memory. Got memory='{}' instead.)	rP   rf   r
   joblib__version__ZMemoryr\   r=   r   )Zmemoryr   r   r   check_memory  s    
ry   c              G   s>   dd | D }t |}t|dkr:tddd |D  dS )a  Check that all arrays have consistent first dimensions.

    Checks whether all objects in arrays have the same shape or length.

    Parameters
    ----------
    *arrays : list or tuple of input objects.
        Objects that will be checked for consistent length.
    c             S   s   g | ]}|d k	rt |qS )N)rs   )r   r>   r   r   r   r   I  s    z+check_consistent_length.<locals>.<listcomp>r   z>Found input variables with inconsistent numbers of samples: %rc             S   s   g | ]}t |qS r   )int)r   lr   r   r   r   N  s    N)r6   uniquer   r=   )ZarrayslengthsZuniquesr   r   r   check_consistent_length>  s    
r~   c             C   s@   t | r|  S t| ds&t| dr*| S | dkr6| S t| S )a  Ensure iterable supports indexing or convert to an indexable variant.

    Convert sparse matrices to csr and other non-indexable iterable to arrays.
    Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.

    Parameters
    ----------
    iterable : {list, dataframe, ndarray, sparse matrix} or None
        Object to be converted to an indexable iterable.
    __getitem__ZilocN)rB   rC   tocsrr\   r6   array)iterabler   r   r   _make_indexableR  s    
r   c              G   s   dd | D }t |  |S )aK  Make arrays indexable for cross-validation.

    Checks consistent length, passes through None, and ensures that everything
    can be indexed by converting sparse matrices to csr and converting
    non-interable objects to arrays.

    Parameters
    ----------
    *iterables : {lists, dataframes, ndarrays, sparse matrices}
        List of objects to ensure sliceability.

    Returns
    -------
    result : list of {ndarray, sparse matrix, dataframe} or None
        Returns a list containing indexable arrays (i.e. NumPy array,
        sparse matrix, or dataframe) or `None`.
    c             S   s   g | ]}t |qS r   )r   )r   r>   r   r   r   r   y  s    zindexable.<locals>.<listcomp>)r~   )	iterablesresultr   r   r   	indexablef  s    r   c             C   s   |dkr| j }d}t|tr"|g}t| | |dkr>tdnVt|ttfr~t|dkr`td| j	|kr| 
|d } d}n|dk	rtd	||| j kr| |} n|r|s|  } |rt| dstjd	| j	 d
d nt| j|dkd | S )a  Convert a sparse matrix to a given format.

    Checks the sparse format of spmatrix and converts if necessary.

    Parameters
    ----------
    spmatrix : sparse matrix
        Input to validate and convert.

    accept_sparse : str, bool or list/tuple of str
        String[s] representing allowed sparse matrix formats ('csc',
        'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). If the input is sparse but
        not in the allowed format, it will be converted to the first listed
        format. True allows the input to be any format. False means
        that a sparse matrix input will raise an error.

    dtype : str, type or None
        Data type of result. If None, the dtype of the input is preserved.

    copy : bool
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.

    force_all_finite : bool or 'allow-nan'
        Whether to raise an error on np.inf, np.nan, pd.NA in X. The
        possibilities are:

        - True: Force all values of X to be finite.
        - False: accepts np.inf, np.nan, pd.NA in X.
        - 'allow-nan': accepts only np.nan and pd.NA values in X. Values cannot
          be infinite.

        .. versionadded:: 0.20
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`

    Returns
    -------
    spmatrix_converted : sparse matrix.
        Matrix that is ensured to have an allowed type.
    NFzjA sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.r   z]When providing 'accept_sparse' as a tuple or list, it must contain at least one string value.TzjParameter 'accept_sparse' should be a string, boolean or list of strings. You provided 'accept_sparse={}'.rD   z,Can't check %s sparse matrix for nan or inf.r   )
stacklevelz	allow-nan)r?   )r7   rP   rf   _check_large_sparserd   listtupler   r=   r   ZasformatrW   rF   r\   r   r   rA   rD   )ZspmatrixrK   r7   rF   rG   accept_large_sparseZchanged_formatr   r   r   _ensure_sparse_format~  s>    .





r   c             C   s>   t | dr:| jd k	r:t | jdr:| jjdkr:td| d S )Nr7   r)   czComplex data not supported
{}
)r\   r7   r)   r=   r   )r   r   r   r   _ensure_no_complex_data  s
    

r   numeric)
r   r7   orderrF   rG   rL   allow_ndensure_min_samplesensure_min_features	estimatorc   
   #      C   s  t | tjrtdt | }t |to,|dk}t| dd}t|dsHd}d}d}t| drnt| j	drnt
t6 d	d
lm} t| ds| j	| rtd W dQ R X t| j	}xt|D ]\}}|jdkrtt||< q|jdrt
tN d	dlm}m}m}m}m}m}m}m} t |||||||||frBd}W dQ R X qW t dd |D rntj!| }|r|dk	r|jdkrtj"}nd}t |tt#fr|dk	r||krd}n|d	 }|r| $|} |dkrt%d&||dk	rt |tr|}n|j'j(}nd}|dk	r,d| nd}t| dr| j)dkr| j*+ } | jtdkrt,dd |j	D }t-|dkrt%dt./| rt0|  t1| |||||d} nt2  yxt3dt4 |dk	r*t|jd kr*tj5| |d!} | jjd"krt6| d|d# | j$|d$dd%} ntj5| ||d&} W n4 t4k
rp } zt%d'&| |W dd}~X Y nX W dQ R X t0|  |r| j)d	krt%d(&| | j)dkrt%d)&| |r"| jjd*kr"tjd+td,d- y| $tj"} W n. t%k
r  }  zt%d.| W dd} ~ X Y nX |sF| j)d/krFt%d0| j)|f |r\t6| |d1kd2 |	d	krt7| }!|!|	k rt%d3|!| j8|	|f |
d	kr| j)d,kr| j8d }"|"|
k rt%d4|"| j8|
|f |rt9| |rtj:| ||d5} | S )6a`  Input validation on an array, list, sparse matrix or similar.

    By default, the input is checked to be a non-empty 2D array containing
    only finite values. If the dtype of the array is object, attempt
    converting to float, raising on failure.

    Parameters
    ----------
    array : object
        Input object to check / convert.

    accept_sparse : str, bool or list/tuple of str, default=False
        String[s] representing allowed sparse matrix formats, such as 'csc',
        'csr', etc. If the input is sparse but not in the allowed format,
        it will be converted to the first listed format. True allows the input
        to be any format. False means that a sparse matrix input will
        raise an error.

    accept_large_sparse : bool, default=True
        If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by
        accept_sparse, accept_large_sparse=False will cause it to be accepted
        only if its indices are stored with a 32-bit dtype.

        .. versionadded:: 0.20

    dtype : 'numeric', type, list of type or None, default='numeric'
        Data type of result. If None, the dtype of the input is preserved.
        If "numeric", dtype is preserved unless array.dtype is object.
        If dtype is a list of types, conversion on the first type is only
        performed if the dtype of the input is not in the list.

    order : {'F', 'C'} or None, default=None
        Whether an array will be forced to be fortran or c-style.
        When order is None (default), then if copy=False, nothing is ensured
        about the memory layout of the output array; otherwise (copy=True)
        the memory layout of the returned array is kept as close as possible
        to the original array.

    copy : bool, default=False
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.

    force_all_finite : bool or 'allow-nan', default=True
        Whether to raise an error on np.inf, np.nan, pd.NA in array. The
        possibilities are:

        - True: Force all values of array to be finite.
        - False: accepts np.inf, np.nan, pd.NA in array.
        - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
          cannot be infinite.

        .. versionadded:: 0.20
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`

    ensure_2d : bool, default=True
        Whether to raise a value error if array is not 2D.

    allow_nd : bool, default=False
        Whether to allow array.ndim > 2.

    ensure_min_samples : int, default=1
        Make sure that the array has a minimum number of samples in its first
        axis (rows for a 2D array). Setting to 0 disables this check.

    ensure_min_features : int, default=1
        Make sure that the 2D array has some minimum number of features
        (columns). The default value of 1 rejects empty datasets.
        This check is only enforced when the input data has effectively 2
        dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0
        disables this check.

    estimator : str or estimator instance, default=None
        If passed, include the name of the estimator in warning messages.

    Returns
    -------
    array_converted : object
        The converted and validated array.
    znp.matrix usage is deprecated in 1.0 and will raise a TypeError in 1.2. Please convert to a numpy array with np.asarray. For more information see: https://numpy.org/doc/stable/reference/generated/numpy.matrix.htmlr   r7   Nr)   Fdtypesr[   r   )	is_sparsesparsezWpandas.DataFrame with sparse columns found.It will be converted to a dense numpy array.b)ZIntZUInt)	Int8Dtype
Int16Dtype
Int32Dtype
Int64Dtype
UInt8DtypeUInt16DtypeUInt32DtypeUInt64DtypeTc             s   s   | ]}t |tjV  qd S )N)rP   r6   r7   )r   r7   r   r   r   	<genexpr>  s    zcheck_array.<locals>.<genexpr>O)TFz	allow-nanzBforce_all_finite should be a bool or "allow-nan". Got {!r} insteadZ	Estimatorz by %s r   r4   c             S   s   g | ]}|j jqS r   )subtyper   )r   dtr   r   r   r     s    zcheck_array.<locals>.<listcomp>zPandas DataFrame with mixed sparse extension arrays generated a sparse matrix with object dtype which can not be converted to a scipy sparse matrix.Sparse extension arrays should all have the same numeric type.)rK   r7   rF   rG   r   erroriu)r   r$   )r?   r@   unsafe)ZcastingrF   )r   r7   zComplex data not supported
{}
zExpected 2D array, got scalar array instead:
array={}.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.zExpected 2D array, got 1D array instead:
array={}.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.ZOUSVzArrays of bytes/strings is being converted to decimal numbers if dtype='numeric'. This behavior is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). Please convert your data to numeric values explicitly instead.r   )r   zRUnable to convert array of bytes/strings into decimal numbers with dtype='numeric'   z*Found array with dim %d. %s expected <= 2.z	allow-nan)r?   zMFound array with %d sample(s) (shape=%s) while a minimum of %d is required%s.zNFound array with %d feature(s) (shape=%s) while a minimum of %d is required%s.)r7   r   );rP   r6   rQ   r   r   r   rf   getattrr\   r   r   ImportErrorZpandas.api.typesr   applyr;   r   	enumerater)   r7   r4   r   
startswithZpandasr   r   r   r   r   r   r   r   r<   Zresult_typerS   r   rW   r=   r   	__class____name__ndimr   Zto_coosetr   rB   rC   r   r   catch_warningssimplefilterr   re   rA   rs   rZ   Zmay_share_memoryr   )#r   rK   r   r7   r   rF   rG   rL   r   r   r   r   Z
array_origZdtype_numericZ
dtype_origZdtypes_origZhas_pd_integer_arrayr   iZ
dtype_iterr   r   r   r   r   r   r   r   Zestimator_namecontextZunique_dtypesZcomplex_warninge	n_samplesZ
n_featuresr   r   r   rR     s    b




(








 



rR   c             C   sl   |shdg}|   dkr ddg}n|   dkr6ddg}ndS x,|D ]$}t| |j}||kr@td	| q@W dS )
zGRaise a ValueError if X has 64bit indices and accept_large_sparse=FalseZint32rJ   colrow)rH   rI   ZbsrindicesindptrNzNOnly sparse matrices with 32-bit integer indices are accepted. Got %s indices.)Z	getformatr   r7   r=   )r>   r   Zsupported_indicesZ
index_keyskeyZindices_datatyper   r   r   r   :  s    


r   )r   r7   r   rF   rG   rL   r   multi_outputr   r   	y_numericr   c            C   sP   |dkrt dt| ||||||||	|||d} t||
|d}t| | | |fS )a=  Input validation for standard estimators.

    Checks X and y for consistent length, enforces X to be 2D and y 1D. By
    default, X is checked to be non-empty and containing only finite values.
    Standard input checks are also applied to y, such as checking that y
    does not have np.nan or np.inf targets. For multi-label y, set
    multi_output=True to allow 2D and sparse y. If the dtype of X is
    object, attempt converting to float, raising on failure.

    Parameters
    ----------
    X : {ndarray, list, sparse matrix}
        Input data.

    y : {ndarray, list, sparse matrix}
        Labels.

    accept_sparse : str, bool or list of str, default=False
        String[s] representing allowed sparse matrix formats, such as 'csc',
        'csr', etc. If the input is sparse but not in the allowed format,
        it will be converted to the first listed format. True allows the input
        to be any format. False means that a sparse matrix input will
        raise an error.

    accept_large_sparse : bool, default=True
        If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by
        accept_sparse, accept_large_sparse will cause it to be accepted only
        if its indices are stored with a 32-bit dtype.

        .. versionadded:: 0.20

    dtype : 'numeric', type, list of type or None, default='numeric'
        Data type of result. If None, the dtype of the input is preserved.
        If "numeric", dtype is preserved unless array.dtype is object.
        If dtype is a list of types, conversion on the first type is only
        performed if the dtype of the input is not in the list.

    order : {'F', 'C'}, default=None
        Whether an array will be forced to be fortran or c-style.

    copy : bool, default=False
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.

    force_all_finite : bool or 'allow-nan', default=True
        Whether to raise an error on np.inf, np.nan, pd.NA in X. This parameter
        does not influence whether y can have np.inf, np.nan, pd.NA values.
        The possibilities are:

        - True: Force all values of X to be finite.
        - False: accepts np.inf, np.nan, pd.NA in X.
        - 'allow-nan': accepts only np.nan or pd.NA values in X. Values cannot
          be infinite.

        .. versionadded:: 0.20
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`

    ensure_2d : bool, default=True
        Whether to raise a value error if X is not 2D.

    allow_nd : bool, default=False
        Whether to allow X.ndim > 2.

    multi_output : bool, default=False
        Whether to allow 2D y (array or sparse matrix). If false, y will be
        validated as a vector. y cannot have np.nan or np.inf values if
        multi_output=True.

    ensure_min_samples : int, default=1
        Make sure that X has a minimum number of samples in its first
        axis (rows for a 2D array).

    ensure_min_features : int, default=1
        Make sure that the 2D array has some minimum number of features
        (columns). The default value of 1 rejects empty datasets.
        This check is only enforced when X has effectively 2 dimensions or
        is originally 1D and ``ensure_2d`` is True. Setting to 0 disables
        this check.

    y_numeric : bool, default=False
        Whether to ensure that y has a numeric type. If dtype of y is object,
        it is converted to float64. Should only be used for regression
        algorithms.

    estimator : str or estimator instance, default=None
        If passed, include the name of the estimator in warning messages.

    Returns
    -------
    X_converted : object
        The converted and validated X.

    y_converted : object
        The converted and validated y.
    Nzy cannot be None)rK   r   r7   r   rF   rG   rL   r   r   r   r   )r   r   )r=   rR   _check_yr~   )r>   yrK   r   r7   r   rF   rG   rL   r   r   r   r   r   r   r   r   r   	check_X_yM  s$    t
r   c             C   sT   |rt | ddddd} nt| dd} t|  t|  |rP| jjdkrP| tj} | S )z4Isolated part of check_X_y dedicated to y validationrH   TFN)rK   rG   rL   r7   )r   r   )	rR   column_or_1drA   r   r7   r)   rW   r6   rS   )r   r   r   r   r   r   r     s    r   )r   c            C   sr   t | } t | }t|dkr*t | S t|dkr`|d dkr`|rVtjdtdd t | S td	|dS )av  Ravel column or 1d numpy array, else raises an error.

    Parameters
    ----------
    y : array-like
       Input data.

    warn : bool, default=False
       To control display of warnings.

    Returns
    -------
    y : ndarray
       Output data.

    Raises
    -------
    ValueError
        If `y` is not a 1D array or a 2D array with a single row or column.
    r   r   zA column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().)r   z9y should be a 1d array, got an array of shape {} instead.N)
r6   re   rZ   r   Zravelr   r   r   r=   r   )r   r   rZ   r   r   r   r     s    



r   c             C   sV   | dks| t jkrt jjjS t| tjr4t j| S t| t jjrF| S td|  dS )a  Turn seed into a np.random.RandomState instance

    Parameters
    ----------
    seed : None, int or instance of RandomState
        If seed is None, return the RandomState singleton used by np.random.
        If seed is an int, return a new RandomState instance seeded with seed.
        If seed is already a RandomState instance, return it.
        Otherwise raise ValueError.
    Nz=%r cannot be used to seed a numpy.random.RandomState instance)	r6   randomZmtrandZ_randrP   rq   rr   ZRandomStater=   )seedr   r   r   check_random_state  s    
r   c             C   s   |t | jjkS )a(  Check whether the estimator's fit method supports the given parameter.

    Parameters
    ----------
    estimator : object
        An estimator to inspect.

    parameter : str
        The searched parameter.

    Returns
    -------
    is_parameter : bool
        Whether the parameter was found to be a named parameter of the
        estimator's fit method.

    Examples
    --------
    >>> from sklearn.svm import SVC
    >>> from sklearn.utils.validation import has_fit_parameter
    >>> has_fit_parameter(SVC(), "sample_weight")
    True
    )r   ro   r   )r   Z	parameterr   r   r   has_fit_parameter)  s    r   g|=)tolraise_warningraise_exceptionc            C   s   | j dks| jd | jd kr.td| jt| rj| | j }|jdkrT| }t	t
|j|k }ntj| | j|d}|s|rtd|rtjddd	 t| rd
| j }td| | j  | } nd| | j  } | S )a  Make sure that array is 2D, square and symmetric.

    If the array is not symmetric, then a symmetrized version is returned.
    Optionally, a warning or exception is raised if the matrix is not
    symmetric.

    Parameters
    ----------
    array : {ndarray, sparse matrix}
        Input object to check / convert. Must be two-dimensional and square,
        otherwise a ValueError will be raised.

    tol : float, default=1e-10
        Absolute tolerance for equivalence of arrays. Default = 1E-10.

    raise_warning : bool, default=True
        If True then raise a warning if conversion is required.

    raise_exception : bool, default=False
        If True then raise an exception if array is not symmetric.

    Returns
    -------
    array_sym : {ndarray, sparse matrix}
        Symmetrized version of the input array, i.e. the average of array
        and array.transpose(). If sparse, then duplicate entries are first
        summed and zeros are eliminated.
    r   r   r   z3array must be 2-dimensional and square. shape = {0})rH   rI   rJ   )atolzArray must be symmetriczYArray is not symmetric, and will be converted to symmetric by average with its transpose.)r   tog      ?)r   rZ   r=   r   rB   rC   Tr   r6   r<   absrD   allcloser   r   r   )r   r   r   r   diffZ	symmetric
conversionr   r   r   check_symmetricD  s*    




r   )msg
all_or_anyc               s   t  rtd |dkr"d}t ds8td  |dk	rlt|ttfsT|g}| fdd|D }n&t dr  }nd	d t D }|st	|d
t
 ji dS )a  Perform is_fitted validation for estimator.

    Checks if the estimator is fitted by verifying the presence of
    fitted attributes (ending with a trailing underscore) and otherwise
    raises a NotFittedError with the given message.

    If an estimator does not set any attributes with a trailing underscore, it
    can define a ``__sklearn_is_fitted__`` method returning a boolean to specify if the
    estimator is fitted or not.

    Parameters
    ----------
    estimator : estimator instance
        estimator instance for which the check is performed.

    attributes : str, list or tuple of str, default=None
        Attribute name(s) given as string or a list/tuple of strings
        Eg.: ``["coef_", "estimator_", ...], "coef_"``

        If `None`, `estimator` is considered fitted if there exist an
        attribute that ends with a underscore and does not start with double
        underscore.

    msg : str, default=None
        The default error message is, "This %(name)s instance is not fitted
        yet. Call 'fit' with appropriate arguments before using this
        estimator."

        For custom messages if "%(name)s" is present in the message string,
        it is substituted for the estimator name.

        Eg. : "Estimator, %(name)s, must be fitted before sparsifying".

    all_or_any : callable, {all, any}, default=all
        Specify whether all or any of the given attributes must exist.

    Returns
    -------
    None

    Raises
    ------
    NotFittedError
        If the attributes are not found.
    z{} is a class, not an instance.NzlThis %(name)s instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.ro   z %s is not an estimator instance.c                s   g | ]}t  |qS r   )r\   )r   attr)r   r   r   r     s    z#check_is_fitted.<locals>.<listcomp>__sklearn_is_fitted__c             S   s$   g | ]}| d r|ds|qS )___)endswithr   )r   vr   r   r   r     s    r   )r   rd   r   r\   rP   r   r   r   varsr   ra   r   )r   
attributesr   r   Zfittedr   )r   r   check_is_fitted  s    .


r   c             C   sZ   t | r:| jdkr|  } | jjdkr.d}qB| j }n|  }|dk rVtd| dS )z
    Check if there is any negative value in an array.

    Parameters
    ----------
    X : {array-like, sparse matrix}
        Input data.

    whom : str
        Who passed X to this function.
    )ZlilZdokr   z$Negative values in data passed to %sN)rB   rC   r   r   rD   sizeminr=   )r>   ZwhomZX_minr   r   r   check_non_negative  s    

r   both)min_valmax_valinclude_boundariesc         	   C   s   t | |s(t| d| dt|  dd}||krNtdt| d| d|dkr\tjntj}|dk	r|| |rt| d	|  d
|dkrdnd d| d|dkrtjntj	}|dk	r|| |rt| d	|  d
|dkrdnd d| d| S )a  Validate scalar parameters type and value.

    Parameters
    ----------
    x : object
        The scalar parameter to validate.

    name : str
        The name of the parameter to be printed in error messages.

    target_type : type or tuple
        Acceptable data types for the parameter.

    min_val : float or int, default=None
        The minimum valid value the parameter can take. If None (default) it
        is implied that the parameter does not have a lower bound.

    max_val : float or int, default=None
        The maximum valid value the parameter can take. If None (default) it
        is implied that the parameter does not have an upper bound.

    include_boundaries : {"left", "right", "both", "neither"}, default="both"
        Whether the interval defined by `min_val` and `max_val` should include
        the boundaries. Possible choices are:

        - `"left"`: only `min_val` is included in the valid interval;
        - `"right"`: only `max_val` is included in the valid interval;
        - `"both"`: `min_val` and `max_val` are included in the valid interval;
        - `"neither"`: neither `min_val` nor `max_val` are included in the
          valid interval.

    Returns
    -------
    x : numbers.Number
        The validated number.

    Raises
    ------
    TypeError
        If the parameter's type does not match the desired type.

    ValueError
        If the parameter's value violates the given bounds.
    z must be an instance of z, not r`   )leftrightr   Zneitherz(Unknown value for `include_boundaries`: z. Possible values are: )r   r   Nz == z
, must be z>=> )r   r   z<=<)
rP   rd   ra   r=   reproperatorltlegtge)r]   r   Ztarget_typer   r   r   Zexpected_include_boundariesZcomparison_operatorr   r   r   check_scalar  s    6
**r   c             C   s~  t | } | jt jk}d}|r"dnd}|r.dnd}|r:dnd}t |  st t |  }t t 	|  }||| krt
d||  |rtd||  t t 	| } |  }	|	d	k rt
d
|	 nj|  }
|
| |	 k r|
| k rt
d|
 |	  n2|
d	k r:|r.td|
 |	  t d	| | d	k < d	| k | ||	 k @ }| rz|rrtdd|  t d	| |< | S )a  Check the eigenvalues of a positive semidefinite (PSD) matrix.

    Checks the provided array of PSD matrix eigenvalues for numerical or
    conditioning issues and returns a fixed validated version. This method
    should typically be used if the PSD matrix is user-provided (e.g. a
    Gram matrix) or computed using a user-provided dissimilarity metric
    (e.g. kernel function), or if the decomposition process uses approximation
    methods (randomized SVD, etc.).

    It checks for three things:

    - that there are no significant imaginary parts in eigenvalues (more than
      1e-5 times the maximum real part). If this check fails, it raises a
      ``ValueError``. Otherwise all non-significant imaginary parts that may
      remain are set to zero. This operation is traced with a
      ``PositiveSpectrumWarning`` when ``enable_warnings=True``.

    - that eigenvalues are not all negative. If this check fails, it raises a
      ``ValueError``

    - that there are no significant negative eigenvalues with absolute value
      more than 1e-10 (1e-6) and more than 1e-5 (5e-3) times the largest
      positive eigenvalue in double (simple) precision. If this check fails,
      it raises a ``ValueError``. Otherwise all negative eigenvalues that may
      remain are set to zero. This operation is traced with a
      ``PositiveSpectrumWarning`` when ``enable_warnings=True``.

    Finally, all the positive eigenvalues that are too small (with a value
    smaller than the maximum eigenvalue multiplied by 1e-12 (2e-7)) are set to
    zero. This operation is traced with a ``PositiveSpectrumWarning`` when
    ``enable_warnings=True``.

    Parameters
    ----------
    lambdas : array-like of shape (n_eigenvalues,)
        Array of eigenvalues to check / fix.

    enable_warnings : bool, default=False
        When this is set to ``True``, a ``PositiveSpectrumWarning`` will be
        raised when there are imaginary parts, negative eigenvalues, or
        extremely small non-zero eigenvalues. Otherwise no warning will be
        raised. In both cases, imaginary parts, negative eigenvalues, and
        extremely small non-zero eigenvalues will be set to zero.

    Returns
    -------
    lambdas_fixed : ndarray of shape (n_eigenvalues,)
        A fixed validated copy of the array of eigenvalues.

    Examples
    --------
    >>> from sklearn.utils.validation import _check_psd_eigenvalues
    >>> _check_psd_eigenvalues([1, 2])      # nominal case
    array([1, 2])
    >>> _check_psd_eigenvalues([5, 5j])     # significant imag part
    Traceback (most recent call last):
        ...
    ValueError: There are significant imaginary parts in eigenvalues (1
        of the maximum real part). Either the matrix is not PSD, or there was
        an issue while computing the eigendecomposition of the matrix.
    >>> _check_psd_eigenvalues([5, 5e-5j])  # insignificant imag part
    array([5., 0.])
    >>> _check_psd_eigenvalues([-5, -1])    # all negative
    Traceback (most recent call last):
        ...
    ValueError: All eigenvalues are negative (maximum is -1). Either the
        matrix is not PSD, or there was an issue while computing the
        eigendecomposition of the matrix.
    >>> _check_psd_eigenvalues([5, -1])     # significant negative
    Traceback (most recent call last):
        ...
    ValueError: There are significant negative eigenvalues (0.2 of the
        maximum positive). Either the matrix is not PSD, or there was an issue
        while computing the eigendecomposition of the matrix.
    >>> _check_psd_eigenvalues([5, -5e-5])  # insignificant negative
    array([5., 0.])
    >>> _check_psd_eigenvalues([5, 4e-12])  # bad conditioning (too small)
    array([5., 0.])

    gh㈵>g{Gzt?g|=gư>g-q=gH׊>zThere are significant imaginary parts in eigenvalues (%g of the maximum real part). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix.zThere are imaginary parts in eigenvalues (%g of the maximum real part). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. Only the real parts will be kept.r   zAll eigenvalues are negative (maximum is %g). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix.zThere are significant negative eigenvalues (%g of the maximum positive). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix.zThere are negative eigenvalues (%g of the maximum positive). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. Negative eigenvalues will be replaced with 0.zBadly conditioned PSD matrix spectrum: the largest eigenvalue is more than %g times the smallest. Small eigenvalues will be replaced with 0.r   )r6   r   r7   rS   Zisrealr<   r   imagmaxrealr=   r   r   r   r   r;   )ZlambdasZenable_warningsZis_double_precisionZsignificant_imag_ratioZsignificant_neg_ratioZsignificant_neg_valueZsmall_pos_ratioZmax_imag_absZmax_real_absZmax_eigZmin_eigZtoo_small_lambdasr   r   r   _check_psd_eigenvalues9  s\    R





r   c             C   s   t |}|dk	r&|tjtjgkr&tj}| dkr>tj||d} nxt| tjr\tj|| |d} nZ|dkrptjtjg}t	| dd|d|d} | j
dkrtd| j|fkrtd| j|f| S )	a	  Validate sample weights.

    Note that passing sample_weight=None will output an array of ones.
    Therefore, in some cases, you may want to protect the call with:
    if sample_weight is not None:
        sample_weight = _check_sample_weight(...)

    Parameters
    ----------
    sample_weight : {ndarray, Number or None}, shape (n_samples,)
       Input sample weights.

    X : {ndarray, list, sparse matrix}
        Input data.

    dtype : dtype, default=None
       dtype of the validated `sample_weight`.
       If None, and the input `sample_weight` is an array, the dtype of the
       input is preserved; otherwise an array with the default numpy dtype
       is be allocated.  If `dtype` is not one of `float32`, `float64`,
       `None`, the output will be of dtype `float64`.

    copy : bool, default=False
        If True, a copy of sample_weight will be created.

    Returns
    -------
    sample_weight : ndarray of shape (n_samples,)
       Validated sample weight. It is guaranteed to be "C" contiguous.
    N)r7   FrN   )rK   rL   r7   r   rF   r   z)Sample weights must be 1D array or scalarz'sample_weight.shape == {}, expected {}!)rs   r6   rT   rS   ZonesrP   rq   NumberfullrR   r   r=   rZ   r   )Zsample_weightr>   r7   rF   r   r   r   r   _check_sample_weight  s.    
r   Hz>&.>c             C   s   t | rjt |rj|  } | }|   |  t| j|joht| j|johtj| j	|j	||dS t | st |stj| |||dS t
ddS )aC  Check allclose for sparse and dense data.

    Both x and y need to be either sparse or dense, they
    can't be mixed.

    Parameters
    ----------
    x : {array-like, sparse matrix}
        First array to compare.

    y : {array-like, sparse matrix}
        Second array to compare.

    rtol : float, default=1e-7
        Relative tolerance; see numpy.allclose.

    atol : float, default=1e-9
        absolute tolerance; see numpy.allclose. Note that the default here is
        more tolerant than the default for numpy.testing.assert_allclose, where
        atol=0.
    )rtolr   zFCan only compare two sparse matrices, not a sparse matrix and an arrayN)rB   rC   r   Zsum_duplicatesr6   array_equalr   r   r   rD   r=   )r]   r   r   r   r   r   r   _allclose_dense_sparse&  s    r   c             C   sj   ddl m} i }xT| D ]H\}}t|r:t|t| krD|||< qt|||< ||| |||< qW |S )a   Check and validate the parameters passed during `fit`.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data array.

    fit_params : dict
        Dictionary containing the parameters passed at fit.

    indices : array-like of shape (n_samples,), default=None
        Indices to be selected if the parameter has the same size as `X`.

    Returns
    -------
    fit_params_validated : dict
        Validated parameters. We ensure that the values support indexing.
    r   )_safe_indexing)r   r   r(   r^   rs   r   )r>   Z
fit_paramsr   r   Zfit_params_validatedZ	param_keyZparam_valuer   r   r   _check_fit_paramsM  s    
r   c             C   s   d}t | drtj| jtd}|dks2t|dkr6dS tdd tdd |D D }t|dks||d d	s|d d
kst	
d| dt dS |d d
kr|S dS )af  Get feature names from X.

    Support for other array containers should place its implementation here.

    Parameters
    ----------
    X : {ndarray, dataframe} of shape (n_samples, n_features)
        Array container to extract feature names.

        - pandas dataframe : The columns will be considered to be feature
          names. If the dataframe contains non-string feature names, `None` is
          returned.
        - All other array containers will return `None`.

    Returns
    -------
    names: ndarray or None
        Feature names of `X`. Unrecognized array containers will return `None`.
    Ncolumns)r7   r   c             s   s   | ]}|j V  qd S )N)rc   )r   tr   r   r   r     s    z%_get_feature_names.<locals>.<genexpr>c             s   s   | ]}t |V  qd S )N)ra   )r   r   r   r   r   r     s    r   rz   rf   zVFeature names only support names that are all strings. Got feature names with dtypes: z!. An error will be raised in 1.2.)r\   r6   re   r   r4   r   sortedr   r   r   r   r   )r>   Zfeature_namestypesr   r   r   _get_feature_namesu  s    
 &
r  c             C   s   t | dd}t | dd}|dk	rztj|td}|dk	rJt||sJtd|dk	rvt||krvtd| dt| |S |dk	r|S |dkrtdtjd	d
 t|D tdS )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 names are generated: `[x0, x1, ..., x(n_features_in_)]`.
        - If `input_features` is an array-like, then `input_features` must
            match `feature_names_in_` if `feature_names_in_` is defined.

    Returns
    -------
    feature_names_in : ndarray of str
        Feature names in.
    feature_names_in_Nn_features_in_)r7   z0input_features is not equal to feature_names_in_z?input_features should have length equal to number of features (z), got z7Unable to generate feature names without n_features_in_c             S   s   g | ]}d | qS )r]   r   )r   r   r   r   r   r     s    z+_check_feature_names_in.<locals>.<listcomp>)r   r6   re   r4   r   r=   r   range)r   Zinput_featuresr  r  r   r   r   _check_feature_names_in  s     r  )N)FN)F)F)F)FF)N)F)NF)r   r   )N)N)A__doc__	functoolsr   r   rq   r   numpyr6   Zscipy.sparser   rB   inspectr   r   r   Znumpy.core.numericr   rw   
contextlibr   fixesr	   r
   r   r   r5   
exceptionsr   r   r   rS   rT   Zfloat16ZFLOAT_DTYPESr0   rA   rE   rX   r^   rn   rs   ry   r~   r   r   r   r   rR   r   r   r   r   r   r   r   r<   r   r   r   r   r   r   r   r  r  r   r   r   r   <module>   s   6
#;5#f  A
}
)=H N
 .
@
'
(0