
    ^MhQW                        U d Z ddlZddlmZ ddlmZmZmZ ddlZ	ddl
mZ ddlmZ ddlmZmZmZmZmZmZmZmZmZ g dZej         !                    dd	          Z"e#e$z  e%d<   ej         !                    d
d          Z&e"e&dZ'eZ(ee%d<   e(ej)        z  Z)ee%d<   d Z*de(deddfdZ+de(defdZ,	 	 	 dLdd	d	dde)deded         dz  de$dz  dedz  de$de$de(fdZ-ddde(dedz  de(fd Z.d!d!d!d!d"d#Z/d$ Z0d!d!d!d!d%dd&d'Z1ddd!d!d!d!d%dd(d)Z2d!d!d!d!d%d!dd*d+Z3dMd-Z4dNd/Z5d0ede#fd1Z6de(dede$fd2Z7dede8e#         e8d         z  fd3Z9dededz  fd4Z:ddde(d5e;dedz  de(fd6Z<ddd7e(d8e(dedz  de(fd9Z=ddde(dedz  de(fd:Z>dd	d;dd<de(d=e;e?e;         z  dz  d>e$d?e;e@z  dedz  de(fd@ZAddde(dedz  de(fdAZBddde(dedz  de(fdBZCdCddDdEe(dFe(d=e;dedz  de(f
dGZDd	d	ddHdIZEdOdEe(dedz  de(fdJZFdK ZGdS )Pa6  Utility functions to use Python Array API compatible libraries.

For the context about the Array API see:
https://data-apis.org/array-api/latest/purpose_and_scope.html

The SciPy use case of the Array API is described on the following page:
https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy
    N)
ModuleType)AnyLiteral	TypeAlias)array_api_compat)	is_array_api_objsizenumpydeviceis_numpy_namespaceis_cupy_namespaceis_torch_namespaceis_jax_namespaceis_array_api_strict_namespace)_asarrayarray_namespaceassert_almost_equalassert_array_almost_equalget_xp_devicesis_array_api_strict
is_complexis_cupyis_jaxis_numpyis_torchSCIPY_ARRAY_APISCIPY_DEVICEscipy_namespace_forxp_assert_closexp_assert_equalxp_assert_lessxp_copyxp_copysign	xp_devicexp_moveaxis_to_endxp_ravelxp_realxp_signxp_sizexp_take_along_axisxp_unsupported_param_msgxp_vector_normr   Fr   cpu)r   r   Array	ArrayLikec                    t          t          |                     D ]}| |         }ddlm}  ||          rd}t	          |          t          |t          j        j                  rt          d          t          |t          j
                  rt          d          t          |t          j        t          j        z            rZ|j        }t          j        |t          j                  s2t          j        |t          j                  st          d|d          t#          |          s	 t          j        |          }n# t          $ r t          d          w xY w|j        }t          j        |t          j                  s4t          j        |t          j                  sd	|d}t          |          || |<   | S )
a  Raise exceptions on known-bad subclasses.

    The following subclasses are not supported and raise and error:
    - `numpy.ma.MaskedArray`
    - `numpy.matrix`
    - NumPy arrays which do not have a boolean or numerical dtype
    - Any array-like which is neither array API compatible nor coercible by NumPy
    - Any array-like which is coerced by NumPy to an unsupported dtype
    r   )issparsezSparse arrays/matrices are not supported by this function. Perhaps one of the `scipy.sparse.linalg` functions would work instead.z8Inputs of type `numpy.ma.MaskedArray` are not supported.z0Inputs of type `numpy.matrix` are not supported.zAn argument has dtype `z3`; only boolean and numerical dtypes are supported.zCAn argument is neither array API compatible nor coercible by NumPy.z1An argument was coerced to an unsupported dtype `)rangelenscipy.sparser1   
ValueError
isinstancenpmaMaskedArray	TypeErrormatrixndarraygenericdtype
issubdtypenumberbool_r   
asanyarray)arraysiarrayr1   msgr>   messages          U/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/_lib/_array_api.py_compliance_scipyrI   9   s    3v;; ! !q	))))))8E?? 	")C S//!eRU.// 	PVWWWry)) 	PNOOOeRZ"*455 	KEM%33 Ur}UBH7U7U U !T% !T !T !T U U U!%(( 	7e,, 7 7 7 !6 7 7 77 KEM%33 )r}UBH7U7U )H H H H   (((F1IMs   2EE!rE   xpreturnc                     d}	 |                     |                    |                     st          |          dS # t          $ r t          |          w xY w)zCheck for NaNs or Infs.z#array must not contain infs or NaNsN)allisfiniter5   r:   )rE   rJ   rF   s      rH   _check_finiterO   h   si    
/Cvvbkk%(()) 	"S//!	" 	"   oos	   7= ArC   c                  |    t           d         st          S d | D             }t          |          }t          j        | S )a1  Get the array API compatible namespace for the arrays xs.

    Parameters
    ----------
    *arrays : sequence of array_like
        Arrays used to infer the common namespace.

    Returns
    -------
    namespace : module
        Common namespace.

    Notes
    -----
    Thin wrapper around `array_api_compat.array_namespace`.

    1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed
       dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``.
    2. `_compliance_scipy` raise exceptions on known-bad subclasses. See
       its definition for more details.

    When the global switch is False, it defaults to the `numpy` namespace.
    In that case, there is no compliance check. This is a convenience to
    ease the adoption. Otherwise, arrays must comply with the new rules.
    r   c                     g | ]}||S N ).0rE   s     rH   
<listcomp>z#array_namespace.<locals>.<listcomp>   s    >>>E,=u,=,=,=    )_GLOBAL_CONFIG	np_compatrI   r   r   )rC   _arrayss     rH   r   r   r   sF    4 +, >>&>>>G((G+W55rV   )rJ   check_finitesubokr>   order)KACFcopyrZ   r[   c                   |t          |           }t          |          rO|du rt          j        | |||          } n|rt          j        | ||          } n|t          j        | ||          } nd	 |                    | ||          } nJ# t          $ r= t          |                    d                    }|                    | ||          } Y nw xY w|rt          | |           | S )a`  SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and
    `subok`.

    Memory layout parameter `order` is not exposed in the Array API standard.
    `order` is only enforced if the input array implementation
    is NumPy based, otherwise `order` is just silently ignored.

    `check_finite` is also not a keyword in the array API standard; included
    here for convenience rather than that having to be a separate function
    call inside SciPy functions.

    `subok` is included to allow this function to preserve the behaviour of
    `np.asanyarray` for NumPy based inputs.
    NT)r\   r>   r[   )r\   r>   )r>   ra      )r   r   r7   rE   rB   asarrayr:   rO   )rE   r>   r\   ra   rJ   rZ   r[   
coerced_xps           rH   r   r      s   0 
zU##|| F4<<HU%uEJJJEE 	@M%uEBBBEEJuE???EE	FJJuEJ==EE 	F 	F 	F(A77J&&uE&EEEEE	F  !eR   Ls   1B
 
ACCrJ   xc                H    |t          |           }t          | d|          S )a3  
    Copies an array.

    Parameters
    ----------
    x : array

    xp : array_namespace

    Returns
    -------
    copy : array
        Copied array

    Notes
    -----
    This copy function does not offer all the semantics of `np.copy`, i.e. the
    `subok` and `order` keywords are not used.
    NT)ra   rJ   )r   r   rg   rJ   s     rH   r"   r"      s+    , 
zQADR((((rV   Tcheck_namespacecheck_dtypecheck_shapecheck_0dc                   d}|rt          | |           t          |          r|rdt          |            dt          |           }|                    |           r|                    |          s4|                    |           s|                    |          r
J |            |                    |           } |                    |          }|r,d| j         d|j         }| j        |j        k    s
J |            |r,d| j         d|j         }| j        |j        k    s
J |            |                    || j                  }| |fS )NTz$Array-ness does not match:
 Actual: z
 Desired: zdtypes do not match.
Actual: 

Desired: zShapes do not match.
Actual: )_assert_matching_namespacer   typeisscalarrd   r>   shapebroadcast_to)	actualdesiredrJ   rk   rl   rm   rn   __tracebackhide___msgs	            rH   _strict_checkrz      s     4"67333 || Q Q=<<= =-1']]= =V$$ 	QW)=)= 	QF++	Q46KK4H4H	Q 	QLP	Q 	Q 	Q ZZFjj!!G 3XXXXX|w},,,d,,, 3XXXXX|w},,,d,,,oogv|44G7?rV   c                     d}t          | t                    r| n| f} t          |          }| D ]3}t          |          }d|j         d|j         }||k    s
J |            4d S )NTz!Namespaces do not match.
Actual: rp   )r6   tupler   __name__)rv   rw   rx   desired_spacearr	arr_spacery   s          rH   rq   rq      s    !&%00?VVviF#G,,M 0 0#C((	5$-5 5)25 5 M)))4))))0 0rV    )rk   rl   rm   rn   err_msgrJ   c          	      j   d}|t          |           }t          | ||||||          \  } }t          |          r|j                            | ||          S t          |          r+|dk    rd n|}|j                            | |dddd|          S t          j                            | ||          S )NTrj   )r   r   r   Frtolatol	equal_nanrl   rF   )r   rz   r   testingassert_array_equalr   assert_closer7   )	rv   rw   rk   rl   rm   rn   r   rJ   rx   s	            rH   r    r      s    	zV$$#_[  OFG r{{ Gz,,VWg,NNN	" G "R--$$Wz&&vwQQRV38g ' G G 	G :(('(JJJrV   )r   r   rk   rl   rm   rn   r   rJ   c          	         d}
|	t          |           }	t          | ||	||||          \  } }|	                    | j        d          }|(|r&|	                    | j                  j        dz  dz  }n|d}t          |	          r|	j                            | ||||          S t          |	          r+|dk    rd n|}|	j        
                    | |||dd	|
          S t          j                            | ||||          S )NTrj   )real floatingcomplex floating      ?   gHz>)r   r   r   r   Fr   )r   rz   isdtyper>   finfoepsr   r   assert_allcloser   r   r7   )rv   rw   r   r   rk   rl   rm   rn   r   rJ   rx   floatings               rH   r   r   $  sP    	zV$$#'[(  OFG zz&,(MNNH|| xx%%)3.2	r{{ Wz))&'/3W * F F 	F	" W!R--$$Wz&&vwT155g ' W W 	W :%%fgD+/ & B B BrV   )rk   rl   rm   rn   r   verboserJ   c          	         d}	|t          |           }t          | ||||||          \  } }t          |          r|j                            | |||          S t          |          rH| j        j        dk    r|                                 } |j        j        dk    r|                                }t          j                            | |||          S )NTrj   )r   r   r-   )
r   rz   r   r   assert_array_lessr   r   rr   r-   r7   )
rv   rw   rk   rl   rm   rn   r   r   rJ   rx   s
             rH   r!   r!   F  s    	zV$$#_[  OFG r{{ $z++FG4;W , N N 	N	" $=&&ZZ\\F>%''kkmmG:''07 ( J J JrV      c                 D    ddd| z  z  }}t          | |g|R ||ddd|S zPBackwards compatible replacement. In new code, use xp_assert_close instead.
    r   g      ?
   F)r   r   rl   rm   r   rv   rw   decimalargskwdsr   r   s          rH   r   r   _  W     CgX&$D67 * * * $4UPU* *$(* * *rV      c                 D    ddd| z  z  }}t          | |g|R ||ddd|S r   r   r   s          rH   r   r   h  r   rV   paramc                     d| dS )Nz
Providing z$ is only supported for numpy arrays.rS   )r   s    rH   r+   r+   q  s    EEEEErV   c                 8    |                     | j        d          S Nr   )r   r>   ri   s     rH   r   r   u  s    ::ag1222rV   c                    g }t          |           re|dgz  }ddl}|j                                        }t	          d|          D ]}|d| gz  }|j        j                                        r|dgz  }|S t          |           r@ddl	}|j        j
                                        }t	          d|          D ]}|d| gz  }|S t          |           rddl}|                    d          }t	          d|          D ]}|d| gz  }|                    d          }t	          d|          D ]}|d	| gz  }|                    d
          }	t	          d|	          D ]}|d| gz  }|S dgS )z<Returns a list of available devices for the given namespace.r-   r   Nzcuda:mps)backendzcpu:gpuzgpu:tpuztpu:)r   torchcudadevice_countr2   backendsr   is_availabler   cupyruntimegetDeviceCountr   jax)
rJ   devicesr   num_cudarD   r   r   num_cpunum_gpunum_tpus
             rH   r   r   y  s   G|| E7:**,,q(## 	% 	%A}$GG>**,, 	wG	 9$3355q(## 	% 	%A}$GG	 


""5"11q'"" 	$ 	$A
q

|#GG""5"11q'"" 	$ 	$A
q

|#GG""5"11q'"" 	$ 	$A
q

|#GG 6MrV   c                     t          |           rddl}|j        S t          |           rddl}|j        S t          |           r| S dS )a  Return the `scipy`-like namespace of a non-NumPy backend

    That is, return the namespace corresponding with backend `xp` that contains
    `scipy` sub-namespaces like `linalg` and `special`. If no such namespace
    exists, return ``None``. Useful for dispatching.
    r   N)r   cupyxscipyr   r   r   )rJ   r   r   s      rH   r   r     sZ     r{{ {bzz 


y|| 	4rV   sourcec                   |t          |          n|}t          t          | j                            }|                    |          }||gz   }|                    | |          S rR   )r   listr2   ndimpoppermute_dims)rg   r   rJ   axestemps        rH   r%   r%     s_    
 !#
			BafD88FD4&=D??1d###rV   x1x2c                   |t          | |          n|}|                    |           }|                    |dk    ||           S )Nr   )r   abswhere)r   r   rJ   abs_x1s       rH   r#   r#     sE    $&JR	 	 	 BBVVBZZF88B!GVfW---rV   c                  |t          |           n|}t          |          r|                    |           S |                    |           }|                    d| j                  }|                    | dk    ||          }|                    | dk     | |          }|                    |                    |           |j        |z  |          }|S )N   r>   r   )	r   r   sign
zeros_likerd   r>   r   isnannan)rg   rJ   r   ones       rH   r(   r(     s    !z			rB|| wwqzz==D
**Qag*
&
&C88AE3%%D88AEC4&&D88BHHQKKT22DKrV      )axiskeepdimsordrJ   r   r   r   c               d   |t          |           n|}t          rtt          |d          r|j                            | |||          S |dk    rt          d          |                    |                    |           | z  ||          dz  S t          j        	                    | |||          S )Nlinalg)r   r   r   r   zonly the Euclidean norm (`ord=2`) is currently supported in `xp_vector_norm` for backends not implementing the `linalg` extension.)r   r   r   )r   r   r   )
r   r   hasattrr   vector_normr5   sumconjr7   norm)rg   r   r   r   rJ   s        rH   r,   r,     s    
  "z			rB H2x   	M9((c(RRRaxx !   66"''!**q.th6GGLL y~~aSth~GGGrV   c               T    |t          |           n|}|                    | d          S )N))r   reshaperi   s     rH   r&   r&     s.      "z			rB::arV   c                   |t          |           n|}|                    | j        d          r|                    |           n| S r   )r   r   r>   realri   s     rH   r'   r'     sD      "z			rBAG-?@@G2771:::aGrV   r   )r   rJ   r   indicesc                   |t          |           n|}t          |          r|                    | ||          S t          |          rt	          d          |                    | ||          S )N)dimz2Array API standard does not define take_along_axis)r   r   take_along_dimr   NotImplementedErrortake_along_axis)r   r   r   rJ   s       rH   r*   r*     sz     "$			B|| 6  g4 888	R	 	  6!"VWWW!!#w555rV   )ensure_writeableforce_floatingrJ   c                 `   	t          | nd |D             }d |D             }                    d          j        }d |D             }	  j        | }|r,                    |d          r                    ||          }n?# t
          $ r2 fd|D             }|r j        g ||R  }n|r|}n
 j        | }Y nw xY wd |D             }		 t          |	          dk    rt          j        |	 n|d	         j	        }
n$# t          $ r}d
}t          |          |d }~ww xY wg }|D ]}||                    |           |j	        |
k    r$t                    rddini } j        ||
fi |}|j        |k    s| r                    ||d          }|                    |           |S )Nc                 8    g | ]}|t          |d          n|S )NT)r[   )r   rT   args     rH   rU   z(xp_broadcast_promote.<locals>.<listcomp>  s.    TTT#/Xc&&&&sTTTrV   c                     g | ]}||S rR   rS   r   s     rH   rU   z(xp_broadcast_promote.<locals>.<listcomp>  s    <<<SCOSOOOrV   g      ?c                     g | ]	}|j         
S rS   r   r   s     rH   rU   z(xp_broadcast_promote.<locals>.<listcomp>      111Cci111rV   integralc                 @    g | ]}                     |d           |S )r   )r   )rT   r>   rJ   s     rH   rU   z(xp_broadcast_promote.<locals>.<listcomp>!  s;     > > >%!zz%<<> > > >rV   c                     h | ]	}|j         
S rS   )rt   r   s     rH   	<setcomp>z'xp_broadcast_promote.<locals>.<setcomp>+  r   rV   r   r   z/Array shapes are incompatible for broadcasting.r[   T)ra   )r   rd   r>   result_typer   r:   r3   r7   broadcast_shapesrt   r5   appendr   ru   astype)r   r   rJ   r   args_not_nonedefault_floatdtypesr>   float_dtypesshapesrt   erG   outr   kwargss     `             rH   xp_broadcast_promoter    s_   #%:$		2BTTtTTTD<<D<<<M JJrNN(M11=111F,' 	9bjj
;; 	9 NN5-88E , , ,> > > >6 > > > 	,"BN@L@-@@@EE 	,!EE"BNF+E, 21=111F)14V1A1A$f--#A&, 	 ) ) )C!!q() C  ;JJsOOO
 9(0<gt__"F!"/#u7777C I#3))CT)22C

3Js*   8B 9CC.D 
D#DD#c                 
   |t          |           n|}| j        }|                    ||j                  r|                    | |j                  } n1|                    |d          r|                    | |j                  } | S )Nr   )r   r>   r   float32r   	complex64
complex128)r   rJ   	arr_dtypes      rH   xp_float_to_complexr	  H  s    !#			B	I 
zz)RZ(( ,iiR\**	I	/	/ ,iiR]++JrV   c                 V    t          |           r|                                 S | j        S )z@Query the namespace-dependent default floating-point dtype.
    )r   get_default_dtypefloat64rf   s    rH   xp_default_dtyper  V  s.     || ##%%% zrV   )NNN)r   )r   rR   )H__doc__ostypesr   typingr   r   r   r
   r7   numpy.typingnpt
scipy._libr   scipy._lib.array_api_compatr   r	   r)   rX   r   r$   r   r   r   r   r   r   r   r   r   r   __all__environgetr   strbool__annotations__r   rW   r.   r/   rI   rO   r   r   r"   rz   rq   r    r   r!   r   r   r+   r   r   r   r   intr%   r#   r(   r|   floatr,   r&   r'   r*   r  r	  r  rS   rV   rH   <module>r     s     
			       * * * * * * * * * *           ' ' ' ' ' '
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
	 	 	 !jnn->FFt F F Fz~~ne44 '   y   s},	9 , , ,, , ,^ J 4    "6U "6z "6 "6 "6 "6N 48 	, !%", , ,,, )*T1, Tk	, , , , 
, , , ,^ 26 ) ) )u )Z$. )% ) ) ) ): #'Dd    <	0 	0 	0 9=$ $tRDK K K K K0 .24 $$4B B B B BD 8<#dBQUJ J J J J2* * * ** * * *FC FC F F F F3% 3Z 3D 3 3 3 3!z !d3i$t*&< ! ! ! !HJ :+<    8 !%		$ 	$ 	$	$	$ 		$ */		$ 	$ 	$ 	$ EI . . .E .u .
T0A .U . . . . 59 	 	 	u 	
T 1 	U 	 	 	 	 48$)&'+/	H H He HuSz)D0H!H eH "D(	H 5:	H H H H4 6:        d!2  e         59 H H Hu H
T 1 HU H H H H $&/36 6 6E 6 %6 6 &,6 9>6 6 6 6  27uQU 4 4 4 4 4n U 
T(9 U        rV   