
    0Ph                        d 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m	Z
 ddlmZ ddlmZ ddlmZ dd	hZd;dZd;dZd Zd Zd
efddZd Zd Zd Zd Zd Zd Zd Zd Zd Z  G d d          Z! e!            Z"d
efddZ#d
efdddZ$d
efddZ%d<d Z&d=d"Z'd# Z(d$ Z)d>d%Z*d?d&Z+d?d'Z,d?d(Z-	 d@ddd)d*Z.d<d+Z/d, Z0d- Z1d. Z2d/ Z3d0ddd1d2Z4dAd3Z5dBd4Z6dBd5Z7dCd6Z8dd7d8Z9d@d9Z:d<d:Z;dS )DzTools to support array_api.    Nwraps   )
get_config   )parse_versionnumpyzarray_api_compat.numpyTc              #   4   K   dD ]}| s
|t           v r|V  dS )a7  Yield supported namespace.

    This is meant to be used for testing purposes only.

    Parameters
    ----------
    include_numpy_namespaces : bool, default=True
        If True, also yield numpy namespaces.

    Returns
    -------
    array_namespace : str
        The name of the Array API namespace.
    )r	   array_api_strictcupytorchN)_NUMPY_NAMESPACE_NAMES)include_numpy_namespacesarray_namespaces     X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/utils/_array_api.pyyield_namespacesr      sH      
   ( 	O?U,U,U     c              #      K   t          |           D ]9}|dk    r*t          j        dd          D ]\  }}|||fV  |ddfV  2|ddfV  :dS )a  Yield supported namespace, device, dtype tuples for testing.

    Use this to test that an estimator works with all combinations.

    Parameters
    ----------
    include_numpy_namespaces : bool, default=True
        If True, also yield numpy namespaces.

    Returns
    -------
    array_namespace : str
        The name of the Array API namespace.

    device : str
        The name of the device on which to allocate the arrays. Can be None to
        indicate that the default value should be used.

    dtype_name : str
        The name of the data type to use for arrays. Can be None to indicate
        that the default value should be used.
    )r   r   )cpucuda)float64float32mpsr   N)r   	itertoolsproduct)r   r   devicedtypes       r   )yield_namespace_device_dtype_combinationsr   5   s      . ,!9   
. 
. g%%!*!2!7" " 5 5 &vu44444!5)33333!4-----
. 
.r   c                    | r	 ddl }n# t          $ r t          d          w xY wt          t          j                  }d}|t          |          k     r t          d| dt          j         d          t          t
          j                  }d}|t          |          k     rt          d	| d
          t          j                            d          dk    rt          d          dS 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 z or newer (found z5) to dispatch array using the array API specificationz1.14.0zSciPy must be zY or newer (found {scipy.__version__}) to dispatch array using the array API specificationSCIPY_ARRAY_API1zScikit-learn array API support was enabled but scipy's own support is not enabled. Please set the SCIPY_ARRAY_API=1 environment variable before importing sklearn or scipy. More details at: https://docs.scipy.org/doc/scipy/dev/api-dev/array_api.html)
array_api_compatImportErrorr   r	   __version__scipyosenvirongetRuntimeError)array_api_dispatchr"   numpy_versionmin_numpy_versionscipy_versionmin_scipy_versions         r   _check_array_api_dispatchr/   Y   sR     !	##### 	 	 	!  	 &e&788"=):;;;;/!2 / /%/ / /   &e&788$=):;;;;/!2 / / /   :>>+,,33N  9! !6 43s   	 #c                     t          | t          j        t          j        f          s$t	          | d          rt                      d         sdS | j        S )z0Hardware device where the array data resides on.r   r*   N)
isinstancer	   ndarraygenerichasattrr   r   )arrays    r   _single_array_devicer6      sT     	55=%-899uh'' ||01 t|r   remove_noneremove_typesc           	          t          || |d}|sdS t          |d                   }|dd         D ]F}t          |          }||k    r/t          dt          |           dt          |                     G|S )aD  Hardware device where the array data resides on.

    If the hardware device is not the same for all arrays, an error is raised.

    Parameters
    ----------
    *array_list : arrays
        List of array instances from NumPy or an array API compatible library.

    remove_none : bool, default=True
        Whether to ignore None objects passed in array_list.

    remove_types : tuple or list, default=(str,)
        Types to ignore in array_list.

    Returns
    -------
    out : device
        `device` object (see the "Device Support" section of the array API spec).
    r7   Nr   r   z$Input arrays use different devices: z, )_remove_non_arraysr6   
ValueErrorstr)r8   r9   
array_listdevice_r5   device_others         r   r   r      s    * $	<  J  t":a=11G ABB  +E22l""'s7|| ' '|$$' '   # Nr   c                 4    t          j        | 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shape)xs    r   sizerF      s     9QWr   c                     | j         t          v S )z%Return True if xp is backed by NumPy.)__name__r   xps    r   _is_numpy_namespacerK      s    ;000r   c                 t   t          |          r?ddlm}  || ||          \  }}|                    t	          j        ||                    S | j        |j        cxk    rdk    sn J |                    |                    |                    |           |                    |          g                    S )Nr   )cached_uniquerI   )	rK   _uniquerM   asarrayr	   union1dndimunique_valuesconcat)abrJ   rM   a_uniqueb_uniques         r   _union1drX      s    2 =*******]1aB777(zz%-(;;<<<6QV    q      BIIr'7'7':':B<L<LQ<O<O&PQQRRRr   c                     t          |t                    rt           fd|D                       S t           |          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   <   K   | ]}t          |           V  dS rI   N_isdtype_single.0kr   rJ   s     r   	<genexpr>zisdtype.<locals>.<genexpr>   s2      BB?5!333BBBBBBr   rI   )r1   tupleanyr]   )r   kindrJ   s   ` `r   isdtypere      sS     $ 3BBBBBTBBBBBBudr2222r   c                    t          |t                    r.|dk    r j        k    S |dk    r j        j        j        j        hv S |dk    r j        j        j	        j
        hv S |dk    rt           fddD                       S |dk    r t                    v S |dk    rft                      }t          d	          r|                    j                   t          d
          r|                    j                    |v S |dk    rt           fddD                       S t%          d|           |k    S )Nboolsigned integerunsigned integerintegralc              3   <   K   | ]}t          |           V  dS r[   r\   r^   s     r   ra   z"_isdtype_single.<locals>.<genexpr>   F          qR000     r   )rh   ri   real floatingcomplex floating	complex64
complex128numericc              3   <   K   | ]}t          |           V  dS r[   r\   r^   s     r   ra   z"_isdtype_single.<locals>.<genexpr>  rl   r   )rj   rm   rn   zUnrecognized data type kind: )r1   r=   rg   int8int16int32int64uint8uint16uint32uint64rc   supported_float_dtypessetr4   addro   rp   r<   )r   rd   rJ   complex_dtypess   ` ` r   r]   r]      s   $ 6>>BG##%%%RWbh"(CCC'''RXry")RYGGGZ     ?      _$$226666''' UUNr;'' 1""2<000r<(( 2""2=111N**Y     J     
 ETEEFFF}r   c                 f    t          | d          r| j        | j        | j        fS | j        | j        fS )aA  Supported floating point types for the namespace.

    Note: float16 is not officially part of the Array API spec at the
    time of writing but scikit-learn estimators and functions can choose
    to accept it when xp.float16 is defined.

    https://data-apis.org/array-api/latest/API_specification/data_types.html
    float16)r4   r   r   r   rI   s    r   r{   r{     s8     r9 (
BJ
33
BJ''r   c                 n    t          |           \  }|rt          |           fd|D             S |S )a  Ensure that all arrays use the same namespace and device as reference.

    If necessary the arrays are moved to the same namespace and device as
    the reference array.

    Parameters
    ----------
    reference : array
        Reference array.

    *arrays : array
        Arrays to check.

    Returns
    -------
    arrays : list
        Arrays with the same namespace and device as reference.
    c                 >    g | ]}                     |           S )r   )rO   )r_   rT   r?   rJ   s     r   
<listcomp>z2ensure_common_namespace_device.<locals>.<listcomp>6  s)    >>>!

1W
-->>>r   )get_namespacer   )	referencearraysis_array_apir?   rJ   s      @@r   ensure_common_namespace_devicer     sO    & %Y//B ##>>>>>v>>>>r   c                 2    | dvrt          d|           d S )N>   Nr   zUnsupported device for NumPy: )r<   r   s    r   _check_device_cpur   ;  s,    ]""D&DDEEE #"r   c                 <     t                      fd            }|S )Nc                  Z    t          |                    dd                       | i |S )Nr   )r   pop)argskwargsfuncs     r   wrapped_funcz(_accept_device_cpu.<locals>.wrapped_funcA  s4    &**Xt44555tT$V$$$r   r   )r   r   s   ` r   _accept_device_cpur   @  s4    
4[[% % % % [% r   c                       e Zd ZdZh dZh dZd Zed             Zdddd	Z	d
d
d
ddZ
d Zd Zd Zd Zd
ddZd
ddZd Zd Zd
S )_NumPyAPIWrappera  Array API compat wrapper for any numpy version

    NumPy < 2 does not implement the namespace. NumPy 2 and later should
    progressively implement more an more of the latest Array API spec but this
    is still work in progress at this time.

    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.
    >   eyefullonesemptyzerosarangelinspace	full_like	ones_like
empty_like
zeros_like>   rs   rt   ru   rv   rw   rx   ry   rz   r   r   r   ro   rp   c                     t          t          |          }|| j        v rt          |          S || j        v rt          j        |          S |S N)getattrr	   _CREATION_FUNCSr   _DTYPESr   )selfnameattrs      r   __getattr__z_NumPyAPIWrapper.__getattr__}  sS    ud## 4'''%d+++ 4<;t$$$r   c                     t           j        S r   )r	   bool_)r   s    r   rg   z_NumPyAPIWrapper.bool  s
    {r   Tunsafecopycastingc                2    |                     |||          S )Nr   )astype)r   rE   r   r   r   s        r   r   z_NumPyAPIWrapper.astype  s    xxD'x:::r   N)r   r   r   c                    t          |           |du rt          j        |d|          S t          j        ||          S )NT)r   r   r   )r   r	   r5   rO   )r   rE   r   r   r   s        r   rO   z_NumPyAPIWrapper.asarray  sE    &!!!4<<;qt59999=%0000r   c                 .    t          j        |d          S )NT)return_inverser	   uniquer   rE   s     r   unique_inversez_NumPyAPIWrapper.unique_inverse  s    |Ad3333r   c                 .    t          j        |d          S )NT)return_countsr   r   s     r   unique_countsz_NumPyAPIWrapper.unique_counts  s    |AT2222r   c                 *    t          j        |          S r   r   r   s     r   rR   z_NumPyAPIWrapper.unique_values  s    |Ar   c                 2    t          j        |ddd          S )NT)return_indexr   r   r   r   s     r   
unique_allz_NumPyAPIWrapper.unique_all  s$    |DT
 
 
 	
r   axisc                .    t          j        ||          S )Nr   )r	   concatenate)r   r   r   s      r   rS   z_NumPyAPIWrapper.concat  s     d3333r   )r   c                    t          |t                    s"t          d|dt          |                     |du r|                                }t          j        ||          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)r1   rb   	TypeErrortyper   r	   reshape)r   rE   rD   r   s       r   r   z_NumPyAPIWrapper.reshape  sk     %'' 	MeMMUMM   4<<A}Q&&&r   c                 J    	 t          |||           S # t          $ r Y dS w xY w)NrI   F)re   r   )r   r   rd   s      r   re   z_NumPyAPIWrapper.isdtype  s@    	5$40000 	 	 	 55	s    
""c                 ,    t          j        ||          S r   )r	   power)r   x1x2s      r   powz_NumPyAPIWrapper.pow  s    {2r"""r   )rH   
__module____qualname____doc__r   r   r   propertyrg   r   rO   r   r   rR   r   rS   r   re   r    r   r   r   r   I  sB       
 
$  O  G$
 
 
   X (,X ; ; ; ; ; #'t$ 1 1 1 1 14 4 43 3 3  
 
 

 &* 4 4 4 4 4 )- ' ' ' ' '	 	 	# # # # #r   r   c                     g }t          |          }|D ]B}| r|t          ||          rt          j        |          r-|                    |           C|S )aP  Filter arrays to exclude None and/or specific types.

    Raise ValueError if no arrays are left after filtering.

    Sparse arrays are always filtered out.

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

    remove_none : bool, default=True
        Whether to ignore None objects passed in arrays.

    remove_types : tuple or list, default=(str,)
        Types to ignore in the arrays.

    Returns
    -------
    filtered_arrays : list
        List of arrays filtered as requested. An empty list is returned if no input
        passes the filters.
    )rb   r1   spissparseappend)r8   r9   r   filtered_arraysr5   s        r   r;   r;     s{    0 O&&L & & 	5=e\** 	;u 	u%%%%r   )r8   r9   rJ   c                 0   t                      d         }|s||dfS t          dfS ||dfS t          || |d}|s	t          dfS t          |           ddl} |j        | d}}|j        dk    r&t          |d          r|                    d	
           ||fS )a  Get namespace of arrays.

    Introspect `arrays` arguments and return their common Array API compatible
    namespace object, if any.

    Note that sparse arrays are filtered by default.

    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.

    Note that if no arrays pass the set filters, ``_NUMPY_API_WRAPPER_INSTANCE, False``
    is returned.

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

    remove_none : bool, default=True
        Whether to ignore None objects passed in arrays.

    remove_types : tuple or list, default=(str,)
        Types to ignore in the arrays.

    xp : module, default=None
        Precomputed array namespace module. When passed, typically from a caller
        that has already performed inspection of its own inputs, skips array
        namespace inspection.

    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*   NFTr7   r   r   set_array_api_strict_flagsz2023.12)api_version)	r   _NUMPY_API_WRAPPER_INSTANCEr;   r/   r"   r   rH   r4   r   )r8   r9   rJ   r   r*   r"   	namespaceis_array_api_compliants           r   r   r     s    n $&:; 6>u9.55	~4x	!  F  2*E110111 (F(8(F(OQU%I///G/5 5/ 	,,,CCC,,,r   c                     t          || |d}t          dg           }t          |i |\  }}t          |i |}|r|||fS |d|fS )a
  Combination into one single function of `get_namespace` and `device`.

    Parameters
    ----------
    *array_list : array objects
        Array objects.
    remove_none : bool, default=True
        Whether to ignore None objects passed in arrays.
    remove_types : tuple or list, default=(str,)
        Types to ignore in the arrays.

    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.
    device : device
        `device` object (see the "Device Support" section of the array API spec).
    r7   F)r;   dictr   r   )r8   r9   r>   skip_remove_kwargsrJ   r   arrays_devices          r   get_namespace_and_devicer   M  s    . $	!  J %bAAA$jG4FGGBJ=*<==M (<..5-''r   c                     t          | |          \  }}t          |          r9|                    t          j        t          j        |                               S dd|                    |            z   z  S )NrI   g      ?)r   rK   rO   specialexpitr	   exp)XrJ   _s      r   _expitr   t  sj    !###EB2 ;zz'-a(8(899:::#r

"##r   Fc                    | j         dk    r$t          dt          | j                             |                    || j        t          |                     }d}| j        d         dz   }|s| j        d         | j        d         z  }|                    | d          }|r|d||xx         |z  cc<   dS ||d||<   dS )a  Implementation to facilitate adding or assigning specified values to the
    diagonal of a 2-d array.

    If ``add_value`` is `True` then the values will be added to the diagonal
    elements otherwise the values will be assigned to the diagonal elements.
    By default, ``add_value`` is set to `True. This is currently only
    supported for 2-d arrays.

    The implementation is taken from the `numpy.fill_diagonal` function:
    https://github.com/numpy/numpy/blob/v2.0.0/numpy/lib/_index_tricks_impl.py#L799-L929
    r   z*array should be 2-d. Got array with shape r   r   Nr   )rQ   r<   rb   rD   rO   r   r   r   )r5   valuerJ   	add_valuewrapendstep
array_flats           r   _fill_or_add_to_diagonalr   |  s     zQMu{9K9KMM
 
 	
 JJuEKuJFFE
C ;q>AD .k!nu{1~-E5))J &9C9& %
9C9r   c                 x    | j         }|dv r)t          |                              d          r| j        S | j        S )zJReturn the float dtype with the highest precision supported by the device.   array_api_compat.torchr   r   )rH   r=   
startswithr   r   )rJ   r   xp_names      r   _max_precision_float_dtyper     sE     kG555Fu%% 6 z:r   c                      d |D             } fd|D             }|r
  j         | S                      d          j        S )a  Find a suitable floating point dtype when computing with arrays.

    If any of the arrays are floating point, return the dtype with the highest
    precision by following official type promotion rules:

    https://data-apis.org/array-api/latest/API_specification/type_promotion.html

    If there are no floating point input arrays (all integral inputs for
    instance), return the default floating point dtype for the namespace.
    c                 2    g | ]}t          |d           |S r   )r4   )r_   rT   s     r   r   z1_find_matching_floating_dtype.<locals>.<listcomp>  s'    >>>1'!W*=*=>Q>>>r   c                 T    g | ]$}                     |j        d           |j        %S )rm   )re   r   )r_   rT   rJ   s     r   r   z1_find_matching_floating_dtype.<locals>.<listcomp>  s@       "**QWo*N*N	  r           )result_typerO   r   )rJ   r   dtyped_arraysfloating_dtypess   `   r   _find_matching_floating_dtyper    sn     ?>>>>M   &  O  0r~//
 ::c??  r   c           	      `   t          | |          \  }}}t          |          rX|r*|                    t          j        | ||                    S |*|(|                    t          j        | |                    S |                    | |          } ||                    ||          }|| j        |j        k    r|:t          dt          | j                   dt          |j                   d          t          |j                  | j        |         fk    r=t          dt          |j                   dt          | j                   d	|d
          dg| j
        z  }| j        |         ||<   |                    ||          }|                    | j        d          rt          d          |*|                    |j        d          rt          d          t          | ||          }|                    | |          } | |r|j        n|j        | |          S |                    ||          }|                    |                    | |          |          }	|s|	S |                    ||          }
|                    |
dk              rt+          d          |	|
z  S )a  Partial port of np.average to support the Array API.

    It does a best effort at mimicking the return dtype rule described at
    https://numpy.org/doc/stable/reference/generated/numpy.average.html but
    only for the common cases needed in scikit-learn.
    )r   weightsNr   z+Axis must be specified when the shape of a z and weights z differ.zShape of weights weights.shape=z! must be consistent with a.shape=z
 and axis=.r   rn   z;Complex floating point values are not supported by average.rI   r   r   z(Weights sum to zero, can't be normalized)r   rK   rO   r	   averagedotrD   r   rb   r<   rQ   r   re   r   NotImplementedErrorr  r   meansummultiplyrc   ZeroDivisionError)rT   r   r  	normalizerJ   r   r?   rD   output_dtypesum_scales              r   _averager    s    .a99NB72 5 	5::emAD'JJJKKK\g1::ei733444


1W
%%A**WW*55qw'-77<:eAGnn : : //: : :  
 AGDM#333I%2F2F I I+0>>I I@DI I I   afgdmd**We,,	zz!'-.. 
!I
 
 	
 rzz'-9KLL!I
 
 	
 1GCCCL
		!\""A090"&!$????ii..G66"++a))655D FF7F&&E	vvesl L JKKK%<r   c                 &   t          | |          \  }}t          |          r)|                    t          j        | |                    S |                    |           }|                    |                    ||                    |j        
 t          |                     |           |          } |
                    ||          }|                    |          r/|                    ||                    |j                  |           } | S NrI   r   r   )r   rK   rO   r	   nanminisnanminwhereinfr   allrc   nanr   r   rJ   r   masks        r   _nanminr         !###EB2 
zz%,qt444555 xx{{FF288D"**bfWVAYY*"G"GKKRVFWWvvdv&&66$<< 	6rzz"&11155Ar   c                 &   t          | |          \  }}t          |          r)|                    t          j        | |                    S |                    |           }|                    |                    ||                    |j         t          |                     |           |          } |
                    ||          }|                    |          r/|                    ||                    |j                  |           } | S r  )r   rK   rO   r	   nanmaxr  maxr  r  r   r  rc   r  r  s        r   _nanmaxr#    r  r   c                    t          | |          \  }}t          |          r)|                    t          j        | |                    S |                    |           }|                    |                    ||                    dt          |                     |           |          }|                    |	                    |
                    |          | j                  |          }||z  S )NrI   r   r   r   )r   rK   rO   r	   nanmeanr  r  r  r   r   logical_notr   )r   r   rJ   r   r  totalcounts          r   _nanmeanr)  %  s     !###EB2 zz%-555666xx{{rxxbjjVAYYj&G&GKKRVWWryy!5!5qw??dKKu}r   )rJ   r   c                
   t          | |          \  }}t          |          rH|du rt          j        | ||          } nt          j        | ||          } |                    |           S |                    | |||          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.
    rI   T)orderr   )r   r   r   )r   rK   r	   r5   rO   )r5   r   r+  r   rJ   r   r   s          r   _asarray_with_orderr,  2  s     %B'''EB2 H4<<KU%@@@EEM%uEBBBE zz%   zz%u4zGGGr   c                     t          | |          \  }}t          |          r=t          j        |           } |                    t          j        | d                    S |                    | d          S )zArray API compliant version of np.ravel.

    For non numpy namespaces, it just returns a flattened array, that might
    be or not be a copy.
    rI   C)r+  r   )rD   )r   rK   r	   rO   ravelr   )r5   rJ   r   s      r   _ravelr0  P  sp     %B'''EB2 9e$$zz%+e3777888::e5:)))r   c                     |j         }|dv r&|                                                                 S |dv r|                                 S t          j        |           S )z*Convert X into a NumPy ndarray on the CPU.r   >   array_api_compat.cupyr   )rH   r   r	   r(   rO   )r5   rJ   r   s      r   _convert_to_numpyr3  ^  sY    kG555yy{{  """	5	5	5yy{{=r   c                    ddl m}  ||           }t          |                                           D ]K\  }}t	          |d          st          |t          j                  r ||          }t          |||           L|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   )clone
__dlpack__)	sklearn.baser5  varsitemsr4   r1   r	   r2   setattr)	estimator	converterr5  new_estimatorkey	attributes         r    _estimator_with_converted_arraysr@  j  s    & #"""""E)$$My////11 / /Y9l++ 	-z)U]/S/S 	-!	),,IsI....r   c                 V    | t           j        } t          j        |           j        dz  S )z6Return the absolute tolerance for a given numpy dtype.Nd   )r	   r   finfoeps)dtype_or_dtype_names    r   _atol_for_typerF    s+    " $m;*++/#55r   c                 6    |                      d          j        S )aM  Return a platform-specific integer dtype suitable for indexing.

    On 32-bit platforms, this will typically return int32 and int64 otherwise.

    Note: using dtype is recommended for indexing transient array
    datastructures. For long-lived arrays, such as the fitted attributes of
    estimators, it is instead recommended to use platform-independent int32 if
    we do not expect to index more 2B elements. Using fixed dtypes simplifies
    the handling of serialized models, e.g. to deploy a model fit on a 64-bit
    platform to a target 32-bit platform such as WASM/pyodide.
    r   )rO   r   rI   s    r   indexing_dtyperH    s    * ::a==r   left)sidesorterrJ   c                :   t          | ||          \  }}t          |d          r|                    | |||          S t          | |          }t          ||          }t	          j        ||||          }|                    |t          |                     S )NrI   searchsorted)rJ  rK  r   )r   r4   rM  r3  r	   rO   r   )	rT   vrJ  rK  rJ   r   a_npv_npindicess	            r   _searchsortedrR    s    
 !Q2&&&EBr>"" ?q!$v>>>Q2&&&DQ2&&&D t$vFFFG::gfQii:000r   c                 .   t          |          r*|                    t          j        | ||                    S |r|                    | d          } n*|                    |           } |                    |          }| t          | ||dd                   S )ziFind the set difference of two arrays.

    Return the unique values in `ar1` that are not in `ar2`.
    )ar1ar2assume_uniquer   TrT  rU  rJ   rV  invert)rK   rO   r	   	setdiff1dr   rR   _in1d)rT  rU  rJ   rV  s       r   
_setdiff1dr[    s    
 2 
zzO+  
 
 	
  $jje$$s##s##u#"DNNNOOr   c           	      ,   t          |          r+|                    t          j        | |||                    S | j        }|                    | d          } |                    |d          }|                    t          | ||||          |          S )zCalculates ``element in test_elements``, broadcasting over `element`
    only.

    Returns a boolean array of the same shape as `element` that is True
    where an element of `element` is in `test_elements` and False otherwise.
    )elementtest_elementsrV  rX  r   rW  )rK   rO   r	   isinrD   r   rZ  )r]  r^  rJ   rV  rX  original_element_shapes         r   _isinra    s     2 
zzJ++	  
 
 	
 %]jj%((GJJ}e44M::'	
 	
 	
 		 	 	r   c                    t          | ||          \  }}|j        d         d| j        d         dz  z  k     r|rD|                    | j        d         |j        t	          |                     }|D ]}|| |k    z  }nC|                    | j        d         |j        t	          |                     }|D ]}|| |k    z  }|S |s-|                    |           \  } }|                    |          }|                    | |f          }	t	          |	          }
|	                    |	d          }|	                    |d          }|
                    |	|d          }|r|d	d
         |d
d         k    }n|d	d
         |d
d         k    }|                    ||                    |g|
          f          }|
                    ||d          }|r|d
| j        d                  S |
                    ||d          S )a  Checks whether each element of an array is also present in a
    second array.

    Returns a boolean array the same length as `ar1` that is True
    where an element of `ar1` is in `ar2` and False otherwise.

    This function has been adapted using the original implementation
    present in numpy:
    https://github.com/numpy/numpy/blob/v1.26.0/numpy/lib/arraysetops.py#L524-L758
    rI   r   
   g(\?r   T)stabler   r   Nr   r   )r   rD   r   rg   r   r   r   rR   rS   argsorttakerO   )rT  rU  rJ   rV  rX  r   r  rT   rev_idxarr?   r+  reverse_ordersarbool_arflagrets                    r   rZ  rZ    s     #sr***EB y|b39Q<50000 	!7739Q<rwvc{{7KKD ! !q ! 88CIaLs8LLD ! !q  $((--Ws##	C:		BRjjGJJr$J''EJJuTJ22M
''"e!'
$
$C &abb'S"X%abb'S"X%99grzz6(7zCCDEED
''$A'
.
.C ->SYq\>""wwsG!w,,,r   c                 0   ddl m} t          | ||          \  }}t          |          r"t	          j        |           r || ||          S | j        dk    sJ |                    | |          }|X|                    ||          }|	                    ||j
        d         df          }|                    ||j                  |z  }|                    d||j        	          }|                    |                    | dk    ||          |
          S )zA variant of `sklearn.utils.sparsefuncs.count_nonzero` for the Array API.

    If the array `X` is sparse, and we are using the numpy namespace then we
    simply call the original function. This function only supports 2D arrays.
    r   )count_nonzerorI   )r   sample_weightr   r   Nr   )r   r   r   )sparsefuncsro  r   rK   r   r   rQ   r   rO   r   rD   r   r   r  r  )	r   r   rp  rJ   r   ro  r   r  zero_scalars	            r   _count_nonzerors     s#    +*****!]r222EB2 H2;q>> H}QTGGGG6Q;;;;ll1Vl,,G 

=
@@

==3Fq3I12MNN))G]%899MI**QvW]*CCK66"((167K88t6DDDr   )outc                J    t          |           r ||d|i| n ||i |}|S )Nrt  )rK   )rJ   r   rt  r   r   s        r   _modify_in_place_if_numpyrv  8  sH    2 $d&&v&&&&dD#F##Jr   c                 >   t          | |          \  }}t          |d          r|                    | ||          S t          | |          }|t          ||          }nd }t	          j        |||          }|                    |t          |                     S )NrI   bincount)r  	minlengthr   )r   r4   rx  r3  r	   rO   r   )r5   r  ry  rJ   r   array_np
weights_npbin_outs           r   	_bincountr}  @  s     %B'''EBr: H{{5'Y{GGG 2...H&w2666


nXzYOOOG::gfUmm:444r   c                     t          | |          \  }}t          |          r|                                 S t          | |          }d |D             S )NrI   c                 6    g | ]}|                                 S r   )item)r_   r]  s     r   r   z_tolist.<locals>.<listcomp>U  s     333wGLLNN333r   )r   rK   tolistr3  )r5   rJ   r   rz  s       r   _tolistr  P  s\    %B'''EB2 ||~~ 2...H33(3333r   )Tr   )TF)NNTN)NN)NNN)F)FF)NNNN)<r   r   rB   r&   	functoolsr   r	   r%   scipy.sparsesparser   scipy.specialr   _configr   fixesr   r   r   r   r/   r6   r=   r   rF   rK   rX   re   r]   r{   r   r   r   r   r   r;   r   r   r   r   r   r  r  r  r#  r)  r,  r0  r3  r@  rF  rH  rR  r[  ra  rZ  rs  rv  r}  r  r   r   r   <module>r     s0   ! !
      				                                            !#;<    >!. !. !. !.H' ' 'T  " %)v * * * * *Z   1 1 1
S S S	3 	3 	3  D( ( (  :F F F
  |# |# |# |# |# |# |# |#~ /.00  -1v # # # # #L (,3&T Y- Y- Y- Y- Y-x 7;# $( $( $( $( $(N$ $ $ $& & & &@	 	 	! ! !2? ? ? ?D   "   "
 
 
 
 )-H48H H H H H<* * * *	  	  	   :6 6 6  0 !'t 1 1 1 1 1P P P P,   D-- -- -- --`E E E E0 48     5 5 5 5 4 4 4 4 4 4r   