
    {Kg                        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mZ ddlmZ ddlmZ ddlmZ ddlmZmZmZmZ ddl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'm(Z(m)Z) ddl*Z*ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9 g dZ: ed      Z;e;jx                  Z=ej|                  j~                  Z?e;j                  ZAe;j                  ZCeCZDdeEfdZF G d d      ZGd ZH	 d9dZ"d:dZId;dZJ	  e,d       dZK	 ddlMZMeMj                  j                  e.d      ZPeMj                  j                  e/d      ZReMj                  j                   e1       d      ZSeMj                  j                  ej                  j                   d      ZVeMj                  j                  eK d      ZWeMj                  j                  ej                  d k(  d!      ZYd" ZZd<d#Z[ G d$ d%      Z\d=d&Z]d<d'Z^d( Z_d>d)Z`d?d*Za	 	 	 	 d@d+ZbdAd,Zc G d- d.ej                        Ze G d/ d0      Zf G d1 d2      Zg G d3 d4      Zhd5 Zid6 Zjd7 Zkd8 Zly# eL$ r dZKY Uw xY w# eL$ r Y w xY w)BzTesting utilities.    N)Iterable)	dataclasswraps)	signature)STDOUTCalledProcessErrorTimeoutExpiredcheck_output)TestCase)assert_allclose)assert_almost_equalassert_approx_equalassert_array_almost_equalassert_array_equalassert_array_lessassert_no_warnings)_check_array_api_dispatch)	_IS_32BIT_IS_PYPYVisibleDeprecationWarning#_in_unstable_openblas_configurationparse_version
sp_version)check_classification_targets)check_arraycheck_is_fitted	check_X_y)assert_raisesassert_raises_regexpr   r   r   r   r   r   'assert_run_python_script_without_outputr   SkipTest__init__c                     t        | t              r7t        | t              r'| j                  }t        dj                  |            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      Z/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/sklearn/utils/_testing.pyignore_warningsr3   Y   sh    8 #tC!9 ||7 8>v<v7X	
 	
 
#11#6611    c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)r0   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 | _        || _        y )NTwarningsF)_recordsysmodules_module_enteredlogr'   selfr'   s     r2   r#   z_IgnoreWarnings.__init__   s.    {{:. r4   c                 2     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 Y   y xY w)Nignore)r7   catch_warningssimplefilterr'   )argskwargsfnr?   s     r2   wrapperz)_IgnoreWarnings.__call__.<locals>.wrapper   s<    ((*%%h>4*6* +**s   (AAr   )r?   rG   rH   s   `` r2   __call__z_IgnoreWarnings.__call__   s"     
r	+ 
	+
 r4   c                    g }| j                   r|j                  d       | j                  t        j                  d   ur|j                  d| j                  z         t        |       j                  }|ddj                  |      dS )Nzrecord=Truer7   z	module=%r(z, ))r8   appendr;   r9   r:   r)   r,   join)r?   rE   names      r2   __repr__z_IgnoreWarnings.__repr__   sf    <<KK&<<s{{:66KKdll23Dz""411r4   c                 .   | j                   rt        d| z        d| _         | j                  j                  | _        | j                  d d  | j                  _        | j                  j
                  | _        t        j                  d| j                         y )NzCannot enter %r twiceTrB   )
r<   RuntimeErrorr;   filters_filtersshowwarning_showwarningr7   rD   r'   )r?   s    r2   	__enter__z_IgnoreWarnings.__enter__   sm    ==6=>>,,#}}Q/ LL44h6r4   c                     | j                   st        d| z        | j                  | j                  _        | j
                  | j                  _        g | j                  d d  y )Nz%Cannot exit %r without entering first)r<   rR   rT   r;   rS   rV   rU   r=   )r?   exc_infos     r2   __exit__z_IgnoreWarnings.__exit__   sI    }}FMNN#}}#'#4#4 r4   N)	r,   
__module____qualname____doc__r#   rI   rP   rW   rZ    r4   r2   r0   r0      s     
!	27r4   r0   c                    	  ||i | t        | t              rdj                  d | D              }n| j                  }t	        |d|j                        # | $ r*}t        |      }||vrt	        d|d|      Y d}~yd}~ww xY w)a  Helper function to test the message raised in an exception.

    Given an exception, a callable to raise the exception, and
    a message string, tests that the correct exception is raised and
    that the message is a substring of the error thrown. Used to test
    that the specific message thrown during an exception is correct.

    Parameters
    ----------
    exceptions : exception or tuple of exception
        An Exception object.

    message : str
        The error message or a substring of the error message.

    function : callable
        Callable object to raise error.

    *args : the positional arguments to `function`.

    **kwargs : the keyword arguments to `function`.
    z or c              3   4   K   | ]  }|j                     y wN)r,   ).0es     r2   	<genexpr>z'assert_raise_message.<locals>.<genexpr>   s     ?Jq

Js   z not raised by z4Error message does not include the expected string: z. Observed error message: N)r(   tuplerN   r,   AssertionErrorstr)
exceptionsmessagefunctionrE   rF   namesrc   error_messages           r2   assert_raise_messagerm      s    .Q$!&! j%(KK?J??E''EeX=N=NOPP  A-' =DmU  (s   A B BBTc           	         g }t        j                  |       t        j                  |      }} | j                  |j                  g}|/|D cg c]  }|t         j                  k(  rdnd }	}t	        |	      }t        | ||||||       yc c}w )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)
    Ng-C6?Hz>)rtolatol	equal_nanerr_msgverbose)np
asanyarraydtypefloat32maxnp_assert_allclose)
actualdesiredrp   rq   rr   rs   rt   dtypesrw   rtolss
             r2   r   r      s    j FmmF+R]]7-CGFllGMM*F|DJKF5"**,$6FK5z Ls   B	c                    t         j                  j                  |       rt         j                  j                  |      r| j                         } |j                         }| j	                          |j	                          t        | j                  |j                  |       t        | j                  |j                  |       t        | j                  |j                  |||       yt         j                  j                  |       s0t         j                  j                  |      st        | ||||       y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.
    )rs   )rp   rq   rs   zGCan only compare two sparse matrices, not a sparse matrix and an array.N)spsparseissparsetocsrsum_duplicatesr   indicesindptrr   datar-   )xyrp   rq   rs   s        r2   assert_allclose_dense_sparser   1  s    2 
yy!!3!3A!6GGIGGI		199aiiA188QXXw?TgNYY"299+=+=a+@14dGDU
 	
r4   c                 N    d| j                         v r| j                  |       yy)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     r2   set_random_stater   [  s+     --//,7 0r4   Fzskipped on 32bit platforms)reasonznot compatible with PyPyz+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 BLASc                  l    t        t        j                  j                  dd            rt	        d      y )NSKLEARN_SKIP_NETWORK_TESTSr   z-Text tutorial requires large dataset download)intosenvirongetr"   r^   r4   r2   check_skip_networkr     s+    
2::>>6:;FGG <r4   c                     	 t         j                  j                  |       rt        j                  |        yy# t
        $ r |rt        j                  d| z         Y yY y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OSErrorr7   warn)folder_pathr   s     r2   _delete_folderr     sX    
P77>>+& MM+& '  PMM@;NO Ps   48 #A A c                   $    e Zd ZdZddZd Zd Zy)
TempMemmapzM
    Parameters
    ----------
    data
    mmap_mode : str, default='r'
    c                      || _         || _        y ra   )	mmap_moder   )r?   r   r   s      r2   r#   zTempMemmap.__init__  s    "	r4   c                 Z    t        | j                  | j                  d      \  }| _        |S )NT)r   return_folder)create_memmap_backed_datar   r   temp_folder)r?   data_read_onlys     r2   rW   zTempMemmap.__enter__  s+    +DIIt,
(( r4   c                 .    t        | j                         y ra   )r   r   )r?   exc_typeexc_valexc_tbs       r2   rZ   zTempMemmap.__exit__  s    t''(r4   N)r)r,   r[   r\   r]   r#   rW   rZ   r^   r4   r2   r   r     s    )r4   r   c                 *   t        j                  d      }t        j                  t	        j
                  t        |d             t        j                  |d      }t        j                  | |       t        j                  ||      }|s|}|S ||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   oprN   joblibdumpload)r   r   r   r   filenamememmap_backed_dataresults          r2   r   r     s     ""*<=K
OOI%%nkMNww{J/H
KKhXC"/  M 7I+5V  Mr4   c                    	 t        |       j                  }|j                         D cg c]+  \  }}|j                  |j
                  |j                  fvr|- }}}|rT|j                         D cg c]'  }|j                  |j
                  k(  r|j                  ) }}t        |      dk(  rd}||fS |S # t        $ r g cY S w xY wc c}}w c c}w )z!Helper to get function arguments.r   N)
r   
parametersr-   itemskindVAR_POSITIONALVAR_KEYWORDvaluesrO   len)rj   varargsparamskeyparamrE   s         r2   	_get_argsr     s    8$// !,,.(JC::e22E4E4EFF 	( 	 
   
(zzU111 JJ( 	 

 w<1GW}%  	
s   B5 0C1,C5CCc                 >   g }t        j                  |       }|r|j                  |j                         | j                  }|| j                  k7  r#|j                  |d|j                  d              |j                  | j                         dj                  |      S )zGet function full name.

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

    Returns
    -------
    name : str
        The function name.
    N.)inspect	getmodulerM   r,   r\   findrN   )funcpartsmodulequalnames       r2   _get_func_namer     s~     Et$FV__%  H4== X2c 234	LL88E?r4   c           	      R   ddl m} g }g nt        |       }|j                  d      r|j                  d      r|S t	        j
                  |       r|S |j                  d      d   dv r|S |j                  d      d	   d
k(  r|S t        t        fdt        |                   }t        |      dkD  r|d   dk(  r|j                  d       |lg }t        j                  d      5  t        j                  dt               	 |j!                  |       }ddd       t        |      rt)        d|d|d         g }
|d   D ]  \  }}}|j+                         sod|v r2|d|j-                  d       dd j+                         r||d|z  z   gz  }n9|j/                         j1                  d      r||d|j3                         z  z   gz  }d|vs|
j%                  |j                  d      d   j+                  d              t        |      dkD  r|S t        t        fd|
            }
g }	t5        t7        t        |
      t        |                  D ]$  }||   |
|   k7  s|	d|d||   d |
|   gz  }	 n t        |      t        |
      kD  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}|j=                  |
      j?                         }|j=                  |      j?                         }|	d#gz  }	|	jA                  d$ |jC                  ||      D               |jA                  |	       d|z   g|z   }|S # t        $ rk}dt#        |      v r9t#        |      j                  d      dd }	|d| g|	z   z  }|cY d}~cddd       S |j%                  t#        |             Y d}~d}~wt&        $ r*}||dz   t#        |      z   gz  }|cY d}~cddd       S d}~ww xY w# 1 sw Y   xY w)%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 ra   r^   r   rB   s    r2   <lambda>z,check_docstring_parameters.<locals>.<lambda>5  s	    AVOr4   r?   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 ra   r^   r   s    r2   r   z,check_docstring_parameters.<locals>.<lambda>k  s	    qr4   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   | ]  }|j                           y wra   )strip)rb   lines     r2   rd   z-check_docstring_parameters.<locals>.<genexpr>  s      RD 	

Rs   )"numpydocr   r   
startswithr   isdatadescriptorsplitlistfilterr   r   remover7   rC   rD   UserWarningFunctionDocrg   rM   	ExceptionrR   r   indexrstripendswithlstriprangemindifflibpprintpformat
splitlinesextendndiff)r   docrB   r   	incorrect	func_nameparam_signaturerecordsexpri   
param_docsrO   type_definition	param_docir   r   param_docs_formattedparam_signature_formatteds     `                r2   check_docstring_parametersr    se   " #I>RvFt$I
+y/C/C0 %sB#FFsA"446";Yt_MNO
?aOA$6&$@v& {$$D1!!';7!++D1 2  w<iLMMJ,/,=(oy$$&d{t$5djjo6rs;AACQTXXY 	 '',N{{}&& 	 d?djjoa066t<=% ->, 9~ f6
CDJ G3s:O(<=>1A. &'(:JqMK G
  ? ?c*o-:c*o./
 	
 
_	J	/8_-./
 	
 7|q	!>>*5@@B & ? J J L~GNN MM";=QR 
 W !9,-	9I  )73s8C "#hnnT22A6GM)"=!>!HHI$$ 21 s3x(( !i*<<s3xGHH	   21! 21sZ   )PM44	P=7O#4P5PO#P#P/PPPPPP&c                    t        j                  d      \  }}t        j                  |       	 t	        |d      5 }|j                  | j                  d             ddd       t        j                  |g}t        j                  t        j                  t        j                  t        j                        d            }t        j                  j!                         }	 t        j"                  j                  ||d   g      |d<   |t&        |d}	t        j                  j)                  d	      }
|
r|
|	d
   d	<   ||	d<   	 	 t+        |fi |	}|j3                  d      }t5        j6                  ||      r|dk(  rd}nd|}| d|}t9        |      	 t        j<                  |       y# 1 sw Y   OxY w# t$        $ r ||d<   Y w xY w# t,        $ r,}t/        d|j0                  j3                  d      z        d}~ww xY w# t:        $ r,}t/        d|j0                  j3                  d      z        d}~ww xY w# 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_STARTr  timeoutzscript errored with output:
%s.+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encoder9   
executabler   normpathrN   dirnamesklearn__file__r   copypathsepKeyErrorr   r   r   r	   rR   outputdecoderesearchrf   r
   unlink)source_codepatternr  fdsource_filefcmdr  r  rF   coverage_rcoutrc   expectationri   s                  r2   r!   r!     s   $ &&.DEOBHHRL'+t$GGK&&w/0 %~~{+kk"''"**W-=-=">EFjjoo	$ "

c,6G0H IC s;jjnn%=>6AF5M23#y	"31&1 **W%Cyy#&d?"6K$I'"UK(M)McWU$W-- ' 			+M %$  	$ #C	$ & "58PP   	4qxxw7OO 	
 			+s   H; !F*BH;  'F7 8H; G AH *F4/H; 7GH; GH; 	H 'G;;H  H 	H8'H33H88H; ;Ic                    |dk(  r2|t        |       S t        j                  | |      j                         S |dk(  r;|t	        |       S t	        t        j                  | |      j                               S |dk(  rt        j                  | |      S |dv rNt        j                  d|      }|j                  | ||d	
      }||D ]  }||   j                  d      ||<    |S |dk(  rt        j                  d|      }	t        j                  |       }
|(t        |
j                  d         D cg c]  }d| 	 }}t        |      D ci c]  \  }}||
dd|f    }}}|	j                  j                  |      }|Rt        |j                        D ]:  \  }}||v s|j                  |||j!                  |      j#                               }< |S |dk(  rot        j                  d|      }|j                  | |d      }|@|D ];  }|j%                  |j'                  |      j)                  |j*                              }= |S |dk(  r*t        j                  d|      }|j-                  | |      S |dk(  r)t        j                  d|      }|j-                  |       S |dk(  r*t        j                  d|      }|j/                  | |      S |dk(  rt1        | d   | d         S d|v rt2        j4                  j7                  |       st        j8                  |       } d|v r&t:        t=        d      k  rt?        | dt:               |dv r!t2        j4                  jA                  | |      S |dk(  r!t2        j4                  jC                  | |      S |dk(  r!t2        j4                  jE                  | |      S |dk(  r!t2        j4                  jG                  | |      S yyc c}w c c}}w )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)rw   re   array)pandas	dataframer7  )
minversionF)columnsrw   r$  r'   pyarrow   col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   ru   asarraytolistre   pytestimportorskip	DataFrameastyper   shape	enumerateTablefrom_pydictcolumn_names
set_columncolumndictionary_encodewith_columnsr=  castCategoricalSeriesIndexrD  r   r   r   
atleast_2dr   r   r-   
csr_matrix	csr_array
csc_matrix	csc_array)	containerconstructor_namecolumns_namerw   r9  categorical_feature_namespdr   col_namepar6  r  rO   r   col_idxpls                   r2   _convert_containerrj    s   D 6!=	?"::iu5<<>>	W	$=##IU;BBDEE	W	$zz)511	4	4  jAiUQVW$05#)(#3#:#::#Fx  6	Y	&  zB

9%/4U[[^/DE/D!c!I/DLE1:<1HI1HgaeAqDk!1HI%%d+$0%.v/B/B%C!88#..6==+B+T+T+VF &D
 	X	%  jAiUK$05,,RVVH-=-B-B2>>-RS 6	X	%  jAyy%y00	_	,  jAyy	y**	W	$  jAxx	x//	W	$Yq\9Q<00	%	%yy!!),
 i0I&&:e8L+L#$$N,   7799''	'??!3399&&y&>>-99''	'??!3399&&y&>> 4) 
&9 FIs   3O)O.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_passrs   s       r2   raisesrp  N  s    J $eXw??r4   c                       e Zd Zd Zd Zy)rl  c                     t        |t              r|n|g| _        t        |t              r|gn|| _        || _        || _        d| _        y )NF)r(   r   expected_exc_typesrg   matchesro  rs   raised_and_matched)r?   rm  rn  ro  rs   s        r2   r#   z_Raises.__init__x  sN     +X6 #$ 	
 #-UC"8we "'r4   c                    5| j                   ry| j                  xs d| j                   }t        |      t	        fd| j                  D              s#| j                  t        | j                        y| j
                  s| j                  xs4 dj                  dj                  | j
                        t                    }t	        fd| j
                  D              st        |      d| _	        y)NTzDid not raise: c              3   6   K   | ]  }t        |        y wra   )r*   )rb   expected_typer   s     r2   rd   z#_Raises.__exit__.<locals>.<genexpr>  s       
!8 x/!8s   FzIThe error message should contain one of the following patterns:
{}
Got {}r   c              3   \   K   | ]#  }t        j                  |t                     % y wra   )r)  r*  rg   )rb   rn  	exc_values     r2   rd   z#_Raises.__exit__.<locals>.<genexpr>  s!     R\EryyI7\s   ),)
ro  rs   rs  rf   anyrt  r.   rN   rg   ru  )r?   r   rz  _rs   s    ``  r2   rZ   z_Raises.__exit__  s     }},,UOD<S<S;T*U$W-- 
!%!8!8
 
 ||'$T\\2	A<<#ll ((.tyy/FI(W  RT\\RR$W-9<&*D#r4   N)r,   r[   r\   r#   rZ   r^   r4   r2   rl  rl  v  s    	(r4   rl  c                   B    e Zd ZdZdZddZddZd Zd Zd Z	d	 Z
d
 Zy)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`.
    
classifierNc                     || _         y ra   r   r?   r   s     r2   r#   zMinimalClassifier.__init__  	    
r4   c                     d| j                   iS Nr   r  r?   deeps     r2   r   zMinimalClassifier.get_params      $$r4   c                 P    |j                         D ]  \  }}t        | ||        | S ra   r   setattrr?   r   r   values       r2   r   zMinimalClassifier.set_params  '     ,,.JCD#u% )r4   c                     t        ||      \  }}t        |       t        j                  |d      \  | _        }|j                         | _        | S )NT)return_counts)r   r   ru   uniqueclasses_argmax_most_frequent_class_idx)r?   Xr   countss       r2   fitzMinimalClassifier.fit  sC    A1$Q' "		!4 @v(.%r4   c                     t        |        t        |      }|j                  d   | j                  j                  f}t        j                  |t
        j                        }d|d d | j                  f<   |S )Nr   )rO  rw   g      ?)	r   r   rO  r  sizeru   zerosfloat64r  )r?   r  proba_shapey_probas       r2   predict_probazMinimalClassifier.predict_proba  s]    Nwwqz4==#5#56((BJJ?4740001r4   c                 f    | j                  |      }|j                  d      }| j                  |   S )Nr<  )axis)r  r  r  )r?   r  r  y_preds       r2   predictzMinimalClassifier.predict  s1    $$Q'Q'}}V$$r4   c                 >    ddl m}  ||| j                  |            S )Nr   )accuracy_score)sklearn.metricsr  r  )r?   r  r   r  s       r2   scorezMinimalClassifier.score  s    2aa11r4   ra   T)r,   r[   r\   r]   _estimator_typer#   r   r   r  r  r  r  r^   r4   r2   r~  r~    s1     #O%
%
2r4   r~  c                   <    e Zd ZdZdZd
dZddZd Zd Zd Z	d	 Z
y)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`.
    	regressorNc                     || _         y ra   r  r  s     r2   r#   zMinimalRegressor.__init__  r  r4   c                     d| j                   iS r  r  r  s     r2   r   zMinimalRegressor.get_params  r  r4   c                 P    |j                         D ]  \  }}t        | ||        | S ra   r  r  s       r2   r   zMinimalRegressor.set_params  r  r4   c                 f    t        ||      \  }}d| _        t        j                  |      | _        | S NT)r   
is_fitted_ru   mean_meanr?   r  r   s      r2   r  zMinimalRegressor.fit  s,    A1WWQZ
r4   c                     t        |        t        |      }t        j                  |j                  d   f      | j
                  z  S )Nr   )rO  )r   r   ru   onesrO  r  )r?   r  s     r2   r  zMinimalRegressor.predict  s5    Nwwaggaj]+djj88r4   c                 >    ddl m}  ||| j                  |            S )Nr   )r2_score)r  r  r  )r?   r  r   r  s       r2   r  zMinimalRegressor.score  s    ,4<<?++r4   ra   r  )r,   r[   r\   r]   r  r#   r   r   r  r  r  r^   r4   r2   r  r    s,     "O%
9
,r4   r  c                   >    e Zd ZdZd	dZd
dZd Zd	dZd	dZd	dZ	y)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                     || _         y ra   r  r  s     r2   r#   zMinimalTransformer.__init__  r  r4   c                     d| j                   iS r  r  r  s     r2   r   zMinimalTransformer.get_params
  r  r4   c                 P    |j                         D ]  \  }}t        | ||        | S ra   r  r  s       r2   r   zMinimalTransformer.set_params  r  r4   c                 *    t        |       d| _        | S r  )r   r  r  s      r2   r  zMinimalTransformer.fit  s    Ar4   c                 2    t        |        t        |      }|S ra   )r   r   r  s      r2   	transformzMinimalTransformer.transform  s    Nr4   c                 F    | j                  ||      j                  ||      S ra   )r  r  r  s      r2   fit_transformz MinimalTransformer.fit_transform  s    xx1~''1--r4   ra   r  )
r,   r[   r\   r]   r#   r   r   r  r  r  r^   r4   r2   r  r    s%    %


.r4   r  c                    	 t        j                  |       }	 dd l}|j                  |j                  d            }| dk(  r4|dk(  r/|j                  j                  j                         st        d      | dk(  rY|dk(  rTt        j                  d	      d
k7  rt        d      |j                  j                  j                         st        d      |S | dv r6dd l}|j                  j                  j!                         dk(  rt        d      |S # t        $ r t        |  d      w xY w# t
        $ r t        d      w xY w)Nz/ is not installed: not checking array_api inputr   z?array_api_compat is not installed: not checking array_api inputr<  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.>   cupy.array_apicupyz/CuPy test requires cuda, which is not available)	importlibimport_moduleModuleNotFoundErrorr"   array_api_compatImportErrorget_namespacerI  backendsr  is_builtr   getenvr  r  runtimegetDeviceCount)array_namespacedevice	array_modr  xpr  s         r2   _array_api_for_testsr     sV   
++O<	

 
	'	'	(9(9!(<	=B7"f  ))+KLL	G	#%9923s:   {{'')*  I 
6	699++-2LMMIQ  
NO
 	

  
M
 	

s   D D* D'*D?c                  v   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                   @    e Zd ZU ded<   dZeed<   eZee   ed<   d Z	y)4_get_warnings_filters_info_list.<locals>.WarningInfozwarnings._ActionKindaction ri   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,   r  ri   r>   s     r2   to_filterwarning_strzI_get_warnings_filters_info_list.<locals>.WarningInfo.to_filterwarning_strU  sh    }}'':5==11"mm667q9O9O8PQkk]!DLL>8*==r4   N)
r,   r[   r\   __annotations__ri   rg   r+   r'   r)   r  r^   r4   r2   WarningInfor  O  s%    &&")$w-)	>r4   r  r   r&   rB   z%pkg_resources is deprecated as an APIri   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   )r  s    r2   _get_warnings_filters_info_listr  N  s    > > > 	G&89Gm4G&?@ 	;'	

 	7'	
 	 (	
 	C'	
 	8'	
 	5@R	
 	9DV	
 	5@R	
 	9DV	
q; ;r4   c                  \    t               } | D cg c]  }|j                          c}S c c}w ra   )r  r  )warning_filters_info_listwarning_infos     r2   get_pytest_filterwarning_linesr    s;     ? A 65L 	))+5  s   )c                      t               } | D ]8  }t        j                  |j                  |j                  |j
                         : y )Nr  )r  r7   filterwarningsr  ri   r'   )warnings_filters_info_listr  s     r2   turn_warnings_into_errorsr    s>    !@!B2 ((!**	
 3r4   )Ng        Tr  T)ro   g&.>r  )r   )F)r   F)NN)r  <   )NNNN)NFN)mr]   r   
contextlibr   r  r   r   os.pathr   r   r)  r   r9   r   unittestr7   collections.abcr   dataclassesr   r   r   
subprocessr   r	   r
   r   r   r   numpyru   scipyr   numpy.testingr   rz   r   r   r   r   r   r   r"  sklearn.utils._array_apir   sklearn.utils.fixesr   r   r   r   r   r   sklearn.utils.multiclassr   sklearn.utils.validationr   r   r   __all___dummyassertRaisesr   caser"   assertDictEqualassert_dict_equalassertRaisesRegexassert_raises_regexr    r+   r3   r0   rm   r   r   ARRAY_API_COMPAT_FUNCTIONALr  rK  markskipifskip_if_32bitxfailfails_if_pypyfails_if_unstable_openblasparallelmpskip_if_no_parallel'skip_if_array_api_compat_not_configuredplatform!if_safe_multiprocessing_with_blasr   r   r   r   r   r   r  r!   rj  rp  AbstractContextManagerrl  r~  r  r  r  r  r  r  r^   r4   r2   <module>r     s         	  	  
    $ !   O O     ?   >  B  
*	##==!!** ..  +  w )2X6 6r'QV OSFR'
T8 (d#"&(	KK&&y9U&VMKK%%h7Q%RM!'!2!2+-< "3 " !++,,OO'A -  /5kk.@.@''V /A /+0 )/(:(: )T ); )%H
P) ),,44Pf;B 
"j?Z%@P*j// *Z.2 .2b%, %,P!. !.H+\JZ
k  ("'(T  		s%   
I- #CI; -I87I8;JJ