
    0Ph0                        d Z ddlZddl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
Z
ddlZddlZddlZddlZddlZddlZddlmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lm Z m!Z!m"Z"m#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.m/Z/ ddl0Z0ddl1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZD g dZEejF        jG        ZGdeHfdZI G d d          ZJ	 dGdZ*dHdZKdIdZLd ZM	  e8d           dZNn# eO$ r dZNY nw xY w	 ddlPZPePjQ        R                    e:d !          ZSePjQ        T                     e<            d"!          ZUePjQ        R                    e$jV        jW         d#!          ZXePjQ        R                    eN d$!          ZYePjQ        R                    ejZ        d%k    d&!          Z[ePjQ        R                     eM             d'!          Z\n# eO$ r Y nw xY wd( Z]dJd)Z^ G d* d+          Z_dKd-Z`dJd.Zad/ ZbdLd0Zcd1 Zdd2 Zed3 Zf	 dMd4Zg	 	 	 	 	 	 	 dNd5ZhdOd8Zi	 	 	 	 dPd9ZjdQd:Zk G d; d<ejl                  Zm G d= d>          Zn G d? d@          Zo G dA dB          ZpdC ZqdD ZrdE ZsdF ZtdS )RzTesting utilities.    N)defaultdict
namedtuple)Iterable)	dataclass)context_diffwraps)	signature)chaingroupby)STDOUTCalledProcessErrorTimeoutExpiredcheck_output)assert_allclose)assert_almost_equalassert_array_almost_equalassert_array_equalassert_array_less)ClassifierTagsRegressorTagsTags
TargetTagsTransformerTags)_check_array_api_dispatch)	_IS_32BITVisibleDeprecationWarning#_in_unstable_openblas_configurationparse_version
sp_version)check_classification_targets)check_arraycheck_is_fitted	check_X_y)r   r   r   r   r   'assert_run_python_script_without_outputSkipTestc                    t          | t                    r?t          | t                    r*| j        }t          d                    |                    t          |           r t          |          |           S t          |          S )a   Context manager and decorator to ignore warnings.

    Note: Using this (in both variants) will clear all warnings
    from all python modules loaded. In case you need to test
    cross-module-warning-logging, this is not your tool of choice.

    Parameters
    ----------
    obj : callable, default=None
        callable where you want to ignore the warnings.
    category : warning class, default=Warning
        The category to filter. If Warning, all categories will be muted.

    Examples
    --------
    >>> import warnings
    >>> from sklearn.utils._testing import ignore_warnings
    >>> with ignore_warnings():
    ...     warnings.warn('buhuhuhu')

    >>> def nasty_warn():
    ...     warnings.warn('buhuhuhu')
    ...     print(42)

    >>> ignore_warnings(nasty_warn)()
    42
    z'obj' should be a callable where you want to ignore warnings. You passed a warning class instead: 'obj={warning_name}'. If you want to pass a warning class to ignore_warnings, you should use 'category={warning_name}')warning_namecategory)	
isinstancetype
issubclassWarning__name__
ValueErrorformatcallable_IgnoreWarnings)objr*   r(   s      V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/utils/_testing.pyignore_warningsr6   L   s    8 #t 2C!9!9 2 |7 8>v<v7X7X	
 
 	
 
# 21111#6661111    c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )r3   at  Improved and simplified Python warnings context manager and decorator.

    This class allows the user to ignore the warnings raised by a function.
    Copied from Python 2.7.5 and modified as required.

    Parameters
    ----------
    category : tuple of warning class, default=Warning
        The category to filter. By default, all the categories will be muted.

    c                 l    d| _         t          j        d         | _        d| _        g | _        || _        d S )NTwarningsF)_recordsysmodules_module_enteredlogr*   selfr*   s     r5   __init__z_IgnoreWarnings.__init__   s0    {:. r7   c                 @     t                     fd            }|S )z<Decorator to catch and hide warnings without visual nesting.c                      t          j                    5  t          j        dj                    | i |cd d d            S # 1 swxY w Y   d S )Nignore)r:   catch_warningssimplefilterr*   )argskwargsfnrB   s     r5   wrapperz)_IgnoreWarnings.__call__.<locals>.wrapper   s    (** + +%h>>>r4*6**+ + + + + + + + + + + + + + + + + +s   "AAAr   )rB   rK   rL   s   `` r5   __call__z_IgnoreWarnings.__call__   s;     
r	+ 	+ 	+ 	+ 	+ 
	+
 r7   c                    g }| j         r|                    d           | j        t          j        d         ur|                    d| j        z             t          |           j        }|dd                    |          dS )Nzrecord=Truer:   z	module=%r(z, ))r;   appendr>   r<   r=   r,   r/   join)rB   rI   names      r5   __repr__z_IgnoreWarnings.__repr__   s{    < 	'KK&&&<s{:666KKdl2333Dzz"44411r7   c                     | j         rt          d| z            d| _         | j        j        | _        | j        d d          | j        _        | j        j        | _        t          j        d| j	                   d S )NzCannot enter %r twiceTrF   )
r?   RuntimeErrorr>   filters_filtersshowwarning_showwarningr:   rH   r*   rB   s    r5   	__enter__z_IgnoreWarnings.__enter__   sp    = 	?6=>>>,#}QQQ/ L4h66666r7   c                     | j         st          d| z            | j        | j        _        | j        | j        _        g | j        d d <   d S )Nz%Cannot exit %r without entering first)r?   rV   rX   r>   rW   rZ   rY   r@   )rB   exc_infos     r5   __exit__z_IgnoreWarnings.__exit__   sM    } 	OFMNNN#}#'#4 r7   N)	r/   
__module____qualname____doc__rC   rM   rT   r\   r_    r7   r5   r3   r3   x   si        
 
! ! !	 	 	2 2 27 7 7    r7   r3           T c           	          g }t          j        |           t          j        |          }} | j        |j        g}|d |D             }t          |          }t	          | ||||||           dS )au  dtype-aware variant of numpy.testing.assert_allclose

    This variant introspects the least precise floating point dtype
    in the input argument and automatically sets the relative tolerance
    parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
    in scikit-learn).

    `atol` is always left to 0. by default. It should be adjusted manually
    to an assertion-specific value in case there are null values expected
    in `desired`.

    The aggregate tolerance is `atol + rtol * abs(desired)`.

    Parameters
    ----------
    actual : array_like
        Array obtained.
    desired : array_like
        Array desired.
    rtol : float, optional, default=None
        Relative tolerance.
        If None, it is set based on the provided arrays' dtypes.
    atol : float, optional, default=0.
        Absolute tolerance.
    equal_nan : bool, optional, default=True
        If True, NaNs will compare equal.
    err_msg : str, optional, default=''
        The error message to be printed in case of failure.
    verbose : bool, optional, default=True
        If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
        If actual and desired are not equal up to specified precision.

    See Also
    --------
    numpy.testing.assert_allclose

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.utils._testing import assert_allclose
    >>> x = [1e-5, 1e-3, 1e-1]
    >>> y = np.arccos(np.cos(x))
    >>> assert_allclose(x, y, rtol=1e-5, atol=0)
    >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
    >>> assert_allclose(a, 1e-5)
    Nc                 6    g | ]}|t           j        k    rd ndS )g-C6?Hz>)npfloat32).0dtypes     r5   
<listcomp>z#assert_allclose.<locals>.<listcomp>   s(    KKK5"*,,$KKKr7   )rtolatol	equal_nanerr_msgverbose)ri   
asanyarrayrl   maxnp_assert_allclose)	actualdesiredrn   ro   rp   rq   rr   dtypesrtolss	            r5   r   r      s    j FmF++R]7-C-CGFlGM*F|KKFKKK5zz     r7   rh   &.>c                    t           j                            |           rt           j                            |          r|                                 } |                                }|                                  |                                 t          | j        |j        |           t          | j        |j        |           t          | j	        |j	        |||           dS t           j                            |           s5t           j                            |          st          | ||||           dS t          d          )a  Assert 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-07
        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.

    err_msg : str, default=''
        Error message to raise.
    )rq   )rn   ro   rq   zGCan only compare two sparse matrices, not a sparse matrix and an array.N)spsparseissparsetocsrsum_duplicatesr   indicesindptrr   datar0   )xyrn   ro   rq   s        r5   assert_allclose_dense_sparser      s)   2 
y! 
!3!3A!6!6 
GGIIGGII		19aiAAAA18QXw????TgNNNNNNY"" 
29+=+=a+@+@ 
14dGDDDDDDU
 
 	
r7   c                 b    d|                                  v r|                     |           dS dS )a~  Set random state of an estimator if it has the `random_state` param.

    Parameters
    ----------
    estimator : object
        The estimator.
    random_state : int, RandomState instance or None, default=0
        Pseudo random number generator state.
        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.
    random_state)r   N)
get_params
set_params)	estimatorr   s     r5   set_random_stater   $  s@     --////,77777 0/r7   c                  @    	 dd l } dS # t          t          f$ r Y dS w xY w)Nr   TF)numpydocImportErrorAssertionError)r   s    r5   _is_numpydocr   4  s@     t (   uus    Fzskipped on 32bit platforms)reasonz+OpenBLAS is unstable for this configurationzjoblib is in serial modezErequires array_api_compat installed and a new enough version of NumPydarwinz)Possible multi-process bug with some BLASz+numpydoc is required to test the docstringsc                  ~    t          t          j                            dd                    rt	          d          d S )NSKLEARN_SKIP_NETWORK_TESTSr   z-Text tutorial requires large dataset download)intosenvirongetr&   rc   r7   r5   check_skip_networkr   q  s?    
2:>>6::;; HFGGGH Hr7   c                     	 t           j                            |           rt          j        |            dS dS # t
          $ r  |rt          j        d| z             Y dS Y dS w xY w)zuUtility function to cleanup a temporary folder if still existing.

    Copy from joblib.pool (for independence).
    z$Could not delete temporary folder %sN)r   pathexistsshutilrmtreeOSErrorr:   warn)folder_pathr   s     r5   _delete_folderr   v  s    
P7>>+&& 	' M+&&&&&	' 	'  P P P 	PM@;NOOOOOO	P 	P 	PPs   39 #A#"A#c                   &    e Zd ZdZddZd Zd ZdS )
TempMemmapzM
    Parameters
    ----------
    data
    mmap_mode : str, default='r'
    rc                 "    || _         || _        d S N)	mmap_moder   )rB   r   r   s      r5   rC   zTempMemmap.__init__  s    "			r7   c                 N    t          | j        | j        d          \  }| _        |S )NT)r   return_folder)create_memmap_backed_datar   r   temp_folder)rB   data_read_onlys     r5   r\   zTempMemmap.__enter__  s1    +DIt,
 ,
 ,
(( r7   c                 .    t          | j                   d S r   )r   r   )rB   exc_typeexc_valexc_tbs       r5   r_   zTempMemmap.__exit__  s    t'(((((r7   N)r   )r/   r`   ra   rb   rC   r\   r_   rc   r7   r5   r   r     sP              ) ) ) ) )r7   r   r   c                    t          j        d          }t          j        t	          j        t          |d                     t          j        |d          }t          j
        | |           t          j        ||          }|s|n||f}|S )zv
    Parameters
    ----------
    data
    mmap_mode : str, default='r'
    return_folder :  bool, default=False
    sklearn_testing_)prefixT)r   zdata.pkl)r   )tempfilemkdtempatexitregister	functoolspartialr   oprR   joblibdumpload)r   r   r   r   filenamememmap_backed_dataresults          r5   r   r     s     "*<===K
OI%nkMMMNNNw{J//H
KhXCCC"/V6H+5V  Mr7   c                    	 t          |           j        }n# t          $ r g cY S w xY wd |                                D             }|r7d |                                D             }t          |          dk    rd}||fS |S )z!Helper to get function arguments.c                 B    g | ]\  }}|j         |j        |j        fv|S rc   )kindVAR_POSITIONALVAR_KEYWORD)rk   keyparams      r5   rm   z_get_args.<locals>.<listcomp>  s>       C:e2E4EFFF 	FFFr7   c                 <    g | ]}|j         |j        k    |j        S rc   )r   r   rS   )rk   r   s     r5   rm   z_get_args.<locals>.<listcomp>  s4     
 
 
zU111 J111r7   r   N)r
   
parametersr0   itemsvalueslen)functionvarargsparamsrI   s       r5   	_get_argsr     s    8$$/   			  ,,..  D
  

 

 
 

 w<<1GW}s    &&c                 H   g }t          j        |           }|r|                    |j                   | j        }|| j        k    r0|                    |d|                    d                              |                    | j                   d                    |          S )zGet function full name.

    Parameters
    ----------
    func : callable
        The function object.

    Returns
    -------
    name : str
        The function name.
    N.)inspect	getmodulerQ   r/   ra   findrR   )funcpartsmodulequalnames       r5   _get_func_namer     s     Et$$F &V_%%% H4=  X2c 2 223444	LL88E??r7   c           	      ^
   ddl m} g }g nt          |           }|                    d          r|                    d          r|S t	          j        |           r|S |                    d          d         dv r|S |                    d          d	         d
k    r|S t          t          fdt          |                               }t          |          dk    r!|d         dk    r|                    d           |Vg }t          j        d          5  t          j        dt                     	 |                    |           }n# t          $ r}dt#          |          v rIt#          |                              d          dd         }	|d| g|	z   z  }|cY d}~cddd           S |                    t#          |                     Y d}~nAd}~wt&          $ r1}||dz   t#          |          z   gz  }|cY d}~cddd           S d}~ww xY wddd           n# 1 swxY w Y   t          |          rt)          d|d|d                   g }
|d         D ]\  }}}|                                sd|v rD|d|                    d                   dd                                         r||d|z  z   gz  }nE|                                                    d          r||d|                                z  z   gz  }d|vrA|
                    |                    d          d                             d                     t          |          dk    r|S t          t          fd|
                    }
g }	t5          t7          t          |
          t          |                              D ]1}||         |
|         k    r|	d|d||         d |
|         gz  }	 n2t          |          t          |
          k    r|	d!|t          |
                   z  gz  }	n<t          |          t          |
          k     r|	d"|
t          |                   z  gz  }	t          |	          dk    rg S ddl}ddl}|                    |
                                          }|                    |                                          }|	d#gz  }	|	                     d$ |!                    ||          D                        |                     |	           d|z   g|z   }|S )%ar  Helper to check docstring.

    Parameters
    ----------
    func : callable
        The function object to test.
    doc : str, default=None
        Docstring if it is passed manually to the test.
    ignore : list, default=None
        Parameters to ignore.

    Returns
    -------
    incorrect : list
        A list of string describing the incorrect results.
    r   )	docscrapeNzsklearn.zsklearn.externalsr   )setup_moduleteardown_module   estimator_checksc                     | vS r   rc   r   rF   s    r5   <lambda>z,check_docstring_parameters.<locals>.<lambda>
  s    AVO r7   rB   T)recorderrorz"potentially wrong underline length
   zIn function: z parsing error: z
Error for z:

Parameters:z9 There was no space between the param name and colon (%r)z6 Parameter %r has an empty type spec. Remove the colon*z` c                     | vS r   rc   r   s    r5   r   z,check_docstring_parameters.<locals>.<lambda>@  s    q r7   z\There's a parameter name mismatch in function docstring w.r.t. function signature, at index z diff: z != zbParameters in function docstring have less items w.r.t. function signature, first missing item: %sz`Parameters in function docstring have more items w.r.t. function signature, first extra item: %sz
Full diff:c              3   >   K   | ]}|                                 V  d S r   )striprk   lines     r5   	<genexpr>z-check_docstring_parameters.<locals>.<genexpr>k  s>         	

     r7   )"r   r   r   
startswithr   isdatadescriptorsplitlistfilterr   r   remover:   rG   rH   UserWarningFunctionDocstrrQ   	ExceptionrV   r   indexrstripendswithlstriprangemindifflibpprintpformat
splitlinesextendndiff)r   docrF   r   	incorrect	func_nameparam_signaturerecordsexpmessage
param_docsrS   type_definition	param_docir  r  param_docs_formattedparam_signature_formatteds     `                r5   check_docstring_parametersr    s   " #"""""I>RRvFt$$I
++ y/C/C0 0  %% sB#FFFsA"4446";";";";Yt__MMNNO
?aOA$6&$@$@v&&& {$D111 	! 	!!';777!++D11 ) ) )73s88CC "#hhnnT222A26G"=)"="=!>!HHI$$$$$$	! 	! 	! 	! 	! 	! 	! 	! s3xx(((((((( ! ! !i*<<s3xxGHH	      	! 	! 	! 	! 	! 	! 	! 	!!	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!  w<< 	N,iiiLMMMJ,/,= > >(oy$$&& 	d{{t$5djjoo$56rss;AACC{QTXXY 		 '',, N{{}}&& 	 d??djjooa066t<<=== 9~~ f6666
CCDDJ G3s:O(<(<==>>  1A..G &'QQ(:(:(:JqMMK G
 E / ?c*oo--:c*oo./
 	
 
_		J	/	/8_--./
 	
 7||q	NNNMMM!>>*55@@BB & ? ? J J L L~GNN  MM";=QRR     
 W !9,-	9Isg   H&8EH&
HAG H!H&2"GH&H&H HH&HH&&H*-H*c                 R    |j         dur| |j         vrdS |j        | |j        v rdS dS )z7Helper to check if item should be included in checking.TF)includeexclude)	item_namerI   s     r5   _check_item_includedr  x  s>    |4IT\$A$Au|I$=$=u4r7   c                     |                      d          rdS |                      d          rdS |                      d          rdS |                      d          rdS dS )z,Key for grouping output from `context_diff`.z  z- z+ z! N)r   )r   s    r5   	_diff_keyr    sk    t t			 t			 t			 t4r7   c                 b   d}d}g }|                                  D ]\  }}|s|s||z  }|                    |           t          t          |                                |                                t          |          t          |          d                    }|d                    |dd                   z  }t          |dd         t                    D ]K\  }}||dd                    |          z   z  }#|d|z   d                    d	 |D                       z   z  }L|d
z  }|S )a  Get message showing the difference between type/desc docstrings of all objects.

    `docstrings_grouped` keys should be the type/desc docstrings and values are a list
    of objects with that docstring. Objects with the same type/desc docstring are
    thus grouped together.
    re      )fromfiletofilenNr   )r   r    c              3   *   K   | ]}|d d         V  dS )r   Nrc   )rk   words     r5   r   z _get_diff_msg.<locals>.<genexpr>  s*      3O3ODH3O3O3O3O3O3Or7   z

)	r   r  r   r   r   r   rR   r   r  )docstrings_groupedmsg_diffref_str	ref_group	docstringgroupdiffstarts           r5   _get_diff_msgr/    s[    HGI.4466  	5 	$y 	$y GU###!!Y5zz  
 
 	BGGT"1"X'''#DH)<<< 	P 	PLE5}D499U#3#333D5L3883O3O3O3O3O+O+OOOFOr7   c                 `   g }|                                  D ]v\  }}t          d |                                D                       |k     r|                    |           K|dk    r|rg }|                                 D ]/\  }	}
t	          j        ||	          s|                    |
           0|r8t          j        d|dd          d| d| d| d		          }t          |          t          |                                          d
k    r}t          |          }d                    d |                                D                       }t          j        d| d|dd          d| d| d	          }||z  }t          |          x|rt          j        d| d| d           dS dS )zHelper to check docstring consistency of all `items_docs`.

    If item is not present in all objects, checking is skipped and warning raised.
    If `regex` provided, match descriptions to all descriptions.
    c                 ,    g | ]}t          |          S rc   )r   )rk   objss     r5   rm   z,_check_consistency_items.<locals>.<listcomp>  s    BBBdD		BBBr7   descriptionzThe description of Nr   z 'z' in z' does not match 'descr_regex_pattern': r$     z and c              3   4   K   | ]}t          |          V  d S r   )r   )rk   r,  s     r5   r   z+_check_consistency_items.<locals>.<genexpr>  s9       & &$E

& & & & & &r7   zThe z of z' is inconsistent between r   zChecking was skipped for z: z' as they were not found in all objects.)r   sumr   rQ   researchr  textwrapfillr   r   keysr/  rR   r:   r   )
items_docstype_or_descsection	n_objectsdescr_regex_patternskippedr  r'  not_matchedr+  r,  msgr(  
obj_groupss                 r5   _check_consistency_itemsrE    s|    G)3)9)9);); & &%	%BB&8&?&?&A&ABBBCCiOONN9%%%%]**/B*K$6$<$<$>$> . . 	5y!4i@@ .&&u--- *mU'#2#, U U) U U+ U U>QU U U  %S)))* #((**++a//$%788H  & &(:(A(A(C(C& & &  J -)| ) )" ) ) ) )%) ) ) C 8OC %%% 0  
( ( (7 ( ( (	
 	
 	
 	
 	

 
r7   c           	      n   ddl m} t          dg d          fd}	i  |	||dd           |	||dd	           |	||d
d          }
t                      }| D ]}t	          j        |          s(t	          j        |          st	          j        |          r& |t	          j        |                    ||j	        <   dt          dt          |           d          t          |           }|
                                D ]1\  }}t          d           }t          d           }|                                D ]\  }}||         D ]\  }}}t          ||          rd                    |                                                                          }d                    t'          j        d |D                                 }||         |                             |           ||         |                             |           Ìt-          |d||           t-          |d|||           3dS )aX  Check consistency between docstring parameters/attributes/returns of objects.

    Checks if parameters/attributes/returns have the same type specification and
    description (ignoring whitespace) across `objects`. Intended to be used for
    related classes/functions/data descriptors.

    Entries that do not appear across all `objects` are ignored.

    Parameters
    ----------
    objects : list of {classes, functions, data descriptors}
        Objects to check.
        Objects may be classes, functions or data descriptors with docstrings that
        can be parsed by numpydoc.

    include_params : list of str or bool, default=False
        List of parameters to be included. If True, all parameters are included,
        if False, checking is skipped for parameters.
        Can only be set if `exclude_params` is None.

    exclude_params : list of str or None, default=None
        List of parameters to be excluded. If None, no parameters are excluded.
        Can only be set if `include_params` is True.

    include_attrs : list of str or bool, default=False
        List of attributes to be included. If True, all attributes are included,
        if False, checking is skipped for attributes.
        Can only be set if `exclude_attrs` is None.

    exclude_attrs : list of str or None, default=None
        List of attributes to be excluded. If None, no attributes are excluded.
        Can only be set if `include_attrs` is True.

    include_returns : list of str or bool, default=False
        List of returns to be included. If True, all returns are included,
        if False, checking is skipped for returns.
        Can only be set if `exclude_returns` is None.

    exclude_returns : list of str or None, default=None
        List of returns to be excluded. If None, no returns are excluded.
        Can only be set if `include_returns` is True.

    descr_regex_pattern : str, default=None
        Regular expression to match to all descriptions of included
        parameters/attributes/returns. If None, will revert to default behavior
        of comparing descriptions between objects.

    Examples
    --------
    >>> from sklearn.metrics import (accuracy_score, classification_report,
    ... mean_absolute_error, mean_squared_error, median_absolute_error)
    >>> from sklearn.utils._testing import assert_docstring_consistency
    ... # doctest: +SKIP
    >>> assert_docstring_consistency([mean_absolute_error, mean_squared_error],
    ... include_params=['y_true', 'y_pred', 'sample_weight'])  # doctest: +SKIP
    >>> assert_docstring_consistency([median_absolute_error, mean_squared_error],
    ... include_params=True)  # doctest: +SKIP
    >>> assert_docstring_consistency([accuracy_score, classification_report],
    ... include_params=["y_true"],
    ... descr_regex_pattern=r"Ground truth \(correct\) (labels|target values)")
    ... # doctest: +SKIP
    r   )NumpyDocStringrI   )r  r  arg_namec                 f    |r| durt          d| d| d          | du ri S | | ||          iS )NTzThe 'exclude_z-' argument can be set only when the 'include_z' argument is True.F)	TypeError)r  r  rH  section_nameArgss       r5   _create_argsz2assert_docstring_consistency.<locals>._create_args*  su     	wd**: : :$: : :   eIdd7GX>>??r7   r   r   attrs
AttributesreturnsReturnszDAll 'objects' must be one of: function, class or descriptor, got a: r   c                  *    t          t                    S r   r   r   rc   r7   r5   r   z.assert_docstring_consistency.<locals>.<lambda>J      T):): r7   c                  *    t          t                    S r   rS  rc   r7   r5   r   z.assert_docstring_consistency.<locals>.<lambda>K  rT  r7   r$  c              3   >   K   | ]}|                                 V  d S r   )r   r   s     r5   r   z/assert_docstring_consistency.<locals>.<genexpr>Q  s*      7V7V

7V7V7V7V7V7Vr7   ztype specificationr3  )r@  N)numpydoc.docscraperG  r   dictr   r   
isfunctionisclassgetdocr/   rJ  r,   r   r   r   r  rR   r   r   r   from_iterablerQ   rE  )objectsinclude_paramsexclude_paramsinclude_attrsexclude_attrsinclude_returnsexclude_returnsr@  rG  rM  section_argsobjects_docr4   r?  r>  rI   
type_items
desc_itemsobj_nameobj_docr  type_defdescrL  s                          @r5   assert_docstring_consistencyrl    s   P 211111f@@@AAD@ @ @ @ @
,~~x
N
N
,}mWl
K
K ,I
N
NL &&K  $S))
	!#&&
	 s##
	
 )7w~c7J7J(K(KK%%'s))' ' '  
 GI%++-- 
 
 !:!:;;
 !:!:;;
!,!2!2!4!4 	A 	AHg-4W-= A A)	8T'	488 A"xx(8(8(>(>(@(@AAH88E$77V7VQU7V7V7V$V$VWWDy)(3::8DDDy)$/66x@@@A 	!-A7IVVV  3	
 	
 	
 	
 	

 
r7   .+<   c                    t          j        d          \  }}t          j        |           	 t	          |d          5 }|                    |                     d                     ddd           n# 1 swxY w Y   t          j        |g}t          j
        t          j        t          j        t          j                  d                    }t          j                                        }	 t          j                            ||d         g          |d<   n# t$          $ r ||d<   Y nw xY w|t&          |d}	t          j                            d	          }
|
r|
|	d
         d	<   ||	d<   	 	 t+          |fi |	}n<# t,          $ r/}t/          d|j                            d          z            d}~ww xY w|                    d          }t5          j        ||          r$|dk    rd}nd|}| d|}t9          |          n<# t:          $ r/}t/          d|j                            d          z            d}~ww xY w	 t          j        |           dS # t          j        |           w xY w)a[  Utility to check assertions in an independent Python subprocess.

    The script provided in the source code should return 0 and the stdtout +
    stderr should not match the pattern `pattern`.

    This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle

    Parameters
    ----------
    source_code : str
        The Python source code to execute.
    pattern : str
        Pattern that the stdout + stderr should not match. By default, unless
        stdout + stderr are both empty, an error will be raised.
    timeout : int, default=60
        Time in seconds before timeout.
    z_src_test_sklearn.py)suffixwbzutf-8Nz..
PYTHONPATH)cwdstderrenvCOVERAGE_PROCESS_STARTru  timeoutzscript errored with output:
%srm  zExpected no outputz%The output was not supposed to match z$, got the following output instead: z!script timeout, output so far:
%s)r   mkstempr   closeopenwriteencoder<   
executabler   normpathrR   dirnamesklearn__file__r   copypathsepKeyErrorr   r   r   r   rV   outputdecoder7  r8  r   r   unlink)source_codepatternrw  fdsource_filefcmdrs  ru  rJ   coverage_rcouteexpectationr  s                  r5   r%   r%   `  s   $ &.DEEEOBHRLLL'+t$$ 	1GGK&&w//000	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1~{+k"'"*W-=">">EEFFjoo	$ "
c,6G0H I IC 	$ 	$ 	$ #C	$s;;jnn%=>> 	B6AF5M23#y	"311&11%   "58P8PP  
 **W%%Cy#&& .d??"6KK"U'"U"UK(UUcUU$W---.  	 	 	4qxw7O7OO  	. 		+	+s   I )A3'I 3A77I :A7;A2I .*D I D+(I *D++?I ,E: 9H :
F3*F..F33AH I 
H>*H99H>>I I.c                 \   |dk    r9|t          |           S t          j        | |                                          S |dk    rF|t	          |           S t	          t          j        | |                                                    S |dk    rt          j        | |          S |dv rVt          j        d|          }|                    | ||d	
          }|#|D ] }||                             d          ||<   !|S |dk    rt          j        d|          }	t          j        |           |$d t          j
        d                   D             }fdt          |          D             }
|	j                            |
          }|Zt          |j                  D ]E\  }}||v r<|                    |||                    |                                                    }F|S |dk    rwt          j        d|          }|                    | |d          }|E|D ]B}|                    |                    |                              |j                            }C|S |dk    r-t          j        d|          }|                    | |          S |dk    r,t          j        d|          }|                    |           S |dk    r-t          j        d|          }|                    | |          S |dk    rt1          | d         | d                   S d|v rt2          j                            |           st          j        |           } d|v r1t:          t=          d          k     rt?          | dt:                     |dv r!t2          j                             | |          S |dk    r!t2          j        !                    | |          S |dk    r!t2          j        "                    | |          S |dk    r#t2          j        #                    | |          S dS dS ) a  Convert a given container to a specific array-like with a dtype.

    Parameters
    ----------
    container : array-like
        The container to convert.
    constructor_name : {"list", "tuple", "array", "sparse", "dataframe",             "series", "index", "slice", "sparse_csr", "sparse_csc",             "sparse_csr_array", "sparse_csc_array", "pyarrow", "polars",             "polars_series"}
        The type of the returned container.
    columns_name : index or array-like, default=None
        For pandas container supporting `columns_names`, it will affect
        specific names.
    dtype : dtype, default=None
        Force the dtype of the container. Does not apply to `"slice"`
        container.
    minversion : str, default=None
        Minimum version for package to install.
    categorical_feature_names : list of str, default=None
        List of column names to cast to categorical dtype.

    Returns
    -------
    converted_container
    r   N)rl   tuplearray)pandas	dataframer  )
minversionF)columnsrl   r  r*   pyarrowc                     g | ]}d | S )colrc   )rk   r  s     r5   rm   z&_convert_container.<locals>.<listcomp>  s    EEE!I!IIEEEr7   r4  c                 0    i | ]\  }}|d d |f         S r   rc   )rk   r  rS   r  s      r5   
<dictcomp>z&_convert_container.<locals>.<dictcomp>  s+    IIIgaeAAAqDkIIIr7   polarsrow)schemaorientseriespolars_series)r   r   slicer   r}   z1.8z* is only available with scipy>=1.8.0, got )r}   
sparse_csrsparse_csr_array
sparse_cscsparse_csc_array)$r   ri   asarraytolistr  pytestimportorskip	DataFrameastyper  shape	enumerateTablefrom_pydictcolumn_names
set_columncolumndictionary_encodewith_columnsr  castCategoricalSeriesIndexr  r|   r}   r~   
atleast_2dr    r   r0   
csr_matrix	csr_array
csc_matrix	csc_array)	containerconstructor_namecolumns_namerl   r  categorical_feature_namespdr   col_namepar   col_idxplr  s                @r5   _convert_containerr    s   D 6!!=	??":iu555<<>>>	W	$	$=###IU;;;BBDDEEE	W	$	$z)51111	4	4	4 jAAAiUQVWW$05 G G#)(#3#:#::#F#Fx  	Y	&	& zBBB
9%%EEuU[^/D/DEEELIIII<1H1HIII%%d++$0%.v/B%C%C  !888#..6==+B+B+T+T+V+V F 	X	%	% jAAAiUKK$05 T T,,RVVH-=-=-B-B2>-R-RSS	X	%	% jAAAyy%y000	_	,	, jAAAyy	y***	W	$	$ jAAAxx	x///	W	$	$Yq\9Q<000	%	%	%y!!),, 	1
 i00I&&&:e8L8L+L+L#          7779''	'???!3339&&y&>>>--9''	'???!3339&&y&>>>+ 
&	%( 43r7   c                 &    t          | |||          S )a[  Context manager to ensure exceptions are raised within a code block.

    This is similar to and inspired from pytest.raises, but supports a few
    other cases.

    This is only intended to be used in estimator_checks.py where we don't
    want to use pytest. In the rest of the code base, just use pytest.raises
    instead.

    Parameters
    ----------
    excepted_exc_type : Exception or list of Exception
        The exception that should be raised by the block. If a list, the block
        should raise one of the exceptions.
    match : str or list of str, default=None
        A regex that the exception message should match. If a list, one of
        the entries must match. If None, match isn't enforced.
    may_pass : bool, default=False
        If True, the block is allowed to not raise an exception. Useful in
        cases where some estimators may support a feature but others must
        fail with an appropriate error message. By default, the context
        manager will raise an exception if the block does not raise an
        exception.
    err_msg : str, default=None
        If the context manager fails (e.g. the block fails to raise the
        proper exception, or fails to match), then an AssertionError is
        raised with this message. By default, an AssertionError is raised
        with a default error message (depends on the kind of failure). Use
        this to indicate how users should fix their estimators to pass the
        checks.

    Attributes
    ----------
    raised_and_matched : bool
        True if an exception was raised and a match was found, False otherwise.
    )_Raises)expected_exc_typematchmay_passrq   s       r5   raisesr    s    J $eXw???r7   c                       e Zd Zd Zd ZdS )r  c                     t          |t                    r|n|g| _        t          |t                    r|gn|| _        || _        || _        d| _        d S )NF)r+   r   expected_exc_typesr   matchesr  rq   raised_and_matched)rB   r  r  r  rq   s        r5   rC   z_Raises.__init__5  se     +X66%#$ 	
 #-UC"8"8Cwwe "'r7   c                    )| j         rdS | j        p	d| j         }t          |          t	          fd| j        D                       s| j        t          | j                  dS | j        y| j        p:d                    d                    | j                  t                              }t	          fd| j        D                       st          |          d| _	        dS )NTzDid not raise: c              3   8   K   | ]}t          |          V  d S r   )r-   )rk   expected_typer   s     r5   r   z#_Raises.__exit__.<locals>.<genexpr>K  sA       
 
 x//
 
 
 
 
 
r7   FzIThe error message should contain one of the following patterns:
{}
Got {}r   c              3   \   K   | ]&}t          j        |t                              V  'd S r   )r7  r8  r   )rk   r  	exc_values     r5   r   z#_Raises.__exit__.<locals>.<genexpr>Y  s5      RREryI77RRRRRRr7   )
r  rq   r  r   anyr  r1   rR   r   r  )rB   r   r  _rq   s    ``  r5   r_   z_Raises.__exit__@  s"    } .t,U*UD<S*U*U$W--- 
 
 
 
!%!8
 
 
 
 
 	 |'$T\22	Au<#l ((.tyy/F/FI(W(W  RRRRT\RRRRR =$W--9<&*D#tr7   N)r/   r`   ra   rC   r_   rc   r7   r5   r  r  3  s2        	( 	( 	(    r7   r  c                   F    e Zd ZdZddZddZd Zd Zd Zd	 Z	d
 Z
d ZdS )MinimalClassifiera  Minimal classifier implementation without inheriting from BaseEstimator.

    This estimator should be tested with:

    * `check_estimator` in `test_estimator_checks.py`;
    * within a `Pipeline` in `test_pipeline.py`;
    * within a `SearchCV` in `test_search.py`.
    Nc                     || _         d S r   r   rB   r   s     r5   rC   zMinimalClassifier.__init__j      


r7   Tc                     d| j         iS Nr   r  rB   deeps     r5   r   zMinimalClassifier.get_paramsm      $$r7   c                 \    |                                 D ]\  }}t          | ||           | S r   r   setattrrB   r   r   values       r5   r   zMinimalClassifier.set_paramsp  7     ,,.. 	& 	&JCD#u%%%%r7   c                     t          ||          \  }}t          |           t          j        |d          \  | _        }|                                | _        | S )NT)return_counts)r$   r!   ri   uniqueclasses_argmax_most_frequent_class_idx)rB   Xr   countss       r5   fitzMinimalClassifier.fitu  sQ    A1$Q''' "	!4 @ @ @v(.%r7   c                     t          |            t          |          }|j        d         | j        j        f}t          j        |t
          j                  }d|d d | j        f<   |S )Nr   )r  rl   g      ?)	r#   r"   r  r  sizeri   zerosfloat64r  )rB   r  proba_shapey_probas       r5   predict_probazMinimalClassifier.predict_proba|  sa    NNwqz4=#56(BJ???474001r7   c                 r    |                      |          }|                    d          }| j        |         S )Nr4  )axis)r  r  r  )rB   r  r  y_preds       r5   predictzMinimalClassifier.predict  s5    $$Q''Q''}V$$r7   c                 L    ddl m}  |||                     |                    S )Nr   )accuracy_score)sklearn.metricsr  r  )rB   r  r   r  s       r5   scorezMinimalClassifier.score  s0    222222~aa111r7   c           	      ^    t          dt                      d d t          d                    S )N
classifierTrequiredestimator_typeclassifier_tagsregressor_tagstransformer_tagstarget_tags)r   r   r   r[   s    r5   __sklearn_tags__z"MinimalClassifier.__sklearn_tags__  s9    '*,,!"D111
 
 
 	
r7   r   T)r/   r`   ra   rb   rC   r   r   r  r  r  r  r  rc   r7   r5   r  r  `  s            % % % %  
    % % %
2 2 2

 
 
 
 
r7   r  c                   @    e Zd ZdZddZddZd Zd Zd Zd	 Z	d
 Z
dS )MinimalRegressora  Minimal regressor implementation without inheriting from BaseEstimator.

    This estimator should be tested with:

    * `check_estimator` in `test_estimator_checks.py`;
    * within a `Pipeline` in `test_pipeline.py`;
    * within a `SearchCV` in `test_search.py`.
    Nc                     || _         d S r   r  r  s     r5   rC   zMinimalRegressor.__init__  r  r7   Tc                     d| j         iS r  r  r  s     r5   r   zMinimalRegressor.get_params  r  r7   c                 \    |                                 D ]\  }}t          | ||           | S r   r  r  s       r5   r   zMinimalRegressor.set_params  r  r7   c                 l    t          ||          \  }}d| _        t          j        |          | _        | S NT)r$   
is_fitted_ri   mean_meanrB   r  r   s      r5   r  zMinimalRegressor.fit  s.    A1WQZZ
r7   c                     t          |            t          |          }t          j        |j        d         f          | j        z  S )Nr   )r  )r#   r"   ri   onesr  r  )rB   r  s     r5   r  zMinimalRegressor.predict  s=    NNwagaj]+++dj88r7   c                 L    ddl m}  |||                     |                    S )Nr   )r2_score)r  r   r  )rB   r  r   r   s       r5   r  zMinimalRegressor.score  s0    ,,,,,,x4<<??+++r7   c           	      ^    t          dd t                      d t          d                    S )N	regressorTr  r
  )r   r   r   r[   s    r5   r  z!MinimalRegressor.__sklearn_tags__  s7    & (??!"D111
 
 
 	
r7   r   r  )r/   r`   ra   rb   rC   r   r   r  r  r  r  rc   r7   r5   r  r    s            % % % %  
  9 9 9
, , ,

 
 
 
 
r7   r  c                   F    e Zd ZdZddZddZd ZddZddZdd	Z	d
 Z
dS )MinimalTransformera  Minimal transformer implementation without inheriting from
    BaseEstimator.

    This estimator should be tested with:

    * `check_estimator` in `test_estimator_checks.py`;
    * within a `Pipeline` in `test_pipeline.py`;
    * within a `SearchCV` in `test_search.py`.
    Nc                     || _         d S r   r  r  s     r5   rC   zMinimalTransformer.__init__  r  r7   Tc                     d| j         iS r  r  r  s     r5   r   zMinimalTransformer.get_params  r  r7   c                 \    |                                 D ]\  }}t          | ||           | S r   r  r  s       r5   r   zMinimalTransformer.set_params  r  r7   c                 2    t          |           d| _        | S r  )r"   r  r  s      r5   r  zMinimalTransformer.fit  s    Ar7   c                 B    t          |            t          |          }|S r   )r#   r"   r  s      r5   	transformzMinimalTransformer.transform  s     NNr7   c                 V    |                      ||                              ||          S r   )r  r*  r  s      r5   fit_transformz MinimalTransformer.fit_transform  s$    xx1~~''1---r7   c           	      ^    t          dd d t                      t          d                    S )NtransformerFr  r
  )r   r   r   r[   s    r5   r  z#MinimalTransformer.__sklearn_tags__  s9    ( ,.."E222
 
 
 	
r7   r   r  )r/   r`   ra   rb   rC   r   r   r  r*  r,  r  rc   r7   r5   r$  r$    s            % % % %  
   
   
. . . .
 
 
 
 
r7   r$  c                    	 t          j        |           }n # t          $ r t          |  d          w xY w	 dd l}n# t
          $ r t          d          w xY w|                    |                    d                    }| dk    r3|dk    r-|j        j	        
                                st          d          | dk    r[|dk    rUt          j        d	          d
k    rt          d          |j        j        
                                st          d          n;| dk    r5dd l}|j	        j                                        dk    rt          d          |S )Nz/ is not installed: not checking array_api inputr   z?array_api_compat is not installed: not checking array_api inputr4  torchcudaz2PyTorch test requires cuda, which is not availablempsPYTORCH_ENABLE_MPS_FALLBACK1zHSkipping MPS device test because PYTORCH_ENABLE_MPS_FALLBACK is not set.zXMPS is not available because the current PyTorch install was not built with MPS enabled.cupyz/CuPy test requires cuda, which is not available)	importlibimport_moduleModuleNotFoundErrorr&   array_api_compatr   get_namespacer  backendsr1  is_builtr   getenvr2  r5  runtimegetDeviceCount)array_namespacedevice	array_modr9  xpr5  s         r5   _array_api_for_testsrD    s   
+O<<		 
 
 
OOO
 
 	


 
 
 
M
 
 	

 
	'	'	(9(9!(<(<	=	=B7""f ))++  KLLL	G	#	#%9233s::    {'')) 	*  	
 
F	"	"9++--22LMMMIs    4= Ac                     t            G d d                      }  | dt                     | dt                     | dt                     | ddt                     | ddt                     | dd	t                     | dd
t                     | ddt                     | ddt                     | ddt                     | ddt                     | ddt                    gS )Nc                   H    e Zd ZU ded<   dZeed<   eZee         ed<   d Z	dS )4_get_warnings_filters_info_list.<locals>.WarningInfozwarnings._ActionKindactionre   r  r*   c                     | j         j        dk    r| j         j        }n| j         j         d| j         j         }| j         d| j         d| S )Nbuiltinsr   r   )r*   r`   r/   rH  r  rA   s     r5   to_filterwarning_strzI_get_warnings_filters_info_list.<locals>.WarningInfo.to_filterwarning_str)  s[    }':55=1"m6QQ9OQQk==DL==8===r7   N)
r/   r`   ra   __annotations__r  r   r.   r*   r,   rK  rc   r7   r5   WarningInforG  #  sU         &&&&")$w-)))	> 	> 	> 	> 	>r7   rM  r   r)   rF   z%pkg_resources is deprecated as an APIr  r*   z!Deprecated call to `pkg_resourceszQThe --rsyncdir command line argument and rsyncdirs config variable are deprecatedz,\s*Pyarrow will become a required dependencyz"datetime.datetime.utcfromtimestampzast.Num is deprecatedzAttribute n is deprecatedzast.Str is deprecatedzAttribute s is deprecated)r   DeprecationWarningFutureWarningr   )rM  s    r5   _get_warnings_filters_info_listrQ  "  s   > > > > > > > Y> 	G&8999Gm444G&?@@@ 	;'	
 	
 	

 	7'	
 	
 	
 	 (	
 	
 	
 	C'	
 	
 	
 	8'	
 	
 	
 	5@R	
 	
 	
 	9DV	
 	
 	
 	5@R	
 	
 	
 	9DV	
 	
 	
q; ;r7   c                  6    t                      } d | D             S )Nc                 6    g | ]}|                                 S rc   )rK  )rk   warning_infos     r5   rm   z2get_pytest_filterwarning_lines.<locals>.<listcomp>q  s4        	))++  r7   )rQ  )warning_filters_info_lists    r5   get_pytest_filterwarning_linesrV  o  s/     ? A A 5   r7   c                  x    t                      } | D ](}t          j        |j        |j        |j                   )d S )NrN  )rQ  r:   filterwarningsrH  r  r*   )warnings_filters_info_listrT  s     r5   turn_warnings_into_errorsrZ  w  sX    !@!B!B2 
 
 (!*	
 	
 	
 	
 	

 
r7   )Nrd   Tre   T)rh   rz   re   )r   )F)r   F)NN)re   )FNFNFNN)rm  rn  )NNNN)NFN)urb   r   
contextlibr   r6  r   r   os.pathr   r   r7  r   r<   r   r9  unittestr:   collectionsr   r   collections.abcr   dataclassesr   r  r   r	   r
   	itertoolsr   r   
subprocessr   r   r   r   r   numpyri   scipyr|   numpy.testingr   ru   r   r   r   r   r  sklearn.utilsr   r   r   r   r   sklearn.utils._array_apir   sklearn.utils.fixesr   r   r   r   r    sklearn.utils.multiclassr!   sklearn.utils.validationr"   r#   r$   __all__caser&   r.   r6   r3   r   r   r   ARRAY_API_COMPAT_FUNCTIONALr   r  markskipifskip_if_32bitxfailfails_if_unstable_openblasparallelmpskip_if_no_parallel'skip_if_array_api_compat_not_configuredplatform!if_safe_multiprocessing_with_blasskip_if_no_numpydocr   r   r   r   r   r   r  r  r  r/  rE  rl  r%   r  r  AbstractContextManagerr  r  r  r$  rD  rQ  rV  rZ  rc   r7   r5   <module>r{     s;    
               				       				  



     / / / / / / / / $ $ $ $ $ $ ! ! ! ! ! !                         $ $ $ $ $ $ $ $ O O O O O O O O O O O O          ? ? ? ? ? ?                          ? > > > > >              B A A A A A            =! w )2 )2 )2 )2X6 6 6 6 6 6 6 6t OSF F F FR'
 '
 '
 '
T8 8 8 8   (d###"& ( ( ("'(+	MMMK&&y9U&VVM!'!2!2++--< "3 " " !+,,O'A -   /5k.@.@''V /A / /+0 )/(:(: )T ); ) )% !+,,LNN< -    	 	 	D	H H H
P P P P) ) ) ) ) ) ) ),   ,   4  4P P P Pf  
 
 
! ! !J GI)
 )
 )
 )
\ 
 
 
 
D; ; ; ;B 
"j? j? j? j?Z%@ %@ %@ %@P* * * * *j/ * * *Z5
 5
 5
 5
 5
 5
 5
 5
p,
 ,
 ,
 ,
 ,
 ,
 ,
 ,
^*
 *
 *
 *
 *
 *
 *
 *
Z+ + +\J J JZ  
 
 
 
 
s%   ?D DDCG. .G65G6