
    UgH                    >   U d Z ddlmZ ddl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 g dZej                            d	d
          Zded	<   ej                            dd          ZeedZe
reZeej        z  ZdMdZdNdZ dOdZ!	 	 	 dPdd
d
ddQd'Z"dd(dRd,Z#dd(dSd-Z$dTd.Z%dTd/Z&dTd0Z'd1 Z(	 dUd3Z)d4 Z*d5 Z+	 	 dVd7Z,	 	 dWd8Z-	 	 dXd9Z.dd(dSd:Z/dYd=Z0dZd>Z1d[d@Z2d\dAZ3d]dDZ4	 	 d^dd(d_dHZ5dd(d`dJZ6dd(dadKZ7dd(dSdLZ8dS )ba6  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
    )annotationsN)
ModuleType)AnyLiteralTYPE_CHECKING)array_api_compat)is_array_api_objsizenumpydevice)array_namespace_asarrayr
   r   SCIPY_ARRAY_APIFz
str | boolSCIPY_DEVICEcpu)r   r   arrayslist[ArrayLike]returnlist[Array]c                F   t          t          |                     D ]}| |         }t          |t          j        j                  rt          d          t          |t          j                  rt          d          t          |t          j        t          j	        f          rY|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
    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
isinstancenpmaMaskedArray	TypeErrormatrixndarraygenericdtype
issubdtypenumberbool_r	   
asanyarray)r   iarrayr!   messages        T/var/www/surfInsights/venv3-11/lib/python3.11/site-packages/scipy/_lib/_array_api.pycompliance_scipyr*   /   s    3v;;  q	eRU.// 	PVWWWry)) 	PNOOOebj"*566 	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   D##D=r'   Arrayxpr   Nonec                    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isfinite
ValueErrorr   )r'   r,   msgs      r)   _check_finiter3   U   si    
/Cvvbkk%(()) 	"S//!	" 	"   oos	   7= Ac                 |    t           d         st          S d | D             }t          |          }t          j        | S )a0  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 ).0r'   s     r)   
<listcomp>z#array_namespace.<locals>.<listcomp>}   s    >>>E,=u,=,=,=    )_GLOBAL_CONFIG	np_compatr*   r   r   )r   _arrayss     r)   r   r   _   sF    4 +, >>&>>>Gw''G+W55r:   )r,   check_finitesubok	ArrayLiker!   r   order"Literal['K', 'A', 'C', 'F'] | Nonecopybool | NoneModuleType | Noner>   boolr?   c                  |t          |           }|j        dv rd|du rt          j        | |||          } n1|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.
    N>   r   !scipy._lib.array_api_compat.numpyT)rA   r!   r?   )rA   r!   )r!   rC      )r   __name__r   r'   r%   asarrayr   r3   )r'   r!   rA   rC   r,   r>   r?   
coerced_xps           r)   r   r      s%   0 
zU##	{DDD4<<HU%uEJJJEE 	@M%uEBBBEEJuE???E 

5!!	FJJuEJ==EE 	F 	F 	F(A77J&&uE&EEEEE	F  !eR   Ls    B AC C r,   xndimintc                   |t          |           }|                    |           } | j        |k     r)|                    | d          } t	          | ||          } | S )z9Recursively expand the dimension to have at least `ndim`.Nr   axisrO   r,   )r   rK   rO   expand_dims
atleast_nd)rN   rO   r,   s      r)   rV   rV      s\    	zQ


1Av}}NN11N%%qt+++Hr:   c               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)rC   r,   )r   r   rN   r,   s     r)   rC   rC      s+    * 
zQADR((((r:   c                    | j         dv S )N)r   rH   rJ   rM   s    r)   is_numpyr[          ;HHHr:   c                    | j         dv S )N)cupyz scipy._lib.array_api_compat.cupyrZ   rM   s    r)   is_cupyr_      s    ;FFFr:   c                    | j         dv S )N)torchz!scipy._lib.array_api_compat.torchrZ   rM   s    r)   is_torchrb      r\   r:   c                    | j         dv S )N)z	jax.numpyzjax.experimental.array_apirZ   rM   s    r)   is_jaxrd      s    ;EEEr:   Tc                h   d}|rt          | |           |                    |          }|r,d| j         d|j         }| j        |j        k    s
J |            |r=d| j         d|j         }| j        |j        k    s
J |            t	          | ||           |                    || j                  }|S )NTzdtypes do not match.
Actual: 

Desired: zShapes do not match.
Actual: )_assert_matching_namespacerK   r!   shape_check_scalarbroadcast_to)actualdesiredr,   check_namespacecheck_dtypecheck_shape__tracebackhide___msgs           r)   _strict_checkrr      s     4"67333jj!!G 3XXXXX|w},,,d,,, +XXXXX|w},,,d,,,fgr***oogv|44GNr:   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: rf   )r   tupler   rJ   )rk   rl   rp   desired_spacearr	arr_spacerq   s          r)   rg   rg     s    !&%00?VVviF#G,,M 0 0#C((	5$-5 5)25 5 M)))4))))0 0r:   c                V   d}|j         dk    st          |          sd S |d         }dt          |            dt          |           }|                    |           r|                    |          s4|                    |           s|                    |          rJ |            d S d S )NTr7   zTypes do not match:
 Actual: z
 Desired: )rh   r[   typeisscalar)rk   rl   r,   rp   rq   s        r)   ri   ri     s     }(2,, bkGUDLLUUd7mmUUDKK MBKK$8$8 MKK''M02G0D0DM MHLM M M M M M Mr:    c           	     b   d}|t          |           }t          | |||||          }t          |          r|j                            | ||          S t          |          r+|dk    rd n|}|j                            | |dddd|          S t          j                            | ||          S )NTrm   rn   ro   )err_msgr{   r   Frtolatol	equal_nanrn   r2   )r   rr   r_   testingassert_array_equalrb   assert_closer   )rk   rl   rm   rn   ro   r~   r,   rp   s           r)   xp_assert_equalr   &  s    	zV$$FGR(3N N NGr{{ Gz,,VWg,NNN	" G "R--$$Wz&&vwQQRV38g ' G G 	G :(('(JJJr:   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 )NTr}   )zreal floatingcomplex floatingg      ?   gHz>)r   r   r~   r{   Fr   )r   rr   isdtyper!   finfoepsr_   r   assert_allcloserb   r   r   )rk   rl   r   r   rm   rn   ro   r~   r,   rp   floatings              r)   xp_assert_closer   9  sI   	zV$$FGR(3N N NG 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r:   c                   d}|t          |           }t          | |||||          }t          |          r|j                            | |||          S t          |          rH| j        j        dk    r|                                 } |j        j        dk    r|                                }t          j                            | |||          S )NTr}   )r~   verboser   )
r   rr   r_   r   assert_array_lessrb   r   ry   r   r   )	rk   rl   rm   rn   ro   r~   r   r,   rp   s	            r)   xp_assert_lessr   V  s    	zV$$FGR(3N N NGr{{ $z++FG4;W , N N 	N	" $=&&ZZ\\F>%''kkmmG:''07 ( J J Jr:   c                  |t          |           }t          | |          }|                    ||j                  }t	          |d|          }|                    ||          }|                    |d          }|j        d         dz
  }|dk    rt          j	        dt          d	           d
}||d d d f         z  }|j        }|                    |j        d          r|                    |          }||z  }||z  }t          d t!          |j                  D                       }|                    ||          S )NrM      rT   r!      rR   r   z!Degrees of freedom <= 0 for slice)
stacklevelg        r   c              3  ,   K   | ]\  }}|d k    |V  dS )r   Nr7   )r8   rS   lengths      r)   	<genexpr>zcov.<locals>.<genexpr>  s*      LL,$!LLr:   )r   rC   result_typefloat64rV   rK   meanrh   warningswarnRuntimeWarningTr   r!   conjrt   	enumeratesqueeze)	rN   r,   Xr!   avgfactX_Tcaxess	            r)   covr   j  sG   	zQQ2ANN1bj))E11$$$A


1E
""A
''!!'

C71:>Dqyy9$	4 	4 	4 	4QQQWA
#C	zz#)/00 ggcll	CAIALL)AG*<*<LLLLLD::ad:###r:   paramstrc                    d| dS )Nz
Providing z$ is only supported for numpy arrays.r7   )r   s    r)   xp_unsupported_param_msgr     s    EEEEEr:   c                8    |                     | j        d          S )Nr   )r   r!   rX   s     r)   
is_complexr     s    ::ag1222r:   list[str] | list[None]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:)rb   ra   cudadevice_countr   backendsr   is_availabler_   r^   runtimegetDeviceCountrd   jax)
r,   devicesra   num_cudar&   r^   r   num_cpunum_gpunum_tpus
             r)   get_xp_devicesr     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 6Mr:   c                v    t          |           rddl}|j        S t          |           rddl}|j        S ddl}|S )z
    Return the `scipy` namespace for alternative backends, where it exists,
    such as `cupyx.scipy` and `jax.scipy`. Useful for ad hoc dispatching.

    Default: return `scipy` (this package).
    r   N)r_   cupyxscipyrd   r   )r,   r   r   r   s       r)   scipy_namespace_forr     sP     r{{ {bzz 


yLLLLr:   x1x2c               0   t          | |          }t          |d          r|                    | |          S |                    | |          \  } }|| k     |                    |          z  }|                    |||           }|j        dk    r|d         n|S )Nminimumr   r7   )r   hasattrr   broadcast_arraysisnanwhererO   )r   r   r,   r&   ress        r)   
xp_minimumr     s    	R	 	 Br9 "zz"b!!!  R((FB	bBHHRLL A
((1b"

Ch!mm3r77,r:   minint | float | Array | Nonemaxc                 |t          |           n|}|                    || j                  |                    || j                  }}t          |d          r|                    | ||          S |                    | ||          \  } }}|                    | d          }||k     }||         ||<   ||k    }||         ||<   |j        dk    r|d         n|S )Nr   clipT)rC   r   r7   )r   rK   r!   r   r   r   rO   )	rN   r   r   r,   abyiaibs	            r)   xp_clipr     s      "z			rB::c:))2::c:+I+IqAr6  wwq!Q!!!Q**GAq!


14
  A	
QBbEAbE	
QBbEAbEFaKK1R55Q&r:   sourcec                  |t          |          n|}t          t          | j                            }|                    |          }||gz   }|                    | |          S r6   )r   listr   rO   poppermute_dims)rN   r   r,   r   temps        r)   xp_moveaxis_to_endr     s_    
 !#
			BafD88FD4&=D??1d###r:   c                  |t          | |          n|}|                    |           }|                    |dk    ||           S )Nr   )r   absr   )r   r   r,   abs_x1s       r)   xp_copysignr     sE    $&JR	 	 	 BBVVBZZF88B!GVfW---r:   c                 |t          |           n|}t          |          r|                    |           S |                    | |j                  }|                    d| j                  }|                    | dk    ||          }|                    | dk     | |          }|                    | dk    d|z  |          }|S )Nr   r   r   )r   r[   sign	full_likenanrK   r!   r   )rN   r,   r   ones       r)   xp_signr     s    !z			rB|| wwqzz<<26""D
**Qag*
&
&C88AE3%%D88AEC4&&D88AFAcE4((DKr:   )r   r   r   r   )r'   r+   r,   r   r   r-   )r   r+   r   r   )NNN)r'   r@   r!   r   rA   rB   rC   rD   r,   rE   r>   rF   r?   rF   r   r+   )rN   r+   rO   rP   r,   rE   r   r+   )rN   r+   r,   rE   r   r+   )r,   r   r   rF   )TTT)TTTr{   N)Nr   TTTr{   N)TTTr{   TN)r   r   r   r   )rN   r+   r,   r   r   rF   )r,   r   r   r   )r,   r   r   r   )r   r+   r   r+   r   r+   )NN)
r   r   r   r   rN   r+   r,   rE   r   r+   )rN   r+   r   rP   r,   rE   r   r+   )r   r+   r   r+   r,   rE   r   r+   )9__doc__
__future__r   osr   typesr   typingr   r   r   r   r   numpy.typingnpt
scipy._libr   scipy._lib.array_api_compatr	   r
   r<   r   __all__environgetr   __annotations__r   r;   r+   r@   r*   r3   r   r   rV   rC   r[   r_   rb   rd   rr   rg   ri   r   r   r   r   r   r   r   r   r   r   r   r   r   r7   r:   r)   <module>r      s8     # " " " " " 				        . . . . . . . . . .           ' ' ' ' ' '            <
;
; !jnn->FF F F F Fz~~ne44 '    &E%I# # # #L   "6 "6 "6 "6N 48 	0 !%"0 0 0 0 0 0f @D       /3 ) ) ) ) ) )6I I I IG G G GI I I IF F F
 GK   *	0 	0 	0M M M2 HL59K K K K& IMGKB B B B: GKBFJ J J J( .2 $ $ $ $ $ $8F F F F3 3 3 3! ! ! !H   .- - - -  +/*.	' !%' ' ' ' ' '4 !%		$ 	$ 	$ 	$ 	$ 	$ EI . . . . . . 59 	 	 	 	 	 	 	 	r:   