CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
_testing.cpython-310.pyc584 linesDownload Raw Back to __pycache__
1o

2�Yi0��	@s�dZddlZddlZddlZddlZddlZddlZddlmZ	ddl3Z4ddlZddlZddl
Z
ddlZddlZddlZddlmZmZddlmZddlmZddlmZddlmZddlmZdd	lmZmZdd5lm Z m!Z!m"Z"m#Z#ddl$Z$ddl%Z&ddl'Z(ddl)m*Z+ddl)m,Z,m-Z-m.Z.m/Z/ddl0Z0dd
l1m2Z2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:m;Z;m<Z<ddl=m>Z>ddl?m@Z@mAZAmBZBgd�ZCejDjEZEdeFfdd�ZGGdd�d�ZH	d^dd�Z*d_dd�ZId`d d!�ZJd"d#�ZKze8d�dZLWneMeNf�yd$ZLYnwz@ddlOZOeOjPjQe:d%d&�ZReOjPjSe<�d'd&�ZTeOjPjQe$jUjVd(d&�ZWeOjPjQeLd)d&�ZXeOjPjQejYd*kd+d&�ZZeOjPjQeK�d,d&�Z[Wn6eM�yQYnwd-d.�Z\dad/d0�Z]Gd1d2�d2�Z^dbd4d5�Z_dad6d7�Z`d8d9�Zadcd:d;�Zbd<d=�Zcd>d?�Zdd@dA�Zedef�fdBdC�Zgd$dd$dd$ddef�fdDdE�ZhdddHdI�Zi				dedJdK�ZjdfdLdM�ZkGdNdO�dOejl�ZmGdPdQ�dQ�ZnGdRdS�dS�ZoGdTdU�dU�ZpdVdW�ZqdXdY�ZrdZd[�Zsd\d]�ZtdS)gzTesting utilities.�N)�defaultdict�7namedtuple)�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�8TargetTags�TransformerTags)�_check_array_api_dispatch)�	_IS_32BIT�VisibleDeprecationWarning�#_in_unstable_openblas_configuration)�check_classification_targets)�check_array�check_is_fitted�	check_X_y)�SkipTestrrrrr�'assert_run_python_script_without_outputcCsJt|t�rt|t�r|j}tdj|d���t|�r t|d�|�St|d�S)a Context manager and decorator to ignore warnings.9 10    Note: Using this (in both variants) will clear all warnings11    from all python modules loaded. In case you need to test12    cross-module-warning-logging, this is not your tool of choice.13 14    Parameters15    ----------16    obj : callable, default=None17        callable where you want to ignore the warnings.18    category : warning class, default=Warning19        The category to filter. If Warning, all categories will be muted.20 21    Examples22    --------23    >>> import warnings24    >>> from sklearn.utils._testing import ignore_warnings25    >>> with ignore_warnings():26    ...     warnings.warn('buhuhuhu')27 28    >>> def nasty_warn():29    ...     warnings.warn('buhuhuhu')30    ...     print(42)31 32    >>> ignore_warnings(nasty_warn)()33    4234    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)	�35isinstance�type�36issubclass�Warning�__name__�37ValueError�format�callable�_IgnoreWarnings)�objr&r$�r1��E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\sklearn/utils/_testing.py�ignore_warningsJs��38r3c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd39d�ZdS)
r/atImproved and simplified Python warnings context manager and decorator.40 41    This class allows the user to ignore the warnings raised by a function.42    Copied from Python 2.7.5 and modified as required.43 44    Parameters45    ----------46    category : tuple of warning class, default=Warning47        The category to filter. By default, all the categories will be muted.48 49    cCs(d|_tjd|_d|_g|_||_dS)NT�warningsF)�_record�sys�modules�_module�_entered�logr&��selfr&r1r1r2�__init__�s5051z_IgnoreWarnings.__init__cst����fdd��}|S)z<Decorator to catch and hide warnings without visual nesting.csHt���t�d�j��|i|��Wd�S1swYdS)N�ignore)r4�catch_warnings�simplefilterr&)�args�kwargs��fnr<r1r2�wrapper�s52$�z)_IgnoreWarnings.__call__.<locals>.wrapperr)r<rDrEr1rCr2�__call__�sz_IgnoreWarnings.__call__cCsPg}|jr53|�d�|jtjdur|�d|j�t|�j}d|d�|�fS)Nzrecord=Truer4z	module=%rz%s(%s)z, )r5�appendr8r6r7r(r+�join)r<rA�namer1r1r2�__repr__�s5455z_IgnoreWarnings.__repr__cCsP|jr	td|��d|_|jj|_|jdd�|j_|jj|_t�d|j	�dS)NzCannot enter %r twiceTr>)56r9�RuntimeErrorr8�filters�_filters�showwarning�_showwarningr4r@r&�r<r1r1r2�	__enter__�s5758z_IgnoreWarnings.__enter__cGs8|js	td|��|j|j_|j|j_g|jdd�<dS)Nz%Cannot exit %r without entering first)r9rKrMr8rLrOrNr:)r<�exc_infor1r1r2�__exit__�s596061z_IgnoreWarnings.__exit__N)	r+�62__module__�__qualname__�__doc__r=rFrJrQrSr1r1r1r2r/vs		r/�T�c		Cs^g}t�|�t�|�}}|j|jg}|dur"dd�|D�}t|�}t|||||||d�dS)audtype-aware variant of numpy.testing.assert_allclose63 64    This variant introspects the least precise floating point dtype65    in the input argument and automatically sets the relative tolerance66    parameter to 1e-4 float32 and use 1e-7 otherwise (typically float6467    in scikit-learn).68 69    `atol` is always left to 0. by default. It should be adjusted manually70    to an assertion-specific value in case there are null values expected71    in `desired`.72 73    The aggregate tolerance is `atol + rtol * abs(desired)`.74 75    Parameters76    ----------77    actual : array_like78        Array obtained.79    desired : array_like80        Array desired.81    rtol : float, optional, default=None82        Relative tolerance.83        If None, it is set based on the provided arrays' dtypes.84    atol : float, optional, default=0.85        Absolute tolerance.86    equal_nan : bool, optional, default=True87        If True, NaNs will compare equal.88    err_msg : str, optional, default=''89        The error message to be printed in case of failure.90    verbose : bool, optional, default=True91        If True, the conflicting values are appended to the error message.92 93    Raises94    ------95    AssertionError96        If actual and desired are not equal up to specified precision.97 98    See Also99    --------100    numpy.testing.assert_allclose101 102    Examples103    --------104    >>> import numpy as np105    >>> from sklearn.utils._testing import assert_allclose106    >>> x = [1e-5, 1e-3, 1e-1]107    >>> y = np.arccos(np.cos(x))108    >>> assert_allclose(x, y, rtol=1e-5, atol=0)109    >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)110    >>> assert_allclose(a, 1e-5)111    NcSsg|]}|tjkrdnd�qS)g-C��6?�H�����z>)�npZfloat32)�.0�dtyper1r1r2�112<listcomp>�sz#assert_allclose.<locals>.<listcomp>)�rtol�atol�	equal_nan�err_msg�verbose)rZZ113asanyarrayr\�max�np_assert_allclose)	�actualZdesiredr^r_r`rarbZdtypesZrtolsr1r1r2r�s5114�rrY��&�.>cCs�tj�|�r;tj�|�r;|��}|��}|��|��t|j|j|d�t|j|j|d�t|j	|j	|||d�dStj�|�sRtj�|�sRt|||||d�dSt115d��)a�Assert allclose for sparse and dense data.116 117    Both x and y need to be either sparse or dense, they118    can't be mixed.119 120    Parameters121    ----------122    x : {array-like, sparse matrix}123        First array to compare.124 125    y : {array-like, sparse matrix}126        Second array to compare.127 128    rtol : float, default=1e-07129        relative tolerance; see numpy.allclose.130 131    atol : float, default=1e-9132        absolute tolerance; see numpy.allclose. Note that the default here is133        more tolerant than the default for numpy.testing.assert_allclose, where134        atol=0.135 136    err_msg : str, default=''137        Error message to raise.138    )ra)r^r_razGCan only compare two sparse matrices, not a sparse matrix and an array.N)�sp�sparse�issparseZtocsrZsum_duplicatesr�indicesZindptrr�datar,)�x�yr^r_rar1r1r2�assert_allclose_dense_sparse�s�rncCs d|��vr|j|d�dSdS)a~Set random state of an estimator if it has the `random_state` param.139 140    Parameters141    ----------142    estimator : object143        The estimator.144    random_state : int, RandomState instance or None, default=0145        Pseudo random number generator state.146        Pass an int for reproducible results across multiple function calls.147        See :term:`Glossary <random_state>`.148    �random_state)roN)�149get_params�150set_params)Z	estimatorror1r1r2�set_random_state"s�rrc	Cs(zddl}WdSttfyYdSw)NrFT)�numpydoc�ImportError�AssertionError)rsr1r1r2�_is_numpydoc2s151��rvFzskipped on 32bit platforms)�reasonz+OpenBLAS is unstable for this configurationzjoblib is in serial modez<SCIPY_ARRAY_API not set, or versions of NumPy/SciPy too old.�darwinz)Possible multi-process bug with some BLASz+numpydoc is required to test the docstringscCsttj�dd��r
td��dS)NZSKLEARN_SKIP_NETWORK_TESTSrz-Text tutorial requires large dataset download)�int�os�environ�getr"r1r1r1r2�check_skip_networkos�r}cCsPztj�|�rt�|�WdSWdSty'|r$t�d|�YdSYdSw)zuUtility function to cleanup a temporary folder if still existing.152 153    Copy from joblib.pool (for independence).154    z$Could not delete temporary folder %sN)rz�path�exists�shutil�rmtree�OSErrorr4�warn)Zfolder_pathr�r1r1r2�_delete_folderts���r�c@s*eZdZdZd155dd�Zdd�Zdd�Zd	S)�156TempMemmapzM157    Parameters158    ----------159    data160    mmap_mode : str, default='r'161    �rcCs||_||_dS�N)�	mmap_moderk)r<rkr�r1r1r2r=�s162zTempMemmap.__init__cCst|j|jdd�\}|_|S)NT)r��
return_folder)�create_memmap_backed_datarkr��temp_folder)r<Zdata_read_onlyr1r1r2rQ�s163�zTempMemmap.__enter__cCst|j�dSr�)r�r�)r<�exc_type�exc_val�exc_tbr1r1r2rS�szTempMemmap.__exit__N)r�)r+rTrUrVr=rQrSr1r1r1r2r��s164165r�r�cCs`tjdd�}t�tjt|dd��t�|d�}t	�166||�t	j||d�}|s*|}|S||f}|S)zv167    Parameters168    ----------169    data170    mmap_mode : str, default='r'171    return_folder :  bool, default=False172    Zsklearn_testing_)�prefixT)r�zdata.pkl)r�)�tempfile�mkdtemp�atexit�register�	functools�partialr��oprH�joblib�dump�load)rkr�r�r��filenameZmemmap_backed_data�resultr1r1r2r��s���r�cCsjzt|�j}WntygYSwdd�|��D�}|r3dd�|��D�}t|�dkr/d}||fS|S)z!Helper to get function arguments.cSs&g|]\}}|j|j|jfvr|�qSr1)�kind�VAR_POSITIONAL�VAR_KEYWORD)r[�key�paramr1r1r2r]�s173�z_get_args.<locals>.<listcomp>cSsg|]}|j|jkr|j�qSr1)r�r�rI)r[r�r1r1r2r]�s174�rN)r	�175parametersr,�items�values�len)�function�varargs�paramsrAr1r1r2�	_get_args�s ���r�cCs\g}t�|�}|r|�|j�|j}||jkr#|�|d|�d���|�|j�d�|�S)z�Get function full name.176 177    Parameters178    ----------179    func : callable180        The function object.181 182    Returns183    -------184    name : str185        The function name.186    N�.)�inspect�	getmodulerGr+rU�findrH)�func�parts�module�qualnamer1r1r2�_get_func_name�s
187188189r�cs�ddlm}g}�durgn��t|�}|�d�r|�d�r |St�|�r'|S|�d�ddvr2|S|�d�d	d190kr=|Stt�fdd�t	|���}t191|�dkr[|dd
kr[|�d
�|dur�g}tj
dd��~t�dt�z|�|�}Wnhty�}z7dt|�vr�t|��d�dd�}	|d|��g|	7}|WYd}~Wd�S|�t|��WYd}~n*d}~wty�}z||dt|�g7}|WYd}~Wd�Sd}~wwWd�n1s�wYt192|�r�td||df��g}193|dD]O\}}}
|���s=d|v�r*|d|�d��dd����r*||d|g7}n|���d��r=||d|��g7}d|v�rO|194�|�d�d�d���qt195|�dk�rZ|Stt�fdd�|196��}197g}	ttt198|199�t200|���D]}|||201|k�r�|	d||||202|fg7}	n�qrt203|�t204|205�k�r�|	d|t206|207�g7}	nt208|�t209|210�k�r�|	d |211t212|�g7}	t213|	�dk�r�gSddl}ddl}|�|214���}|�|���}|	d!g7}	|	� d"d#�|�!||�D��|� |	�d|g|}|S)$arHelper to check docstring.215 216    Parameters217    ----------218    func : callable219        The function object to test.220    doc : str, default=None221        Docstring if it is passed manually to the test.222    ignore : list, default=None223        Parameters to ignore.224 225    Returns226    -------227    incorrect : list228        A list of string describing the incorrect results.229    r)�	docscrapeNzsklearn.zsklearn.externalsr������)Zsetup_moduleZteardown_module�Zestimator_checksc�|�vSr�r1�rl�r>r1r2�<lambda>�z,check_docstring_parameters.<locals>.<lambda>r<T)�record�errorz"potentially wrong underline length�230�z
In function: z parsing error: zError for %s:231%s�232Parameters�:z9 There was no space between the param name and colon (%r)z6 Parameter %r has an empty type spec. Remove the colon�*z` cr�r�r1r�r�r1r2r�>r�zmThere's a parameter name mismatch in function docstring w.r.t. function signature, at index %s diff: %r != %rzbParameters 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: %sz233Full diff:cs��|]}|��VqdSr�)�strip�r[�liner1r1r2�	<genexpr>is234��235�z-check_docstring_parameters.<locals>.<genexpr>)"rsr�r��236startswithr��isdatadescriptor�split�list�filterr�r��remover4r?r@�UserWarningZFunctionDoc�strrG�	ExceptionrKr��index�rstrip�endswith�lstrip�range�min�difflib�pprintZpformat�237splitlines�extendZndiff)r��docr>r�Z	incorrect�	func_nameZparam_signature�records�exp�messageZ238param_docsrIZtype_definitionZ	param_doc�ir�r�Zparam_docs_formattedZparam_signature_formattedr1r�r2�check_docstring_parameters�s��239240����
��241*�����242����243��244��	245246247�248r�cCs4|jdur||jvrdS|jdur||jvrdSdS)z7Helper to check if item should be included in checking.TFN)�include�exclude)�	item_namerAr1r1r2�_check_item_includedvs249r�cCs<|�d�rdS|�d�rdS|�d�rdS|�d�rdSdS)z,Key for grouping output from `context_diff`.z  z- z+ z! N)r�)r�r1r1r2�	_diff_keys250251252253r�c	Cs�d}d}g}|��D]`\}}|s|s||7}|�|�tt|��|��t|�t|�dd��}|d�|dd��7}t|dd�td�D]"\}}|durU|dd�|�7}qC|d|d�d	d254�|D��7}qC|d7}q255|S)aGet message showing the difference between type/desc docstrings of all objects.256 257    `docstrings_grouped` keys should be the type/desc docstrings and values are a list258    of objects with that docstring. Objects with the same type/desc docstring are259    thus grouped together.260    rX�)�fromfile�tofile�nNr�)r�r�� css�|]	}|dd�VqdS)r�Nr1)r[�wordr1r1r2r��s�z _get_diff_msg.<locals>.<genexpr>z261 262)	r�r�r�rr�r�rHrr�)�docstrings_grouped�msg_diffZref_strZ	ref_group�	docstring�group�diff�startr1r1r2�
_get_diff_msg�s.263��264"265r�cCsPg}|��D]�\}}tdd�|��D��|kr|�|�q|dkrV|rVg}	|��D]\}266}t�||267�s8|	�|�q)|	rUt�d|dd��d|�d|	�d	|�d268�	�}t	|��q|dkr_||vr_qt269|���dkr�t|�}
d
�
dd�|��D��}t�d|�d|dd��d|�d|�d�	�}||
7}t	|��q|r�t�d|�d|�d��dSdS)a�Helper to check docstring consistency of all `items_docs`.270 271    If item is not present in all objects, checking is skipped and warning raised.272    If `regex` provided, match descriptions to all descriptions.273 274    Parameters275    ----------276    items_doc : dict of dict of str277        Dictionary where the key is the string type or description, value is278        a dictionary where the key is "type description" or "description"279        and the value is a list of object names with the same string type or280        description.281 282    type_or_desc : {"type description", "description"}283        Whether to check type description or description between objects.284 285    section : {"Parameters", "Attributes", "Returns"}286        Name of the section type.287 288    n_objects : int289        Total number of objects.290 291    descr_regex_pattern : str, default=""292        Regex pattern to match for description of all objects.293        Ignored when `type_or_desc="type description".294 295    ignore_types : tuple of str, default=()296        Tuple of parameter/attribute/return names for which type description297        matching is ignored. Ignored when `type_or_desc="description".298    cSsg|]}t|��qSr1)r�)r[Zobjsr1r1r2r]�sz,_check_consistency_items.<locals>.<listcomp>�descriptionzThe description of Nr�z 'z' in z' does not match 'descr_regex_pattern': r��type specification�z and css�|]}t|�VqdSr�)r�)r[r�r1r1r2r��s�299�z+_check_consistency_items.<locals>.<genexpr>zThe z of z' is inconsistent between r�zChecking was skipped for z: z' as they were not found in all objects.)r��sumr�rG�re�searchr��textwrap�fillrur��keysr�rHr4r�)Z300items_docsZtype_or_desc�section�	n_objects�descr_regex_pattern�ignore_typesZskippedr�r�Znot_matchedr�r��msgr�Z301obj_groupsr1r1r2�_check_consistency_items�sL&302����303������rc		s�ddlm}	tdgd����fdd�}304i|305||dd��|306||d	d307��|308||dd��}t�}|D]%}
t�|
�s@t�|
�s@t�|
�rK|	t�|
��||
j	<q/t309d
t|
��d���t|�}|�
�D]b\}}tdd��}tdd��}|�
�D];\}}||D]2\}}}t||�r�d�|�����}d�t�dd�|D���}|||�|�|||�|�qyqqt|d|||d�t|d|||d�q]dS)a�Check consistency between docstring parameters/attributes/returns of objects.310 311    Checks if parameters/attributes/returns have the same type specification and312    description (ignoring whitespace) across `objects`. Intended to be used for313    related classes/functions/data descriptors.314 315    Entries that do not appear across all `objects` are ignored.316 317    Parameters318    ----------319    objects : list of {classes, functions, data descriptors}320        Objects to check.321        Objects may be classes, functions or data descriptors with docstrings that322        can be parsed by numpydoc.323 324    include_params : list of str or bool, default=False325        List of parameters to be included. If True, all parameters are included,326        if False, checking is skipped for parameters.327        Can only be set if `exclude_params` is None.328 329    exclude_params : list of str or None, default=None330        List of parameters to be excluded. If None, no parameters are excluded.331        Can only be set if `include_params` is True.332 333    include_attrs : list of str or bool, default=False334        List of attributes to be included. If True, all attributes are included,335        if False, checking is skipped for attributes.336        Can only be set if `exclude_attrs` is None.337 338    exclude_attrs : list of str or None, default=None339        List of attributes to be excluded. If None, no attributes are excluded.340        Can only be set if `include_attrs` is True.341 342    include_returns : list of str or bool, default=False343        List of returns to be included. If True, all returns are included,344        if False, checking is skipped for returns.345        Can only be set if `exclude_returns` is None.346 347    exclude_returns : list of str or None, default=None348        List of returns to be excluded. If None, no returns are excluded.349        Can only be set if `include_returns` is True.350 351    descr_regex_pattern : str, default=None352        Regular expression to match to all descriptions of included353        parameters/attributes/returns. If None, will revert to default behavior354        of comparing descriptions between objects.355 356    ignore_types : tuple of str, default=tuple()357        Tuple of parameter/attribute/return names to exclude from type description358        matching between objects.359 360    Examples361    --------362    >>> from sklearn.metrics import (accuracy_score, classification_report,363    ... mean_absolute_error, mean_squared_error, median_absolute_error)364    >>> from sklearn.utils._testing import assert_docstring_consistency365    ... # doctest: +SKIP366    >>> assert_docstring_consistency([mean_absolute_error, mean_squared_error],367    ... include_params=['y_true', 'y_pred', 'sample_weight'])  # doctest: +SKIP368    >>> assert_docstring_consistency([median_absolute_error, mean_squared_error],369    ... include_params=True)  # doctest: +SKIP370    >>> assert_docstring_consistency([accuracy_score, classification_report],371    ... include_params=["y_true"],372    ... descr_regex_pattern=r"Ground truth \(correct\) (labels|target values)")373    ... # doctest: +SKIP374    r)�NumpyDocStringrA)r�r��arg_namecs>|r|durtd|�d|�d���|duriS|�|||�iS)NTz
The 'exclude_z-' argument can be set only when the 'include_z' argument is True.F)�	TypeError)r�r�r�section_name�ZArgsr1r2�_create_argsNs��z2assert_docstring_consistency.<locals>._create_argsr�r��attrsZ375Attributes�returnsZReturnszDAll 'objects' must be one of: function, class or descriptor, got a: r�cS�tt�Sr��rr�r1r1r1r2r�nr�z.assert_docstring_consistency.<locals>.<lambda>cSr	r�r376r1r1r1r2r�or�r�csr�r�)r�r�r1r1r2r�us�z/assert_docstring_consistency.<locals>.<genexpr>r�)r�r�)r�N)Znumpydoc.docscraperr�dictr�r��377isfunction�isclass�getdocr+rr(r�r�rr�rHr�r�r378�
from_iterablerGr)�objectsZinclude_paramsZexclude_paramsZ
include_attrsZ
exclude_attrsZinclude_returnsZexclude_returnsr�r�rrZsection_argsZobjects_docr0r�r�rAZ379type_itemsZ380desc_items�obj_nameZobj_docr�Ztype_def�descr1rr2�assert_docstring_consistency�shM381��������382��	���r�.+�<c383Cs�tjdd�\}}t�|�z�t|d��}|�|�d��Wd�n1s&wYtj|g}t	�384t	�t	�t
j�d��}tj��}ztj�||dg�|d<Wn
ty]||d<Ynw|t|d�}	tj�d	�}385|386rr|387|	d388d	<||	d<zEz389t|fi|	��}Wnty�}z390td|j�d���d}~ww|�d�}t�||�r�|d
kr�d}
nd|��}
|
�d|��}t|��Wnty�}z391td|j�d���d}~wwWt�|�dSt�|�w)a[Utility to check assertions in an independent Python subprocess.392 393    The script provided in the source code should return 0 and the stdtout +394    stderr should not match the pattern `pattern`.395 396    This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle397 398    Parameters399    ----------400    source_code : str401        The Python source code to execute.402    pattern : str403        Pattern that the stdout + stderr should not match. By default, unless404        stdout + stderr are both empty, an error will be raised.405    timeout : int, default=60406        Time in seconds before timeout.407    z_src_test_sklearn.py)�suffix�wbzutf-8Nz..�408PYTHONPATH)�cwd�stderr�envZCOVERAGE_PROCESS_STARTr�timeoutzscript errored with output:409%srzExpected no outputz%The output was not supposed to match z$, got the following output instead: z!script timeout, output so far:410%s)r��mkstemprz�close�open�write�encoder6�411executabler��normpathrH�dirname�sklearn�__file__r{�copy�pathsep�KeyErrorrr|rr
rK�output�decoder�r�rur�unlink)Zsource_code�patternr�fd�source_file�f�cmdrrrBZcoverage_rc�out�eZexpectationr�r1r1r2r#�sX412�413414����415416�����
r#c
s|dkr|durt|�Stj||d���S|dkr,|dur!t|�Sttj||d����S|dkr7tj||d�S|dvr_tjd|d�}|j|||d	d417�}|dur]|D]}||�d�||<qQ|S|dkr�tjd|d�}	t�|���j	d
kr|�dd�dfn��|dur�dd�t418�jd
�D�}�fdd�t|�D�}419|	j
�|420�}|dur�t|j�D]\}}||vr�|�|||�|����}q�|S|dkr�tjd|d�}|j||dd�}|dur�|D]}|�|�|��|j��}q�|S|dkr�tjd|d�}|j||d�S|dk�rtjd|d�}	|	�|�S|dk�rtjd|d�}|j|d�S|dk�r1tjd|d�}|j||d�S|dk�r?t|d|d
�Sd|v�r�tj�|��sPt�|�}|dv�r]tjj||d�S|dk�rjtjj ||d�S|dk�rwtjj!||d�S|d k�r�tjj"||d�SdSdS)!a�Convert a given container to a specific array-like with a dtype.421 422    Parameters423    ----------424    container : array-like425        The container to convert.426    constructor_name : {"list", "tuple", "array", "sparse", "dataframe",             "series", "index", "slice", "sparse_csr", "sparse_csc",             "sparse_csr_array", "sparse_csc_array", "pyarrow", "polars",             "polars_series"}427        The type of the returned container.428    columns_name : index or array-like, default=None429        For pandas container supporting `columns_names`, it will affect430        specific names.431    dtype : dtype, default=None432        Force the dtype of the container. Does not apply to `"slice"`433        container.434    minversion : str, default=None435        Minimum version for package to install.436    categorical_feature_names : list of str, default=None437        List of column names to cast to categorical dtype.438 439    Returns440    -------441    converted_container442    r�N)r\�tuple�array)�pandasZ	dataframer6)�443minversionF)�columnsr\r'r&Zpyarrowr�cSsg|]}d|���qS)�colr1)r[r�r1r1r2r]sz&_convert_container.<locals>.<listcomp>cs"i|]
\}}|�dd�|f�qSr�r1)r[r�rI�r5r1r2�444<dictcomp>s"z&_convert_container.<locals>.<dictcomp>Zpolars�row)ZschemaZorientZseriesZ
pyarrow_arrayZ
polars_series)r�r��slicerrh)rhZ445sparse_csrZsparse_csr_arrayZ446sparse_cscZsparse_csc_array)#r�rZ�asarray�tolistr4�pytestZimportorskipZ	DataFrameZastype�ndimr��shape�	enumerate�TableZfrom_pydictZcolumn_namesZ447set_column�columnZdictionary_encodeZwith_columnsr9�castZCategoricalZSeriesr5�Indexr=rgrhriZ448atleast_2dZ449csr_matrixZ	csr_arrayZ450csc_matrixZ	csc_array)
�	containerZconstructor_nameZcolumns_namer\r7Zcategorical_feature_names�pdr�Zcol_name�parkZcol_idx�plr1r:r2�_convert_container�s�"451��452453454455456457458459460461462�rLcCst||||�S)a[Context manager to ensure exceptions are raised within a code block.463 464    This is similar to and inspired from pytest.raises, but supports a few465    other cases.466 467    This is only intended to be used in estimator_checks.py where we don't468    want to use pytest. In the rest of the code base, just use pytest.raises469    instead.470 471    Parameters472    ----------473    excepted_exc_type : Exception or list of Exception474        The exception that should be raised by the block. If a list, the block475        should raise one of the exceptions.476    match : str or list of str, default=None477        A regex that the exception message should match. If a list, one of478        the entries must match. If None, match isn't enforced.479    may_pass : bool, default=False480        If True, the block is allowed to not raise an exception. Useful in481        cases where some estimators may support a feature but others must482        fail with an appropriate error message. By default, the context483        manager will raise an exception if the block does not raise an484        exception.485    err_msg : str, default=None486        If the context manager fails (e.g. the block fails to raise the487        proper exception, or fails to match), then an AssertionError is488        raised with this message. By default, an AssertionError is raised489        with a default error message (depends on the kind of failure). Use490        this to indicate how users should fix their estimators to pass the491        checks.492 493    Attributes494    ----------495    raised_and_matched : bool496        True if an exception was raised and a match was found, False otherwise.497    )�_Raises)�expected_exc_type�match�may_passrar1r1r2�raises4s%rQc@seZdZdd�Zdd�ZdS)rMcCsBt|t�r|n|g|_t|t�r|gn||_||_||_d|_dS)NF)r'r�expected_exc_typesr��matchesrPra�raised_and_matched)r<rNrOrPrar1r1r2r=^s��498z_Raises.__init__cs��dur|jr	dS|jpd|j��}t|��t�fdd�|jD��s/|jdur-t|j���dS|jdurW|jpBd�d�|j�t���}t�fdd�|jD��sTt|���d|_	dS)	NTzDid not raise: c3s�|]}t�|�VqdSr�)r))r[�
expected_type)r�r1r2r�ts499��500�z#_Raises.__exit__.<locals>.<genexpr>FzIThe error message should contain one of the following patterns:501{}502Got {}r�c3s �|]}t�|t���VqdSr�)r�r�r�)r[rO)�	exc_valuer1r2r��s�)503rPrarRru�anyrSr-rHr�rT)r<r�rV�_rar1)r�rVr2rSis(�504505�506z_Raises.__exit__N)r+rTrUr=rSr1r1r1r2rM\srMc@sTeZdZdZddd�Zddd�Zdd	�Zd507d�Zdd
�Zdd�Z	dd�Z508dd�ZdS)�MinimalClassifieraMinimal classifier implementation without inheriting from BaseEstimator.509 510    This estimator should be tested with:511 512    * `check_estimator` in `test_estimator_checks.py`;513    * within a `Pipeline` in `test_pipeline.py`;514    * within a `SearchCV` in `test_search.py`.515    NcC�516||_dSr��r��r<r�r1r1r2r=��517zMinimalClassifier.__init__TcC�518d|jiS�Nr�r[�r<�deepr1r1r2rp�r]zMinimalClassifier.get_paramscK�"|��D]519\}}t|||�q|Sr��r��setattr�r<r�r��valuer1r1r2rq��zMinimalClassifier.set_paramscCs8t||�\}}t|�tj|dd�\|_}|��|_|S)NT)Z
return_counts)r!rrZ�unique�classes_�argmax�_most_frequent_class_idx)r<�Xrm�countsr1r1r2�fit�s520521zMinimalClassifier.fitcCsHt|�t|�}|jd|jjf}tj|tjd�}d|dd�|jf<|S)Nr)rBr\g�?)	r rrBri�sizerZZzerosZfloat64rk)r<rlZproba_shape�y_probar1r1r2�
predict_proba�szMinimalClassifier.predict_probacCs |�|�}|jdd�}|j|S)Nr�)Zaxis)rqrjri)r<rlrpZy_predr1r1r2�predict�s522523zMinimalClassifier.predictcC�ddlm}|||�|��S)Nr)�accuracy_score)�sklearn.metricsrtrr)r<rlrmrtr1r1r2�score��zMinimalClassifier.scorecCstdt�ddtdd�d�S)NZ524classifierT��required�Zestimator_typeZclassifier_tagsZregressor_tagsZtransformer_tagsZtarget_tags)rrrrPr1r1r2�__sklearn_tags__�s�z"MinimalClassifier.__sklearn_tags__r��T)r+rTrUrVr=rprqrnrqrrrvr{r1r1r1r2rY�s525	526rYc@sLeZdZdZddd�Zddd�Zdd	�Zd527d�Zdd
�Zdd�Z	dd�Z528dS)�MinimalRegressoraMinimal regressor implementation without inheriting from BaseEstimator.529 530    This estimator should be tested with:531 532    * `check_estimator` in `test_estimator_checks.py`;533    * within a `Pipeline` in `test_pipeline.py`;534    * within a `SearchCV` in `test_search.py`.535    NcCrZr�r[r\r1r1r2r=�r]zMinimalRegressor.__init__TcCr^r_r[r`r1r1r2rp�r]zMinimalRegressor.get_paramscKrbr�rcrer1r1r2rq�rgzMinimalRegressor.set_paramscCs$t||�\}}d|_t�|�|_|S�NT)r!�536is_fitted_rZ�mean�_mean�r<rlrmr1r1r2rn�szMinimalRegressor.fitcCs*t|�t|�}tj|jdfd�|jS)Nr)rB)r rrZZonesrBr�)r<rlr1r1r2rr�szMinimalRegressor.predictcCrs)Nr)�r2_score)rur�rr)r<rlrmr�r1r1r2rv�rwzMinimalRegressor.scorecCstddt�dtdd�d�S)NZ	regressorTrxrz)rrrrPr1r1r2r{�s�z!MinimalRegressor.__sklearn_tags__r�r|)r+rTrUrVr=rprqrnrrrvr{r1r1r1r2r}�s537	538r}c@sReZdZdZddd�Zddd�Zdd	�Zdd539d�Zddd
�Zddd�Z	dd�Z540dS)�MinimalTransformeraMinimal transformer implementation without inheriting from541    BaseEstimator.542 543    This estimator should be tested with:544 545    * `check_estimator` in `test_estimator_checks.py`;546    * within a `Pipeline` in `test_pipeline.py`;547    * within a `SearchCV` in `test_search.py`.548    NcCrZr�r[r\r1r1r2r=�r]zMinimalTransformer.__init__TcCr^r_r[r`r1r1r2rp�r]zMinimalTransformer.get_paramscKrbr�rcrer1r1r2rqrgzMinimalTransformer.set_paramscCst|�d|_|Sr~)rrr�r1r1r2rnszMinimalTransformer.fitcCst|�t|�}|Sr�)r rr�r1r1r2�	transformszMinimalTransformer.transformcCs|�||��||�Sr�)rnr�r�r1r1r2�
fit_transformsz MinimalTransformer.fit_transformcCstdddt�tdd�d�S)NZtransformerFrxrz)rrrrPr1r1r2r{s�z#MinimalTransformer.__sklearn_tags__r�r|)r+rTrUrVr=rprqrnr�r�r{r1r1r1r2r��s549 550 551552553554r�c	Cs�zt�|�}Wnttfyt|�d���wtj�d�dur$td��ddlm	}||�555d��}|dkrC|dkrC|jj�
�sCtd	��|dkrb|d556krbt�d�dkrVtd
��|jj�
�s`td��|S|dkrvddl}|jj��dkrvtd��|S)Nz/ is not installed: not checking array_api inputZSCIPY_ARRAY_APIz8SCIPY_ARRAY_API is not set: not checking array_api inputr)�
get_namespacer�Ztorch�cudaz2PyTorch test requires cuda, which is not available�mpsZPYTORCH_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�ModuleNotFoundErrorrtr"rzr{r|Z"sklearn.externals.array_api_compatr�r>�backendsr�Zis_built�getenvr�r�ZruntimeZgetDeviceCount)Zarray_namespaceZdeviceZ	array_modr�Zxpr�r1r1r2�_array_api_for_testss>��557���	�r�cCs�tGdd�d��}|dtd�|dtd�|dtd�|ddtd�|ddtd�|dd	td�|dd558td�|ddtd�|ddtd�|dd
td�|ddtd�|ddtd�|ddtd�g
S)Nc@s:eZdZUded<dZeed<eZeeed<dd�Z	dS)	z4_get_warnings_filters_info_list.<locals>.WarningInfozwarnings._ActionKind�actionrXr�r&cSsD|jjdkr|jj}n|jj�d|jj��}|j�d|j�d|��S)N�builtinsr�r�)r&rTr+r�r�r;r1r1r2�to_filterwarning_strQs559zI_get_warnings_filters_info_list.<locals>.WarningInfo.to_filterwarning_strN)560r+rTrU�__annotations__r�r�r*r&r(r�r1r1r1r2�WarningInfoKs561562r�r�r%r>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.utcfromtimestampzast.Num is deprecatedzAttribute n is deprecatedzast.Str is deprecatedzAttribute s is deprecatedz0.+scattermapbox.+deprecated.+scattermap.+instead)r�DeprecationWarning�
FutureWarningr)r�r1r1r2�_get_warnings_filters_info_listJs`563564565�����������r�cCst�}dd�|D�S)NcSsg|]}|���qSr1)r�)r[�warning_infor1r1r2r]�s��z2get_pytest_filterwarning_lines.<locals>.<listcomp>)r�)Zwarning_filters_info_listr1r1r2�get_pytest_filterwarning_lines�s�r�cCs*t�}|D]
}tj|j|j|jd�qdS)Nr�)r�r4�filterwarningsr�r�r&)Zwarnings_filters_info_listr�r1r1r2�turn_warnings_into_errors�s��r�)NrWTrXT)rYrfrX)r)F)r�F)NN)rr)NNNN)NFN)urVr��566contextlibr�r�r�rzZos.pathr~r�r�r�r6r�r�Zunittestr4�collectionsrr�collections.abcr�dataclassesrr�rrr	�	itertoolsr567r�568subprocessrr
rrr��numpyrZZscipyrgZ
numpy.testingrrdrrrrr%Z
sklearn.utilsrrrrrZsklearn.utils._array_apirZsklearn.utils.fixesrrrZsklearn.utils.multiclassrZsklearn.utils.validationrr r!�__all__�caser"r*r3r/rnrrrvZARRAY_API_COMPAT_FUNCTIONALrtrKr@�markZskipifZ
skip_if_32bitZxfailZfails_if_unstable_openblasZparallel�mpZskip_if_no_parallelZ'skip_if_array_api_compat_not_configured�platformZ!if_safe_multiprocessing_with_blasZskip_if_no_numpydocr}r�r�r�r�r�r�r�r�r�r4rrr#rLrQ�AbstractContextManagerrMrYr}r�r�r�r�r�r1r1r1r2�<module>s�569,:570571I572*	��573��574�575��576577578579	
)580�O581�582A583584l(-8/--U
Aluode/PerceptionLabPortable · CoolFace