U
    3dL                     @   sn   d Z ddlZddlmZ ddlmZ G dd dZG dd dZd	d
 Zdd Z	dddZ
dd Zdd ZdS )zTools to support array_api.    N   )
get_configc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_ArrayAPIWrappera  sklearn specific Array API compatibility wrapper

    This wrapper makes it possible for scikit-learn maintainers to
    deal with discrepancies between different implementations of the
    Python array API standard and its evolution over time.

    The Python array API standard specification:
    https://data-apis.org/array-api/latest/

    Documentation of the NumPy implementation:
    https://numpy.org/neps/nep-0047-array-api-standard.html
    c                 C   s
   || _ d S N)
_namespace)selfZarray_namespace r   </tmp/pip-unpacked-wheel-zrfo1fqw/sklearn/utils/_array_api.py__init__   s    z_ArrayAPIWrapper.__init__c                 C   s   t | j|S r   )getattrr   r   namer   r   r	   __getattr__   s    z_ArrayAPIWrapper.__getattr__c                   s   | j jdkr(tj ||d}| j |S |dkr>td|  jdkrXtd j |dkr jdkr~ fd	d
|D }q fdd
|D }n fdd
|D }| j j||dS )Nnumpy.array_apiaxis>   r      z&Only axis in (0, 1) is supported. Got >   r   r   z(Only X.ndim in (1, 2) is supported. Got r   r   c                    s   g | ]} | qS r   r   .0iXr   r	   
<listcomp>,   s     z)_ArrayAPIWrapper.take.<locals>.<listcomp>c                    s   g | ]} |d d f qS r   r   r   r   r   r	   r   .   s     c                    s   g | ]} d d |f qS r   r   r   r   r   r	   r   0   s     )r   __name__numpytakeasarray
ValueErrorndimstack)r   r   indicesr   ZX_npselectedr   r   r	   r      s    

z_ArrayAPIWrapper.takeN)r   
__module____qualname____doc__r
   r   r   r   r   r   r	   r      s   r   c                   @   s`   e Zd ZdZdd ZdddddZd	d	d	d
ddZdd Zdd Zdd Z	d	dddZ
d	S )_NumPyApiWrapperaR  Array API compat wrapper for any numpy version

    NumPy < 1.22 does not expose the numpy.array_api namespace. This
    wrapper makes it possible to write code that uses the standard
    Array API while working with any version of NumPy supported by
    scikit-learn.

    See the `get_namespace()` public function for more details.
    c                 C   s
   t t|S r   )r   r   r   r   r   r	   r   ?   s    z_NumPyApiWrapper.__getattr__TZunsafecopycastingc                C   s   |j |||dS )Nr&   )astype)r   xdtyper'   r(   r   r   r	   r)   B   s    z_NumPyApiWrapper.astypeN)r+   devicer'   c                C   s*   |dkrt j|d|dS t j||dS d S )NT)r'   r+   )r+   )r   arrayr   )r   r*   r+   r,   r'   r   r   r	   r   F   s    z_NumPyApiWrapper.asarrayc                 C   s   t j|ddS )NT)Zreturn_inverser   uniquer   r*   r   r   r	   unique_inverseM   s    z_NumPyApiWrapper.unique_inversec                 C   s   t j|ddS )NT)Zreturn_countsr.   r0   r   r   r	   unique_countsP   s    z_NumPyApiWrapper.unique_countsc                 C   s
   t |S r   r.   r0   r   r   r	   unique_valuesS   s    z_NumPyApiWrapper.unique_valuesr   c                C   s   t j||dS )Nr   )r   Zconcatenate)r   arraysr   r   r   r	   concatV   s    z_NumPyApiWrapper.concat)r   r"   r#   r$   r   r)   r   r1   r2   r3   r5   r   r   r   r	   r%   4   s   
r%   c                  G   sl   t  d st dfS dd | D }|s.tdt|dkrHtd| |\}|dkr`t dfS t|d	fS )
aq  Get namespace of arrays.

    Introspect `arrays` arguments and return their common Array API
    compatible namespace object, if any. NumPy 1.22 and later can
    construct such containers using the `numpy.array_api` namespace
    for instance.

    See: https://numpy.org/neps/nep-0047-array-api-standard.html

    If `arrays` are regular numpy arrays, an instance of the
    `_NumPyApiWrapper` compatibility wrapper is returned instead.

    Namespace support is not enabled by default. To enabled it
    call:

      sklearn.set_config(array_api_dispatch=True)

    or:

      with sklearn.config_context(array_api_dispatch=True):
          # your code here

    Otherwise an instance of the `_NumPyApiWrapper`
    compatibility wrapper is always returned irrespective of
    the fact that arrays implement the `__array_namespace__`
    protocol or not.

    Parameters
    ----------
    *arrays : array objects
        Array objects.

    Returns
    -------
    namespace : module
        Namespace shared by array objects.

    is_array_api : bool
        True of the arrays are containers that implement the Array API spec.
    Zarray_api_dispatchFc                 S   s4   h | ],}t |ttttfst|d r,| ndqS )__array_namespace__N)
isinstanceboolintfloatcomplexhasattrr6   )r   r*   r   r   r	   	<setcomp>   s   z get_namespace.<locals>.<setcomp>zUnrecognized array inputr   z&Multiple namespaces for array inputs: NT)r   r%   r   lenr   )r4   
namespacesxpr   r   r	   get_namespaceZ   s    -


rA   c                 C   s@   t | \}}|jdkr,|tt| S dd||    S )N>   r   r   g      ?)rA   r   r   specialZexpitr   exp)r   r@   _r   r   r	   _expit   s    
rE   c                 C   sP   |dkrt | \}}|jdkr<tj| ||d} |j| |dS |j| ||dS dS )a  Helper to support the order kwarg only for NumPy-backed arrays

    Memory layout parameter `order` is not exposed in the Array API standard,
    however some input validation code in scikit-learn needs to work both
    for classes and functions that will leverage Array API only operations
    and for code that inherently relies on NumPy backed data containers with
    specific memory layout constraints (e.g. our own Cython code). The
    purpose of this helper is to make it possible to share code for data
    container validation without memory copies for both downstream use cases:
    the `order` parameter is only enforced if the input array implementation
    is NumPy based, otherwise `order` is just silently ignored.
    N>   r   r   )orderr+   )r'   )r+   r'   )rA   r   r   r   )r-   r+   rF   r'   r@   rD   r   r   r	   _asarray_with_order   s    
rG   c                 C   sL   ddg}|j |kr*d|}td| |j dkr>| j S t| S dS )zsConvert X into a NumPy ndarray.

    Only works on cupy.array_api and numpy.array_api and is used for testing.
    r   zcupy.array_apiz, zSupported namespaces are: N)r   joinr   Z_arraygetr   r   )r-   r@   Zsupported_array_apiZsupport_array_api_strr   r   r	   _convert_to_numpy   s    



rJ   c                 C   sX   ddl m} || }t|  D ]2\}}t|ds>t|tjrF||}t||| q |S )a[  Create new estimator which converting all attributes that are arrays.

    Parameters
    ----------
    estimator : Estimator
        Estimator to convert

    converter : callable
        Callable that takes an array attribute and returns the converted array.

    Returns
    -------
    new_estimator : Estimator
        Convert estimator
    r   )cloner6   )	Zsklearn.baserK   varsitemsr<   r7   r   Zndarraysetattr)Z	estimator	converterrK   Znew_estimatorkey	attributer   r   r	    _estimator_with_converted_arrays   s     rR   )NNNN)r$   r   _configr   Zscipy.specialrB   r   r%   rA   rE   rG   rJ   rR   r   r   r   r	   <module>   s   -&F
