
    Q3jN                     V   d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	Z	ddl
Z
ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z dd	lmZ dd
lmZ dgZddhZeee fZ! edddg      Z"dEdZ#dEdZ$d Z%d Z&d Z'de!ddZ(d Z)d Z*dFdZ+de!ddZ,d Z-de!dddZ.de!ddd Z/d! Z0dGd"Z1dGd#Z2d$ Z3d% Z4d& Z5d' Z6d( Z7d) Z8dHd*Z9dId+Z:dFd,Z;dGd-Z<dGd.Z=dGd/Z>dJd0Z?	 dKddd1d2Z@dFd3ZAd4 ZBd5 ZCd6 ZDd7 ZEd8 ZFd9 ZGdLd:ZHdLd;ZIdMd<ZJdd=d>ZKdNd?ZLdGd@ZMdA ZNdB ZOdGdCZPdFdDZQy)OzTools to support array_api.    N)
namedtuple)partial)
get_config)array_api_compat)array_api_extra)numpy)is_df_or_series)parse_versionxpxr   z(sklearn.externals.array_api_compat.numpyNamespaceAndDevicexpdeviceTc              #   8   K   dD ]  }| s	|t         v r|  yw)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torchdpnpN)_NUMPY_NAMESPACE_NAMES)include_numpy_namespacesarray_namespaces     E/DATA/.local/lib/python3.12/site-packages/sklearn/utils/_array_api.pyyield_namespacesr   &   s(      (O?U,Us   c              #     K   t        |       D ]z  }|dk(  r-t        j                  dd      D ]  \  }}|||f  |ddf 5|dk(  r&t        j                  dd      D ]  \  }}|||f  `|d	k(  r|d
df |ddf t|ddf | yw)a  Yield supported namespace, device_name, dtype_name tuples for testing.

    Use this to test that an estimator works with all combinations.
    Pass the yielded values to `_array_api_for_tests` which returns (xp, device)
    for array allocation.

    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_name : str or None
        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xpufloat64float32mpsr   r   )r   gpur   
CPU_DEVICEr   device1N)r   	itertoolsproduct)r   r   device_namedtypes       r   )yield_namespace_device_dtype_combinationsr(   F   s     2 ,!9 g%&/&7&7&(>'"U &{E99' "5)33&&/&7&7 6'"U &{E99'
  22 "<::!9i77!4--/s   BBc               #     K   t        dd      t        dd      df t        dd      t        dd      df t        dd      t        dd      d	f t        dd      t        dd      d
f t        dd      t        dd      df yw)al  Yield mixed namespace and device inputs for testing.

    We do not test for all possible permutations of namespace/device from
    `yield_namespace_device_dtype_combinations` (excluding dtype variations, this is
    P(8,2)=56), to avoid slow testing and maintenance burden.

    The included selection ensures that the following conversions are tested:

    * non-NumPy to NumPy (including GPU to CPU)
    * NumPy to non-NumPy (including CPU to GPU)
    * non-NumPy to non-NumPy (GPU to GPU)
    * array-api-strict to non-NumPy (this pair also has no special hardware
      requirements to allow for local testing)
    r   Nr   r   zcupy to torch cudar    r   ztorch mps to numpyznumpy to torch cudaznumpy to torch mpsr   r#   r   zarray_api_strict to torch cpu)r        r   (yield_mixed_namespace_input_permutationsr,   y   s       	64(7F+  	7E*7D)  	7D)7F+  	7D)7E*  	-y97E*' s   B	Bc                     | syt        t        j                        }d}|t        |      k  rt        d| d      t        j
                  j                  d      dk7  rt        d      y)zChecks that array API support is functional.

    In particular scipy needs to be recent enough and the environment variable
    needs to be set: SCIPY_ARRAY_API=1.
    Nz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)r
   scipy__version__ImportErrorosenvirongetRuntimeError)array_api_dispatchscipy_versionmin_scipy_versions      r   _check_array_api_dispatchr:      s~     !%"3"34M }%677./ 0+ +
 	
 
zz~~'(C/J
 	
 0r+   c                 N    t        | d      rt               d   sy| j                  S )z0Hardware device where the array data resides on.r   r7   N)hasattrr   r   )arrays    r   _single_array_devicer>      s(     E8$ |01||r+   remove_noneremove_typesc                     t        || |d}|syt        |d         }|dd D ]#  }t        |      }||k7  st        d| d|        |S )aP  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, list, tuple)
        Types to ignore in array_list.

    Returns
    -------
    out : device
        `device` object (see the "Device Support" section of the array API spec).
    r?   Nr      z$Input arrays use different devices: z, )_remove_non_arraysr>   
ValueError)r@   rA   
array_listdevice_r=   device_others         r   r   r      ss    * $	<J ":a=1G AB+E2l"6wir,P    Nr+   c                 @    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   sizerN      s     99QWWr+   c                 &    | j                   t        v S )z%Return True if xp is backed by NumPy.)__name__r   r   s    r   _is_numpy_namespacerR     s    ;;000r+   c                     | j                         j                  d|      }g }dD ]  }||v s|j                  ||           t        | d      r|j                  | j                         t        |      S )a  Supported floating point types for the namespace.

    Parameters
    ----------
    xp : module
        Array namespace to inspect.

    device : str or device instance from xp, default=None
        Device to use for dtype selection. If ``None``, then a default device
        is assumed.

    Returns
    -------
    supported_dtypes : tuple
        Tuple of real floating data types supported by the provided array namespace,
        ordered from the highest precision to lowest.

    See Also
    --------
    max_precision_float_dtype : Maximum float dtype for a namespace/device pair.

    Notes
    -----
    `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.

    Additionally, some devices available within a namespace may not support
    all floating-point types that the namespace provides.

    https://data-apis.org/array-api/latest/API_specification/data_types.html
    real floatingkindr   r   float16)__array_namespace_info__dtypesappendr<   rW   tuple)r   r   dtypes_dictvalid_float_dtypes	dtype_keys        r   supported_float_dtypesr_     s    B --/66V 7 K +	#%%k)&<= , r9!!"**-#$$r+   c                     g }t        |      }|D ]G  }| r|t        ||      rt        j                  |      r+t	        |      r7|j                  |       I |S )a  Filter arrays to exclude None and/or specific types.

    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, list, tuple)
        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.
    )r[   
isinstancespissparser	   rZ   )r@   rA   arraysfiltered_arraysr=   s        r   rD   rD   ?  sd    , O&L5=e\*;;u5!u%  r+   c                      g }| D ]T  }t        |      }|j                  dk(  r'|j                  dk(  rt        |d      r|j                  }|j                  |       V |S )N
_cyutility_memoryviewslicebase)type
__module__rP   r<   ri   rZ   )rd   	unwrappedaa_types       r   _unwrap_memoryviewslicesro   e  s`    
 Ia-#556"A  r+   )r@   rA   r   c                 $   t               d   }|s||dfS t        dfS ||dfS t        || |d}t        | }|st        dfS t	        |       t        j                  | }d}|j                  dk(  rt        |d      r|j                  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, `array_api_compat.numpy` 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 `array_api_compat.numpy` 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, list, tuple)
        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 the NumPy namespace.

    is_array_api_compliant : bool
        True if the arrays are containers that implement the array API spec (see
        https://data-apis.org/array-api/latest/index.html).
        Always False when array_api_dispatch=False.
    r7   FTr?   r   set_array_api_strict_flagsz2024.12)api_version)
r   	np_compatrD   ro   r:   r   get_namespacerP   r<   rq   )r@   rA   r   rd   r7   	namespaceis_array_api_compliants          r   rt   rt   w  s    r $&:;>u9e##	~4x	!F &v.F%01 ..7I!//G/5 	,,,C,,,r+   c                     t        dg       }t        || |d}t        |i |}|t        |i |\  }}n|d}}|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, list, tuple)
        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.
    device : device
        `device` object (see the "Device Support" section of the array API spec).
    Fr?   T)dictrD   r   rt   )r@   rA   r   rF   skip_remove_kwargsarrays_deviceis_array_apis          r   get_namespace_and_devicer|     sv    : %bA#	!J
 J=*<=M	z(*K8JKLtL<..5-''r+   c                 T   t        |t              r
|dk(  r|dz  }|D cg c]  }t        j                  |       }}|D cg c]  }|du  }}t	        |      rt        |       st        d      |}t        | |      | j                  k(  rng }|D ]g  }t        |      \  }}t        |dd      |j                  k(  r,|j                  |j                  ||j                               W|j                  |       i g }	t        |||      D ]~  \  }}
}|r|	j                  d       |
r|	j                  |       /t        |      \  }}}| |k(  r||k(  r|	j                  |       Z	 | j!                  ||      }|	j                  |        t/        |	      dk(  r|	d   S t1        |	      S c c}w c c}w # t"        t        t$        t&        t(        f$ rY t        |       rt+        ||      }n>t        |      r| j-                  ||      }nt+        ||      }| j-                  ||      }Y w xY w)	aK  Move all arrays to `xp` and `device`.

    Each array will be moved to the reference namespace and device if
    it is not already using it. Otherwise the array is left unchanged.

    `arrays` may contain `None` entries, these are left unchanged.

    Sparse arrays are accepted (as pass through) if the reference namespace is
    NumPy, in which case they are returned unchanged. Otherwise a `TypeError`
    is raised.

    Parameters
    ----------
    *arrays : iterable of arrays
        Arrays to (potentially) move.

    xp : namespace
        Array API namespace to move arrays to.

    device : device
        Array API device to move arrays to.

    Returns
    -------
    arrays : tuple or array
        Tuple of arrays with the same namespace and device as reference. Single array
        returned if only one `arrays` input.
    r   z:0NzWSparse arrays are only accepted (and passed through) when the target namespace is Numpyr'   r   rC   r   )ra   strrb   rc   anyrR   	TypeError_max_precision_float_dtyper   rt   getattrr   rZ   astypezipr|   from_dlpackAttributeErrorNotImplementedErrorBufferErrorrE   _convert_to_numpyasarraylenr[   )r   r   rd   r=   sparse_mask	none_maskarrays_xp_array_converted_arrays	is_sparseis_nonedevice_arrayarray_convertedarray_nps                  r   move_tor     s6   : &#6U? 	$39:6%2;;u%6K:,23F5$FI3
; 3B 7!
 	

 G!"f-;E'.KHaugt,0@0@@xuh6F6FGHu%  %(+y%I!y'##D)##E*(@(G%HaX~&L"8 ''.'N ')nnU6n&JOB !''8e &Jj  ##349?DEU?VQ ;3d #' N +2.*;E8*L,X6*,**U6**J $5UH#E*,**Xf**M'Ns   F&F+"F00A4H'&H'c                     t        | |      \  }}t        |      rt        j                  | |      S dd|j	                  |        z   z  S )NrQ   outg      ?)rt   rR   specialexpitexp)rM   r   r   r   s       r   _expitr   w  sG     !#EB2}}QC((#r
"##r+   c                     t        |       \  }t              rt        j                  | |      S fd}j	                  j                  | dk  | dkD        j                  | d| z
  z         ||             S )NrQ   r   c                 \    d| dz
  z  }j                  |      j                  |       z
  S )N         ?)log1p)rM   sr   s     r   logit_v2z_logit.<locals>.logit_v2  s-    SMxx{RXXqb\))r+   g333333?g?rC   )rt   rR   r   logitwhere
logical_orlog)rM   r   r   r   r   s     `  r   _logitr     sw     !#EB2}}QC((* 88
a#gq4x(
qAE{ r+   c                    | j                   dk7  r!t        dt        | j                               |j	                  || j
                  t        |             }|j                   dvrt        d|j                    d      t        | j                        }|j                   dk(  r0|j                  d   |k7  rt        d	| d
|j                  d          ||fS )z:Validate arguments to `_fill_diagonal`/`_add_to_diagonal`.r   z+`array` should be 2D. Got array with shape r'   r   )r   rC   z2`value` needs to be a scalar or a 1D array, got a zD array instead.rC   r   zX`value` needs to be a scalar or 1D array of the same length as the diagonal of `array` (z). Got )ndimrE   r[   rL   r   r'   r   min)r=   valuer   min_rows_columnss       r   _validate_diagonal_argsr     s    zzQ9%:L9MN
 	
 JJuEKKuJFEzzZZL 02
 	
 5;;'zzQ5;;q>-==$$4#5WU[[^<LN
 	

 """r+   c                     t        | ||      \  }}t        |      r|j                  | |d       y|j                  dk(  rt	        |      D ]	  }|| ||f<    yt	        |      D ]  }||   | ||f<    y)a  Minimal implementation of `numpy.fill_diagonal`.

    `wrap` is not supported (i.e. always False). `value` should be a scalar or
    1D of greater or equal length as the diagonal (i.e., `value` is never repeated
    when shorter).

    Note `array` is altered in place.
    F)wrapr   N)r   rR   fill_diagonalr   range)r=   r   r   r   is        r   _fill_diagonalr     s     6eUBGE2
E2 ::?+,#ad - +,#Ahad -r+   c                 B   t        | ||      \  }}t        |      rL| j                  d   dz   }| j                  d   | j                  d   z  }| j                  d||xx   |z  cc<   y|j                  j                  |       |z   }t        |      D ]  }||   | ||f<    y)zAdd `value` to diagonal of `array`.

    Related to `fill_diagonal`. `value` should be a scalar or
    1D of greater or equal length as the diagonal (i.e., `value` is never repeated
    when shorter).

    Note `array` is altered in place.
    rC   N)r   rR   rL   flatlinalgdiagonalr   )r=   r   r   r   stependr   s          r   _add_to_diagonalr     s     6eUBGE2{{1~!kk!nu{{1~-

9C9& IIu%-E#$Ahad %r+   c                 0    | j                   |d| d| fv S )Nzarray_api_compat.z#sklearn.externals.array_api_compat.)rP   )r   names     r   _is_xp_namespacer     s/    ;;
D6"
-dV4  r+   c                     t        |       r| j                  S | j                         j                  d|      }d|v r| j                  S | j                  S )zReturn the float dtype with the highest precision supported by the device.

    Note that scikit-learn only considers float32 and float64 as suitable
    floating point dtypes.
    rT   rU   r   )rR   r   rX   rY   r   )r   r   floating_dtypess      r   r   r     sY     2 zz113::V ; O O#zz::r+   c                 0   |D cg c]   }t        |d      s| j                  |      " }}|D cg c]+  }| j                  |j                  d      s |j                  - }}|r | j                  | S | j                  d      j                  S c c}w c c}w )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.
    r'   rT           )r<   r   isdtyper'   result_type)r   rd   rm   dtyped_arraysr   s        r   _find_matching_floating_dtyper     s     -3JFqga6IRZZ]FMJ&&A"**QWWo*N   r~~//
 ::c?    Ks   BB!BBc           	         t        | ||      \  }}}t        |      rR|r'|j                  t        j                  | ||            S |'|%|j                  t        j
                  | |            S |j                  | |      } ||j                  ||      }|| j                  |j                  k7  r|8t        dt        | j                         dt        |j                         d      t        |j                        | j                  |   fk7  r;t        dt        |j                         dt        | j                         d	|d
      dg| j                  z  }| j                  |   ||<   |j                  |t        |            }|j                  | j                  d      rt        d      |'|j                  |j                  d      rt        d      t        | ||      }|j!                  | |      } |" |r|j"                  n|j$                  | |      S |j!                  ||      }|j%                  |j'                  | |      |      }	|s|	S |j%                  ||      }
|j)                  |
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.
    rQ   )axisweightsr~   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=.rC   zcomplex floatingz;Complex floating point values are not supported by average.r   r   z(Weights sum to zero, can't be normalized)r|   rR   r   r   averagedotrL   r   r[   rE   r   reshaper   r'   r   r   r   meansummultiplyr   ZeroDivisionError)rm   r   r   	normalizer   r   rG   rL   output_dtypesum_scales              r   _averager     sn    .aR@NB72::emmAD'JKK\g1::eii7344


1W
%A**WW*5qww'--7<=eAGGn=M N /0: 
 AGGDM#331%2F1G H++0>*:+waI  affggdmd**WeEl3	zz!''-.!I
 	
 rzz'--9KL!I
 	
 1GCL
		!\"A09"&&!$??ii.G66"++a)65DFF7F&E	vvesl JKK%<r+   c                 .   t        | |      \  }}}t        j                  |      r|j                  | d||      S t	        |d      r|j                  | ||      S t        | t        d      }|j                  t        j
                  |||      |      S )	NrQ   r   )qdimkeepdimmedianr   keepdimsr   r   r   r~   )	r|   r   is_torch_namespacequantiler<   r   r   r   r   )rM   r   r   r   r   r   x_nps          r   _medianr   W  s     -Q26MB6 **2.{{1x{@@r8yyy99 1u-D::ell4dXFv:VVr+   c                 
   t        | ||      \  }}}t        j                  dd      5  | |j                  |      z  }d d d        |j	                  | dk(  |j                  dj                  |      |      S # 1 sw Y   ;xY w)NrQ   ignore)divideinvalidr   r   )r|   r   errstater   r   r   r'   )rM   yr   r   rG   temps         r   _xlogyr   n  sn    -ar:NB7	x	:266!9} 
;88AHbjjDJJwjOQUVV 
;	:s   A99Bc           
         t        | |      \  }}}t        |      r&|j                  t        j                  | |            S |j                  |       }|j                  |j                  ||j                  |j                  | j                  |      |       |      } |j                  ||      }|j                  |      r9|j                  ||j                  |j                  | j                  |      |       } | S NrQ   r   r   )r|   rR   r   r   nanminisnanr   r   infr'   allr   nanXr   r   r   rG   masks         r   _nanminr   w       .aB7NB72zz%,,qt455 xx{FFHHT2::rvvgQWWW:MqQ  

 vvdv&66$<rzz"&&zPRSTAr+   c           
         t        | |      \  }}}t        |      r&|j                  t        j                  | |            S |j                  |       }|j                  |j                  ||j                  |j                   | j                  |      |       |      } |j                  ||      }|j                  |      r9|j                  ||j                  |j                  | j                  |      |       } | S r   )r|   rR   r   r   nanmaxr   maxr   r   r'   r   r   r   r   s         r   _nanmaxr     r   r+   c           
         t        | |      \  }}}t        |      r&|j                  t        j                  | |            S |j                  |       }|j                  |j                  ||j                  d| j                  |      |       |      }|j                  |j                  |j                  |      | j                        |      }||z  S )NrQ   r   r   r   )r|   rR   r   r   nanmeanr   r   r   r'   r   logical_not)r   r   r   r   rG   r   totalcounts           r   _nanmeanr    s     .aB7NB72zz%--566xx{HHT2::c:I1MTX  
 ryy!5qww?dKu}r+   c                 4   t        | |      \  }}}t        |      r(|j                  t        j                  | |||            S |j                  |       }|j                  ||j                  d|| j                        |       }|j                  ||||      S )NrQ   r   r   r'   r   r   r'   )	r|   rR   r   r   nansumr   r   r'   r   )	r   r   r   r   r'   r   X_devicer   
masked_arrs	            r   _nansumr    s     /qR8OB82zz%,,qtheTUU88A;D$

1XQWW
 MqQJ66*4(%6HHr+   r   c                    t        | |      \  }}t        |      rF|du rt        j                  | ||      } nt        j                  | ||      } |j	                  |       S |j	                  | |||      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.
    rQ   T)orderr'   )r'   copyr   )rt   rR   r   r=   r   )r=   r'   r  r  r   r   r   s          r   _asarray_with_orderr    so     %B'EB24<KKU%@EMM%uEBE zz%  zz%u4zGGr+   c                     t        | |      \  }}t        |      r;t        j                  |       } |j                  t        j                  | d            S |j                  | 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.
    rQ   C)r  )rL   )rt   rR   r   r   ravelr   )r=   r   r   s      r   _ravelr    sW     %B'EB2e$zz%++e3788::e5:))r+   c                 r   t        |d      r| j                         j                         S t        |d      r| j                         S t        |d      r5t        j                  |j	                  | |j                  d                  S t        |d      r| j                         S t        j                  |       S )af  Convert X into a NumPy ndarray on the CPU.

    This function uses library-specific methods to convert the array to a NumPy
    ndarray on the CPU. It is only meant as a fallback when move_to fails to use the
    DLPACK protocol.

    This function is not meant to be called directly and
    `move_to(array, xp=np, device="cpu")` should be used instead.
    r   r   r   r"   r~   r   )r   r   r   r5   r   Deviceasnumpy)r=   r   s     r   r   r     s     G$yy{  ""	"f	%yy{	"0	1}}RZZbii6MZNOO	"f	%}}==r+   c           	         ddl m} t        |       }t        | d      r&t	        j
                  |       s| j                        S |t        u r.| j                         D ci c]  \  }}|t        |       c}}S |t        t        t        t        fv r |fd| D              S t        | d      s*t        | t        j                   t        j"                  f      r |       S t        | d      rt        | t              r| S  ||       }t%        |       j                         D ]  \  }}t        |      }t'        |||         |S c c}}w )a  Create a new estimator with converted array attributes.

    All attributes that are arrays will be converted using the provided converter.

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

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

    Returns
    -------
    new_estimator : Estimator
        A clone of the estimator with converted array attributes.
    r   )clone__sklearn_array_api_convert__c              3   6   K   | ]  }t        |        y wN) _estimator_with_converted_arrays).0v	converters     r   	<genexpr>z3_estimator_with_converted_arrays.<locals>.<genexpr>"  s      
DMq,Q	:Is   
__dlpack__
get_params)sklearn.baser  rj   r<   inspectisclassr  rx   itemsr  listr[   set	frozensetra   r   ndarraygenericvarssetattr)		estimatorr"  r  estimator_typekr!  new_estimatorkey	attributes	    `       r   r  r    sD   & # )_Ny9:7??D 66yAA ")
)1 /9==)
 	

 $sI66 
DM
 
 	
 y,':EMM5==1, ##9l+z)T/J)$My///1Y4Y	J	sI. 2 -
s    Ec                 :    t        | t        t        ||            S )a  Move estimator array attributes to the given namespace and device.

    Attributes which are not arrays are left unchanged.

    Parameters
    ----------
    estimator : estimator object
        The estimator whose attributes should be converted.

    xp : array namespace
        The target array API namespace.

    device : device or None
        The target device.

    Returns
    -------
    new_estimator : estimator object
        A clone of the estimator with array attributes moved.
    r   )r  r   r   )r1  r   r   s      r   move_estimator_tor8  5  s    * ,77r&9 r+   c          	         t               d   syt        ||      }t        |      \  }}}t        |       \  }}}	||k(  r|	|k(  ryt        |      rt        |      ry|	3t	        j
                  |       rdnd}
d|j                   d|
 d| d|
 d		}n2||k7  r!d
|j                   d| d|j                   d}nd| d| d|	 d}t        d|j                  j                   d| d| d      )aY  Check that estimator's fitted attribute is compatible with X.

    Use this to check that an estimator was fitted using the same array
    namespace and device as ``X``. This is done by comparing the namespace and
    device of ``X`` and the provided ``attribute``.

    Parameters
    ----------
    X : array-like
        The data passed to the fitted estimator's method, e.g. to ``predict``.

    estimator : estimator object
        The fitted estimator.

    attribute : str
        The name of the fitted attribute to check; for example it could be
        ``"coef_"`` for a linear model. This function will check that ``X`` is
        in a namespace and device that are consistent with the attribute.

    method : str
        The name of the calling method (e.g. ``"predict"``). It is used to
        write the error message if the check fails.
    r7   Nzsparse arrayz
array-likez!Array namespace used during fit (z) is not compatible with the z input passed to z.. Only the NumPy namespace is compatible with z inputs.z"Array namespaces used during fit (z) and z (z	) differ.zDevices used during fit (zInputs passed to r   zM() must use the same namespace and the same device as those passed to fit(). z You can move the estimator to the same namespace and device as X with: 'from sklearn.utils._array_api import get_namespace_and_device, move_estimator_to; xp, _, device = get_namespace_and_device(X); estimator = move_estimator_to(estimator, xp, device)')	r   r   r|   rR   rb   rc   rP   rE   	__class__)r   r1  r6  methodattra_xpr   a_deviceX_xpr
  	type_namemsgs               r   check_same_namespacerB  O  sA   0 <,-9i(D06D!X03D!Xt|H,4 %8%> 	&(kk!nN,	/ ?**34EfX N;;D+XO 	
 
0 @("T]]O96 	
 *(6&H:YW

I//8896( CU% @	@	 	r+   c                 j    | t         j                  } t        j                  |       j                  dz  S )z6Return the absolute tolerance for a given numpy dtype.i  )r   r   finfoeps)dtype_or_dtype_names    r   _atol_for_typerG    s/    " $mm;;*+//$66r+   c                 8    | j                  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   )r   r'   rQ   s    r   indexing_dtyperI    s    * ::a=r+   c           	         t        |      r(|j                  t        j                  | |||            S | j                  }|j                  | d      } |j                  |d      }|j                  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_elementsassume_uniqueinvertr  )ar1ar2r   rM  rN  )rR   r   r   isinrL   r   _in1d)rK  rL  r   rM  rN  original_element_shapes         r   _isinrT    s     2zzJJ++	
 	
 %]]jj%(GJJ}e4M::'	
 		 	r+   c                    t        | ||      \  }}|j                  d   d| j                  d   dz  z  k  r|rE|j                  | j                  d   |j                  t	        |             }|D ]
  }|| |k7  z  } |S |j                  | j                  d   |j                  t	        |             }|D ]
  }|| |k(  z  } |S |s%|j                  |       \  } }|j                  |      }|j                  | |f      }	t	        |	      }
|j                  |	d      }|j                  |d      }|j                  |	|d      }t        |      d	k\  r|r|d	d
 |d
d k7  n
|d	d
 |d
d k(  }n&|r|j                  dg      n|j                  dg      }|j                  ||j                  |g|
      f      }|j                  ||d      }|r|d
| j                  d    S |j                  |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
    rQ   r   
   g(\?r   T)stabler   rC   Nr  Fr~   )rt   rL   onesboolr   zerosunique_inverseunique_valuesconcatargsorttakerN   r   )rO  rP  r   rM  rN  r   r   rm   rev_idxarrG   r  reverse_ordersarbool_arflagrets                    r   rR  rR    s    #sr*EB yy|b399Q<500077399Q<rwwvc{7KDq    88CIIaLs8LDq  ((-Ws#	C:	BRjGJJr$J'EJJuTJ2M
''"e!'
$CCyA~)/#ab'S"X%SWCR5H *0"**eW%RZZ5G99grzz6(7zCDED
''$A'
.C>SYYq\""wwsG!w,,r+   c                    ddl m} t        | ||      \  }}t        |      r t	        j
                  |       r || ||      S | j                  dk(  sJ |j                  | |      }|S|j                  ||      }|j                  ||j                  d   df      }|j                  ||j                        |z  }|j                  d||j                        }|j                  |j                  | dk7  ||      |	      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_nonzerorQ   )r   sample_weightr   r~   rC   r  r   )sklearn.utils.sparsefuncsrh  rt   rR   rb   rc   r   	ones_liker   r   rL   r   r'   r   r   )	r   r   ri  r   r   rh  r   r   zero_scalars	            r   _count_nonzerorm  
  s     8!]r2EB22;;q>QTGG66Q;;ll1Vl,G 

=
@

==3F3Fq3I12MN))G]%8%89MI**QvW]]*CK66"((167K8t6DDr+   r   c                D    t        |       r ||d|i| |S  ||i |}|S )Nr   )rR   )r   funcr   argskwargss        r   _modify_in_place_if_numpyrr  "  s9    2d&&v& J D#F#Jr+   c                    t        | |      \  }}t        |d      r|j                  | ||      S t        | t        d      }|t        |t        d      }nd }t	        j                  |||      }|j                  |t        |             S )NrQ   bincount)r   	minlengthr   r   r~   )rt   r<   rt  r   r   r   r   )r=   r   ru  r   r   r   
weights_npbin_outs           r   	_bincountrx  *  s     %B'EBr:{{5'Y{GGuu5HWu=

nnXzYOG::gfUm:44r+   c                 <   t        | |      \  }}}|t        t        | j                              n|}t	        ||      }| j
                  |vr|j                  | |d   |      } |j                  | |d      }| |k(  }|j                  | d      } |j                   | |<   |j                  || j
                        }|j                  ||d| j
                        }	|j                  |j                  |      |d      }
|j                  | |
z
        }|j                  ||d|j
                        }|j                  |dk(  |||	z        }|j                  |      |j                  |	      z   |z   }|j!                  ||	      }|j                  dk(  r|d
   }|S |}|S )NrQ   r~   r   r   Tr   )r  r  r   r*   )r|   r[   r   r   r_   r'   r   r   r   r   r   r   isfiniter   r   r   squeeze)r=   r   r   r   r   supported_dtypes	array_max	index_maxi_max_dtmshiftr   r   r   s                 r   
_logsumexpr  :  s   
 -Ur:MB6'+|5uzz"#D-b@{{**

5(8(;F
Ku4$7I"IJJu4J(EwE)yyEKK0H
xdTEAHHR[[+Y:E
&&
C
sCII>A
aAE"A
((1+q	
!I
-C
**St*
$CXX]#b'CJ ),CJr+   c                     t        |      r!t        j                  j                  | d      S |j                  j                  |       S NT)lower)rR   r0   r   cholesky)
covariancer   s     r   	_choleskyr  Y  s9    2||$$Zt$<<yy!!*--r+   c                     t        |      r"t        j                  j                  | |d      S |j                  j	                  | |      S r  )rR   r0   r   solve_triangularsolve)cov_chol
eye_matrixr   s      r   _linalg_solver  `  s;    2||,,Xz,NNyyx44r+   c                 L   t        | ||      \  }}}t        |d|      }|j                  | |j                  |      } |j	                  | j
                  d   |      |j
                  d   z  }|j                  t        |      | |z         }t        t        ||z
  ||            S )zGA version of the multinomial loss that is compatible with the array APIrC   )r   r   r   r   r~   )r   r   )
r|   r  r   int64arangerL   r_  r  floatr   )	r   predri  r   r   rG   log_sum_expclass_marginslabel_predictionss	            r   _half_multinomial_lossr  g  s    -a}ENB7Tb1K


1BHHW
5AIIaggajI9DJJqMIMta-.?@00-BO r+   c                 L   t        | |      \  }}}t        |      r| j                  S |j                         j	                  |      }|j                         D ci c]  \  }}||
 }}}|| j                     }t        j                         j	                         |   S c c}}w )NrQ   r~   )r|   rR   r'   rX   rY   r)  rs   )	r   r   r   rG   r\   r   r'   reversed_dtypes_dict
dtype_names	            r   _matching_numpy_dtyper  s  s    -aB7NB72ww--/66g6FK;F;L;L;NO;NKD%E4K;NO%agg.J--/668DD Ps   B )Tr  )NN)NNTN)NFN)NNFN)NNN)FF)NNNN)Nr   N)R__doc__r'  r$   rJ   r3   collectionsr   	functoolsr   r   r0   scipy.sparsesparserb   scipy.specialr   sklearn._configr   sklearn.externalsr   r   r   "sklearn.externals.array_api_compatrs   sklearn.utils._dataframer	   sklearn.utils.fixesr
   __all__r   r   r*  r[   REMOVE_TYPES_DEFAULTr   r   r(   r,   r:   r>   r   rN   rR   r_   rD   ro   rt   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r   r  r8  rB  rG  rI  rT  rR  rm  rr  rx  r  r  r  r  r  r*   r+   r   <module>r     s   !
    	 "      & . 4 A 4 - '!#MN 	    4tX6FG @0.f(V
6  %)7K )X 1
,%^ -1?S #L& ,@T\-@ "0D.(bm`$&#.'46(!2?DW.W((
I )-H48H<* ,5p4CL70D.-bE0 48 5 >.5	Er+   