U
    9%eN5                     @   s   d Z ddlZddlmZ ddlZddlmZ ddlmZ ddl	m
Z
 dd	 Zd
d Zdd Zdd Zdd Zdd ZG dd dZdd Zdd ZG dd dZe Zdd Zdd Zd'dd d!d"Zd#d$ Zd%d& ZdS )(zTools to support array_api.    Nwraps   )
get_config   )parse_versionc                 C   s\   | rXzddl }W n tk
r,   tdY nX ttj}d}|t|k rXtd| ddS )zCheck that array_api_compat is installed and NumPy version is compatible.

    array_api_compat follows NEP29, which has a higher minimum NumPy version than
    scikit-learn.
    r   NzKarray_api_compat is required to dispatch arrays using the API specificationz1.21zNumPy must be z7 or newer to dispatch array using the API specification)array_api_compatImportErrorr   numpy__version__)array_api_dispatchr   Znumpy_versionZmin_numpy_version r   W/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sklearn/utils/_array_api.py_check_array_api_dispatch   s    


r   c                 C   s   t | tjtjfrdS | jS )a  Hardware device the array data resides on.

    Parameters
    ----------
    x : array
        Array instance from NumPy or an array API compatible library.

    Returns
    -------
    out : device
        `device` object (see the "Device Support" section of the array API spec).
    cpu)
isinstancer
   ndarrayZgenericdevicexr   r   r   r   $   s    r   c                 C   s   t | jS )zReturn the total number of elements of x.

    Parameters
    ----------
    x : array
        Array instance from NumPy or an array API compatible library.

    Returns
    -------
    out : int
        Total number of elements.
    )mathprodshaper   r   r   r   size6   s    r   c                 C   s
   | j dkS )z%Return True if xp is backed by NumPy.>   r
   numpy.array_apiarray_api_compat.numpy)__name__xpr   r   r   _is_numpy_namespaceF   s    r   c                   s4   t |tr"t fdd|D S t |dS dS )zReturns a boolean indicating whether a provided dtype is of type "kind".

    Included in the v2022.12 of the Array API spec.
    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
    c                 3   s   | ]}t  |d V  qdS r   N_isdtype_single.0kdtyper   r   r   	<genexpr>R   s     zisdtype.<locals>.<genexpr>r   N)r   tupleanyr"   )r'   kindr   r   r&   r   isdtypeK   s    
r,   c                   s  t |tr
|dkr jkS |dkr> jjjjhkS |dkr^ jjj	j
hkS |dkr~t fdddD S |dkr jjhkS |d	krt }td
r|j tdr|j  |kS |dk rt fdddD S td|n |kS d S )Nboolsigned integerunsigned integerintegralc                 3   s   | ]}t  |d V  qdS r    r!   r#   r&   r   r   r(   `   s   z"_isdtype_single.<locals>.<genexpr>)r.   r/   real floatingcomplex floating	complex64
complex128numericc                 3   s   | ]}t  |d V  qdS r    r!   r#   r&   r   r   r(   p   s   )r0   r1   r2   zUnrecognized data type kind: )r   strr-   int8int16int32int64uint8uint16uint32uint64r*   float32float64sethasattraddr3   r4   
ValueError)r'   r+   r   Zcomplex_dtypesr   r&   r   r"   W   s4    



r"   c                   @   s6   e Zd ZdZdd Zdd Zdd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_namespacer   r   r   __init__   s    z_ArrayAPIWrapper.__init__c                 C   s   t | j|S rF   )getattrrG   )rH   namer   r   r   __getattr__   s    z_ArrayAPIWrapper.__getattr__r   axisc                   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 )Nr   rM   >   r   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   r$   iXr   r   
<listcomp>   s     z)_ArrayAPIWrapper.take.<locals>.<listcomp>c                    s   g | ]} |d d f qS rF   r   rO   rQ   r   r   rS      s     c                    s   g | ]} d d |f qS rF   r   rO   rQ   r   r   rS      s     )rG   r   r
   takeasarrayrD   ndimstack)rH   rR   indicesrN   ZX_npselectedr   rQ   r   rT      s    

z_ArrayAPIWrapper.takec                 C   s   t ||| jdS Nr   )r,   rG   rH   r'   r+   r   r   r   r,      s    z_ArrayAPIWrapper.isdtypeN)r   
__module____qualname____doc__rI   rL   rT   r,   r   r   r   r   rE   z   s
   rE   c                 C   s   | dkrt d| d S )N>   r   NzUnsupported device for NumPy: )rD   )r   r   r   r   _check_device_cpu   s    r_   c                    s   t   fdd}|S )Nc                     s   t |dd   | |S )Nr   )r_   pop)argskwargsfuncr   r   wrapped_func   s    z(_accept_device_cpu.<locals>.wrapped_funcr   )rd   re   r   rc   r   _accept_device_cpu   s    rf   c                   @   s   e Zd ZdZdddddddd	d
ddhZddddddddddddhZdd Ze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"d/d0d1Zd2d3 Zd"S )4_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.
    ZarangeemptyZ
empty_likeeyefullZ	full_likeZlinspaceZonesZ	ones_likeZzerosZ
zeros_liker7   r8   r9   r:   r;   r<   r=   r>   r?   r@   r3   r4   c                 C   s4   t t|}|| jkrt|S || jkr0t|S |S rF   )rJ   r
   _CREATION_FUNCSrf   _DTYPESr'   )rH   rK   attrr   r   r   rL      s    



z_NumPyAPIWrapper.__getattr__c                 C   s   t jS rF   )r
   Zbool_)rH   r   r   r   r-      s    z_NumPyAPIWrapper.boolTunsafecopycastingc                C   s   |j |||dS )Nro   )astype)rH   r   r'   rp   rq   r   r   r   rr      s    z_NumPyAPIWrapper.astypeN)r'   r   rp   c                C   s2   t | |dkr tj|d|dS tj||dS d S )NT)rp   r'   )r'   )r_   r
   arrayrU   )rH   r   r'   r   rp   r   r   r   rU      s    z_NumPyAPIWrapper.asarrayc                 C   s   t j|ddS )NT)Zreturn_inverser
   uniquerH   r   r   r   r   unique_inverse   s    z_NumPyAPIWrapper.unique_inversec                 C   s   t j|ddS )NT)Zreturn_countsrt   rv   r   r   r   unique_counts  s    z_NumPyAPIWrapper.unique_countsc                 C   s
   t |S rF   rt   rv   r   r   r   unique_values  s    z_NumPyAPIWrapper.unique_valuesrM   c                C   s   t j||dS )NrM   )r
   Zconcatenate)rH   arraysrN   r   r   r   concat  s    z_NumPyAPIWrapper.concat)rp   c                C   s>   t |ts"td|dt| |dkr2| }t||S )zGives a new shape to an array without changing its data.

        The Array API specification requires shape to be a tuple.
        https://data-apis.org/array-api/latest/API_specification/generated/array_api.reshape.html
        zshape must be a tuple, got z	 of type T)r   r)   	TypeErrortyperp   r
   reshape)rH   r   r   rp   r   r   r   r~     s    
z_NumPyAPIWrapper.reshapec                 C   s   t ||| dS rZ   )r,   r[   r   r   r   r,     s    z_NumPyAPIWrapper.isdtype)r   r\   r]   r^   rk   rl   rL   propertyr-   rr   rU   rw   rx   ry   r{   r~   r,   r   r   r   r   rg      sJ   
rg   c                  G   sP   t  d }|stdfS t| ddl}|j|  d }}|jdkrHt|}||fS )a  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. If any of the `arrays` are not arrays,
        the namespace defaults to NumPy.

    is_array_api_compliant : bool
        True if the arrays are containers that implement the Array API spec.
        Always False when array_api_dispatch=False.
    r   Fr   NT>   cupy.array_apir   )r   _NUMPY_API_WRAPPER_INSTANCEr   r   get_namespacer   rE   )rz   r   r   	namespaceZis_array_api_compliantr   r   r   r   !  s    +

r   c                 C   s>   t | \}}t|r*|tt| S dd||    S )Ng      ?)r   r   rU   specialZexpitr
   exp)rR   r   _r   r   r   _expit`  s    r   r   c                C   sd   |dkrt | \}}t|rP|dkr6tj| ||d} nt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.
    NT)orderr'   )r'   rp   )r   r   r
   rs   rU   )rs   r'   r   rp   r   r   r   r   r   _asarray_with_orderh  s    
r   c                 C   sF   |j }|dkr|   S |dkr,| j S |dkr<|  S t| S )z*Convert X into a NumPy ndarray on the CPU.>   array_api_compat.torchtorchr   >   array_api_compat.cupycupy)r   r   r
   Z_arraygetrU   )rs   r   Zxp_namer   r   r   _convert_to_numpy  s    
r   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.

    The converter is called on all NumPy arrays and arrays that support the
    `DLPack interface <https://dmlc.github.io/dlpack/latest/>`__.

    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   )cloneZ
__dlpack__)	Zsklearn.baser   varsitemsrB   r   r
   r   setattr)Z	estimator	converterr   Znew_estimatorkey	attributer   r   r    _estimator_with_converted_arrays  s    r   )NNN)r^   r   	functoolsr   r
   Zscipy.specialr   _configr   fixesr   r   r   r   r   r,   r"   rE   r_   rf   rg   r   r   r   r   r   r   r   r   r   r   <module>   s,   #0	f?