
    3;ji                        d Z ddl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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d>dZd>dZd Zd Zd ZdefddZd Z d Z!d Z"d?dZ#defddZ$defdddZ%defdddZ&d Z'd?dZ(d Z)d Z*d  Z+d! Z,d" Z-d# Z.d@d$Z/dAd&Z0d?d'Z1dBd(Z2dBd)Z3dBd*Z4dCd+Z5	 dDddd,d-Z6d?d.Z7d/ Z8d0 Z9d1 Z:d2 Z;dEd3Z<dEd4Z=dFd5Z>dd6d7Z?dDd8Z@d?d9ZAdBd:ZBd; ZCd< ZDdBd=ZEdS )GzTools to support array_api.    N)
get_config)array_api_compat)array_api_extra)numpy)is_df_or_series)parse_versionxpxr   z(sklearn.externals.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     R/root/voice-cloning/.venv/lib/python3.11/site-packages/sklearn/utils/_array_api.pyyield_namespacesr      sH      
   ( 	O?U,U,U     c              #   Z  K   t          |           D ]}|dk    r*t          j        dd          D ]\  }}|||fV  |ddfV  2|dk    rX	 dd	l}||                    d
          dfV  ||                    d          dfV  r# t
          $ r |d
dfV  |ddfV  Y w xY w|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.
    Use in conjunction with `ids=_get_namespace_device_dtype_ids` to give
    clearer pytest parametrization ID names.

    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xpufloat64float32mpsr   r   r   N
CPU_DEVICEr   device1)r   	itertoolsproductr   DeviceImportError)r   r   devicedtyper   s        r   )yield_namespace_device_dtype_combinationsr$   ;   sY     2 ,!9   . . g%%!*!2&(>" " 5 5 &vu44444!5)33333 222
<''''%'7'>'>|'L'LiWWWW%'7'>'>y'I'I9TTTTT < < < &|Y>>>>%y);;;;;;< "4-----/. .s   8BB B c                     	 ddl }| |                    d          k    rdS | |                    d          k    rdS | |                    d          k    rdS dS # t          $ r Y dS w xY w)zNGet pytest parametrization IDs for `yield_namespace_device_dtype_combinations`r   Nr   r   device2)r   r    r!   )paramr   s     r   _get_namespace_device_dtype_idsr(   n   s    
 $++L9999<$++I66669$++I66669 76    tts   A 
A'&A'c                     | sdS t          t          j                  }d}|t          |          k     rt          d| d          t          j                            d          dk    rt          d          dS )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__r!   osenvirongetRuntimeError)array_api_dispatchscipy_versionmin_scipy_versions      r   _check_array_api_dispatchr5      s      !%"344M }%67777+. + + +
 
 	
 
z~~'((C//J
 
 	
 0/r   c                 \    t          | d          rt                      d         sdS | j        S )z0Hardware device where the array data resides on.r"   r2   N)hasattrr   r"   )arrays    r   _single_array_devicer9      s9     E8$$ ||01 t|r   remove_noneremove_typesc                     t          || |d}|sdS t          |d                   }|dd         D ],}t          |          }||k    rt          d| d|           -|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).
    r:   Nr      z$Input arrays use different devices: z, )_remove_non_arraysr9   
ValueError)r;   r<   
array_listdevice_r8   device_others         r   r"   r"      s    * $	<  J  t":a=11G ABB  +E22l""PwPP,PP   #
 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   sizerI      s     9QWr   c                     | j         t          v S )z%Return True if xp is backed by NumPy.)__name__r   xps    r   _is_numpy_namespacerN      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_uniquerL   r>   )	rN   sklearn.utils._uniquerP   asarrayr   union1dndimunique_valuesconcat)abrM   rP   a_uniqueb_uniques         r   _union1dr[      s    2 =777777*]1aB777(zz%-(;;<<<6QV    q      BIIr'7'7':':B<L<LQ<O<O&PQQRRRr   c                    |                                                      d|          }g }dD ]!}||v r|                    ||                    "t          | d          r|                    | 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appendr7   r_   tuple)rM   r"   dtypes_dictvalid_float_dtypes	dtype_keys        r   supported_float_dtypesrg      s    B --//66V 7  K + > >	##%%k)&<===r9 .!!"*---#$$$r   c                     g }t          |          }|D ]R}| r|t          ||          rt          j        |          r-t	          |          r=|                    |           S|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,)
        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.
    )rc   
isinstancespissparser   rb   )r;   r<   arraysfiltered_arraysr8   s        r   r?   r?   %  s    , O&&L 	& 	& 	5=e\** 	;u 	5!! 	u%%%%r   )r;   r<   rM   c                 0   t                      d         }|s||dfS t          dfS ||dfS t          || |d}|s	t          dfS t          |           t	          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, `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,)
        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.
    r2   NFTr:   r   set_array_api_strict_flagsz2024.12)api_version)	r   	np_compatr?   r5   r   get_namespacerK   r7   ro   )r;   r<   rM   rl   r2   	namespaceis_array_api_compliants          r   rr   rr   K  s    n $&:; $>u9e##	~4x	!  F   %0111(8(F(OQU%I///G/5 5/ 	,,,CC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,)
        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:   NT)dictr?   r"   rr   )r;   r<   rM   rA   skip_remove_kwargsarrays_deviceis_array_apis          r   get_namespace_and_devicerz     s    : %bAAA#	!  J
 J=*<==M	z(*K8JKKLLtL (<..5-''r   c                 l   d |D             }d |D             }t          |          rt          |           st          d          g }t          |||          D ]1\  }}}|r|                    d           |r|                    |           7t          |          \  }	}
}| |	k    r||k    r|                    |           l	 |                     ||          }n# t          t          t          t          t          f$ rq t          |           rt          ||	          }nNt          |	          r|                     ||          }n't          ||	          }|                     ||          }Y nw xY w|                    |           3t          |          dk    r|d         nt          |          S )aJ  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.

    `array` 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.
    c                 6    g | ]}t          j        |          S  )rj   rk   .0r8   s     r   
<listcomp>zmove_to.<locals>.<listcomp>  s"    :::%2;u%%:::r   c                     g | ]}|d u S Nr}   r~   s     r   r   zmove_to.<locals>.<listcomp>  s    3335$333r   zWSparse arrays are only accepted (and passed through) when the target namespace is NumpyNr"   r>   r   )anyrN   	TypeErrorziprb   rz   from_dlpackAttributeErrorNotImplementedErrorBufferErrorr@   _convert_to_numpyrR   lenrc   )rM   r"   rl   sparse_mask	none_maskconverted_arraysr8   	is_sparseis_nonexp_array_device_arrayarray_convertedarray_nps                 r   move_tor     s   : ;:6:::K33F333I
; 
 3B 7 7 
!
 
 	

 %(i%H%H 29 29!y' 1	9##D)))) /	9##E****(@(G(G%HaX~~&L"8"8 ''....'N ')nnU6n&J&JOO #' N N N +2.. N*;E8*L*L,X66 N*,**U6**J*J $5UH#E#E*,**Xf**M*M'N( !''8888  ##34499uEU?V?Vs   CBE21E2c                     t          | |          \  }}t          |          r9|                    t          j        t          j        |                               S dd|                    |            z   z  S )NrL   g      ?)rr   rN   rR   specialexpitr   exp)XrM   r   s      r   _expitr   2  sj    !###EB2 ;zz'-a(8(899:::#r

"##r   c                    | j         dk    r$t          dt          | j                             |                    || j        t          |                     }|j         dvrt          d|j          d          t          | j                  }|j         dk    r1|j        d         |k    r t          d	| d
|j        d                    ||fS )z:Validate arguments to `_fill_diagonal`/`_add_to_diagonal`.   z+`array` should be 2D. Got array with shape r#   r"   )r   r>   z2`value` needs to be a scalar or a 1D array, got a zD array instead.r>   r   zX`value` needs to be a scalar or 1D array of the same length as the diagonal of `array` (z). Got )rT   r@   rc   rG   rR   r#   r"   min)r8   valuerM   min_rows_columnss       r   _validate_diagonal_argsr   :  s   zQN%:L:LNN
 
 	
 JJuEKuJFFEz2Z2 2 2
 
 	
 5;''zQ5;q>-===N$4N N=B[^N N
 
 	

 """r   c                 
   t          | ||          \  }}t          |          r|                    | |d           dS |j        dk    rt	          |          D ]	}|| ||f<   
dS t	          |          D ]}||         | ||f<   dS )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   rN   fill_diagonalrT   range)r8   r   rM   r   is        r   _fill_diagonalr   Q  s     6eUBGGE2 '
E22222 :??+,, $ $#ad$ $ +,, ' '#Ahad' 'r   c                 N   t          | ||          \  }}t          |          rE| j        d         dz   }| j        d         | j        d         z  }| j        d||xx         |z  cc<   dS |j                            |           |z   }t          |          D ]}||         | ||f<   dS )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.
    r>   N)r   rN   rG   flatlinalgdiagonalr   )r8   r   rM   r   stependr   s          r   _add_to_diagonalr   k  s     6eUBGGE2 {1~!k!nu{1~-
9C9& Iu%%-E#$$  Ahad r   c                 &    | j         |d| d| fv S )Nzarray_api_compat.z#sklearn.externals.array_api_compat.)rK   )rM   names     r   _is_xp_namespacer     s/    ;"D""4d44  r   c                     t          | d          r)t          |                              d          r| j        S | j        S )zJReturn the float dtype with the highest precision supported by the device.r   r   )r   str
startswithr   r   rM   r"   s     r   _max_precision_float_dtyper     sH     G$$ V)?)?* *  z:r   c                       f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                 Z    g | ]'}t          |d                               |          (S r#   )r7   rR   r   rW   rM   s     r   r   z1_find_matching_floating_dtype.<locals>.<listcomp>  s2    JJJqga6I6IJRZZ]]JJJr   c                 T    g | ]$}                     |j        d           |j        %S )r]   )isdtyper#   r   s     r   r   z1_find_matching_floating_dtype.<locals>.<listcomp>  s@       "**QWo*N*N	  r           )result_typerR   r#   )rM   rl   dtyped_arraysfloating_dtypess   `   r   _find_matching_floating_dtyper     su     KJJJFJJJM   &  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        |         ||<   |                    |t          |                    }|                    | 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.
    rL   )axis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>   zcomplex floatingz;Complex floating point values are not supported by average.r   r   z(Weights sum to zero, can't be normalized)rz   rN   rR   r   averagedotrG   r   rc   r@   rT   reshaper   r#   r   r   astypemeansummultiplyr   ZeroDivisionError)rW   r   r   	normalizerM   r   rB   rG   output_dtypesum_scales              r   _averager     s    .aR@@@NB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**WeEll33	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   Fc                 P   t          | |          \  }}}t          j        |          r|                    | d||          S t	          |d          r|                    | ||          S t          | |          }|                    t          j        |||          |          S )NrL   g      ?)qdimkeepdimmedianr   keepdimsr   )	rz   r   is_torch_namespacequantiler7   r   r   rR   r   )rH   r   r   rM   r   r"   x_nps          r   _medianr     s     -Q2666MB6 *2.. A{{1x{@@@r8 :yyy999 Q2&&&D::el4dXFFFv:VVVr   c                 &   t          | ||          \  }}}t          j        dd          5  | |                    |          z  }d d d            n# 1 swxY w Y   |                    | dk    |                    d|j        |          |          S )NrL   ignore)divideinvalidr   r   )rz   r   errstatelogwhererR   r#   )rH   yrM   r   rB   temps         r   _xlogyr     s    -ar:::NB7	x	:	:	:  266!99}              88AHbjjDJwjOOQUVVVs   AAAc           
      *   t          | |          \  }}}t          |          r)|                    t          j        | |                    S |                    |           }|                    |                    ||                    |j        
 | j	        |          |           |          } |
                    ||          }|                    |          r7|                    ||                    |j        | j	        |          |           } | S NrL   r   r   )rz   rN   rR   r   nanminisnanr   r   infr#   allr   nanr   r   rM   r   rB   masks         r   _nanminr          .aB777NB72 zz%,qt444555 xx{{FFHHT2::rvgQWW:MMqQQ  
 

 vvdv&&66$<< 	Urzz"&zPPRSTTAr   c           
      *   t          | |          \  }}}t          |          r)|                    t          j        | |                    S |                    |           }|                    |                    ||                    |j         | j	        |          |           |          } |
                    ||          }|                    |          r7|                    ||                    |j        | j	        |          |           } | S r   )rz   rN   rR   r   nanmaxr   maxr   r   r#   r   r   r   r   s         r   _nanmaxr   )  r   r   c           
         t          | |          \  }}}t          |          r)|                    t          j        | |                    S |                    |           }|                    |                    ||                    d| j        |          |           |          }|                    |	                    |
                    |          | j                  |          }||z  S )NrL   r   r   r   )rz   rN   rR   r   nanmeanr   r   r   r#   r   logical_not)r   r   rM   r   rB   r   totalcounts           r   _nanmeanr   =  s     .aB777NB72 zz%-555666xx{{HHT2::c:II1MMTX  
 
 ryy!5!5qw??dKKu}r   c                 `   t          | |          \  }}}t          |          r+|                    t          j        | |||                    S |                    |           }|                    ||                    d|| j                  |           }|                    ||||          S )NrL   r   r   r#   r   r"   r#   )	rz   rN   rR   r   nansumr   r   r#   r   )	r   r   rM   r   r#   r   X_devicer   
masked_arrs	            r   _nansumr  L  s     /qR888OB82 Vzz%,qtheTTTUUU88A;;D$

1XQW
 M MqQQJ66*4(%6HHHr   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.
    rL   T)orderr#   )r#   copyr"   )rr   rN   r   r8   rR   )r8   r#   r	  r
  rM   r"   r   s          r   _asarray_with_orderr  Y  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.
    rL   C)r	  )rG   )rr   rN   r   rR   ravelr   )r8   rM   r   s      r   _ravelr  w  sp     %B'''EB2 9e$$zz%+e3777888::e5:)))r   c                 v   t          |d          r&|                                                                 S t          |d          r|                                 S t          |d          r<t          j        |                    | |                    d                              S t          j        |           S )z*Convert X into a NumPy ndarray on the CPU.r   r   r   r   r   )r   r   r   r0   rR   r    )r8   rM   s     r   r   r     s    G$$ Pyy{{  """	"f	%	% Pyy{{	"0	1	1 P}RZZbii6M6MZNNOOO=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.baser  varsitemsr7   ri   r   ndarraysetattr)	estimator	converterr  new_estimatorkey	attributes         r    _estimator_with_converted_arraysr     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.Ni  )r   r   finfoeps)dtype_or_dtype_names    r   _atol_for_typer%    s+    " $m;*++/$66r   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   )rR   r#   rL   s    r   indexing_dtyper'    s    * ::a==r   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_elementsassume_uniqueinvertr  )ar1ar2rM   r+  r,  )rN   rR   r   isinrG   r   _in1d)r)  r*  rM   r+  r,  original_element_shapes         r   _isinr2    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          }t          |          d	k    r/|r|d	d
         |d
d         k    n|d	d
         |d
d         k    }n.|r|                    dg          n|                    dg          }|                    ||                    |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
    rL   r   
   g(\?r   T)stabler   r>   Nr  Fr   )rr   rG   onesboolr"   zerosunique_inverserU   rV   argsorttakerI   rR   )r-  r.  rM   r+  r,  r   r   rW   rev_idxarrB   r	  reverse_ordersarbool_arflagrets                    r   r0  r0    sY    #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CyyA~~)/H#abb'S"X%%SWCRC5H *0G"**eW%%%RZZ5G5G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_nonzerorL   )r   sample_weightr   r   Nr>   r  r   )sklearn.utils.sparsefuncsrD  rr   rN   rj   rk   rT   	ones_likerR   r   rG   r   r#   r   r   )	r   r   rE  rM   r"   rD  r   r   zero_scalars	            r   _count_nonzerorI  #  s#    877777!]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 )NrJ  )rN   )rM   funcrJ  argskwargss        r   _modify_in_place_if_numpyrO  ;  sH    2 $d&&v&&&&dD#F##Jr   c                 >   t          | |          \  }}t          |d          r|                    | ||          S t          | |          }|t          ||          }nd }t	          j        |||          }|                    |t          |                     S )NrL   bincount)r   	minlengthr   )rr   r7   rQ  r   r   rR   r"   )r8   r   rR  rM   r   r   
weights_npbin_outs           r   	_bincountrU  C  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 )NrL   c                 6    g | ]}|                                 S r}   )item)r   r)  s     r   r   z_tolist.<locals>.<listcomp>X  s     333wGLLNN333r   )rr   rN   tolistr   )r8   rM   r   r   s       r   _tolistrZ  S  s\    %B'''EB2 ||~~ 2...H33(3333r   c           	         t          | |          \  }}}|!t          t          | j                            n|}t	          |          }| j        |vr|                    | |d                   } |                    | |d          }| |k    }|                    | d          } |j         | |<   |	                    || j                  }|
                    ||d| j                  }	|                    |                    |          ||                    d|j        |                    }
|                    | |
z
            }|
                    ||d|j                  }|                    |dk    |||	z            }|                    |          |                    |	          z   |z   }|                    ||	          }|j        dk    r|d
         n|}|S )NrL   r   r   Tr   )r
  r  r   r   r}   )rz   rc   r   rT   rg   r#   rR   r   r   r   r   r   isfiniter   log1pr   squeeze)r8   r   rM   r   r"   supported_dtypes	array_max	index_maxi_max_dtmshiftr   srJ  s                 r   
_logsumexprf  [  s   
 -Ur:::MB6'+|5uz""###D-b11{***

5(8(;
<<u4$77I"IJJu4J((EwE)yyEK00H
xdTEEAHH
I


1IOF
;; E
 &&

C
sCI>>A
aAE""A
((1++q		
!I
-C
**St*
$
$CX]]#b''CJr   c                     t          |          r!t          j                            | d          S |j                            |           S NT)lower)rN   r,   r   cholesky)
covariancerM   s     r   	_choleskyrl  ~  sC    2 .|$$Zt$<<<y!!*---r   c                     t          |          r"t          j                            | |d          S |j                            | |          S rh  )rN   r,   r   solve_triangularsolve)cov_chol
eye_matrixrM   s      r   _linalg_solverr    sE    2 5|,,Xz,NNNyx444r   c                 z   t          | ||          \  }}}t          |d|          }|                    | |j        |          } |                    | j        d         |          |j        d         z  }|                    t          |          | |z             }t          t          ||z
  ||                    S )zGA version of the multinomial loss that is compatible with the array APIr>   )r   rM   r   r   r   )r   rM   )
rz   rf  rR   int64arangerG   r;  r  floatr   )	r   predrE  rM   r   rB   log_sum_expclass_marginslabel_predictionss	            r   _half_multinomial_lossr{    s    -a}EENB7Tb111K


1BHW
55AIIagajI99DJqMIMta-.?@@00-BOOO  r   )Tr   )NNTN)NFN)NN)NNFN)NNN)FF)NNNN)F__doc__r   rE   r.   r   r,   scipy.sparsesparserj   scipy.specialr   sklearn._configr   sklearn.externalsr   r   r	   "sklearn.externals.array_api_compatrq   sklearn.utils._dataframer   sklearn.utils.fixesr   __all__r   r   r$   r(   r5   r9   r   r"   rI   rN   r[   rg   r?   rr   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r   r%  r'  r2  r0  rI  rO  rU  rZ  rf  rl  rr  r{  r}   r   r   <module>r     s   ! !
      				               & & & & & & . . . . . . 4 4 4 4 4 4 A A A A A A 4 4 4 4 4 4 - - - - - - '!#MN    >0. 0. 0. 0.f  "
 
 
6    %)v ) ) ) ) )X   1 1 1
S S S,% ,% ,% ,%^ -1v # # # # #L (,3&T S- S- S- S- S-n "4.( .( .( .( .(b] ] ]@$ $ $ $# # #.' ' '4  6    ! ! !2? ? ? ?DW W W W0W W W W   (   (   
I 
I 
I 
I )-H48H H H H H<* * * *	  	  	   :7 7 7  0   D.- .- .- .-bE E E E0 48     5 5 5 5 4 4 4 4       F. . .5 5 5	 	 	 	 	 	r   