
    ukiL             	         d dl mZ d dlmZ d dl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 d dlm	Z d d	lmZmZmZ d d
lmZ d d
lmZ d dlmZ d dlmZmZmZmZm Z  d dl!m"Z" d dl#m$Z$m%Z%  ejL                  d      Z'e'dz   Z( ed      dd       Z)	 	 d	 	 	 ddZ*	 	 d	 	 	 ddZ+ ed      dd       Z,	 d	 	 	 	 	 ddZ-edd       Z.edd       Z.edd       Z. ed      dd       Z.e	 	 	 d	 	 	 	 	 	 	 dd!       Z/e	 	 d	 	 	 	 	 	 	 dd"       Z/edddd d#	 	 	 	 	 	 	 dd$       Z/e	 	 	 d	 	 	 	 	 	 	 dd%       Z/	 	 	 d	 	 	 	 	 	 	 dd&Z/ddd'Z0e	 	 	 	 	 	 dd(       Z1e	 	 	 	 	 	 dd)       Z1e	 	 	 	 	 	 dd*       Z1 ed+      	 	 	 	 	 	 dd,       Z1e	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd.       Z2edddddd-dd/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd0       Z2e	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd1       Z2e	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd2       Z2	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd3Z2 ed4      dd5       Z3ddd6Z4ddd7Z5 ed8      ddd9       Z6 ed:      	 	 d	 	 	 	 	 dd;       Z7edd<       Z8edd=       Z8edd>       Z8 ed?@      ddA       Z8e	 	 d	 	 	 ddB       Z9e	 	 d	 	 	 ddC       Z9e	 	 d	 	 	 ddD       Z9 edE      	 	 d	 	 	 ddF       Z9e	 	 ddG       Z:e	 	 ddH       Z:e	 	 ddI       Z:e	 	 ddJ       Z:e	 	 ddK       Z:e	 	 ddL       Z:e	 	 ddM       Z: edN      	 	 ddO       Z:eddddP	 	 	 	 	 	 	 ddQ       Z;eddddP	 	 	 	 	 	 	 ddR       Z;eddddP	 	 	 	 	 	 	 ddS       Z;eddddP	 	 	 	 	 	 	 ddT       Z;eddddP	 	 	 	 	 	 	 ddU       Z;eddddP	 	 	 	 	 	 	 ddV       Z;e	 	 d	 	 	 	 	 ddW       Z;	 	 d	 	 	 	 	 ddXZ; edY      ddZ       Z<	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd[Z= ed\      	 	 	 	 	 	 dd]       Z>	 	 	 d	 	 	 	 	 	 	 	 	 dd^Z? ed_      dd`d_dda       Z@eddb       ZAdddcZBdddZC ede@      ddf       ZDddgZEddhZFddiZGddjZHddkZIedddl	 	 	 ddn       ZJeddo	 	 	 ddp       ZJedddl	 	 	 ddq       ZJ edl      dddl	 	 	 ddr       ZJedds       ZK edt      dddddu	 	 	 	 	 	 	 ddw       ZL edx       ej                  dy      ddzddd{	 	 	 dd|              ZNedd}       ZOedd~       ZPd?ddZQ ed      ddd       ZReddd8	 	 	 dd       ZSeddd8	 	 	 dd       ZS ed      dddd	 	 	 dd       ZSdddZT eej2                  d      dd       ZU ed      dd       ZV ed      ddd       ZWed        ZXddZY edmdvg      ddddd       ZZy)    )annotations)partialN)overloadAnyLiteral)config)dtypes)lax)numpy)jitvmapjvp)linalg)	vectorize)check_arraylikepromote_dtypespromote_dtypes_inexactpromote_dtypes_complexpromote_args_inexact)qdwh)Array	ArrayLikez
Does not support the Scipy argument ``check_finite=True``,
because compiled JAX code cannot perform checks of array values at runtime.
z:
Does not support the Scipy argument ``overwrite_*=True``.lower)static_argnamesac                    t        t        j                  |             \  } t        j                  |r| nt        j
                  | j                        d      }|r|S t        j
                  |j                        S )NF)symmetrize_input)r   jnpasarray
lax_linalgcholeskyconjmT)r   r   ls      P/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/scipy/linalg.py	_choleskyr'   ,   sQ    ckk!n-"!u!#((144.5Q!'!$$'    FTc                    ~~t        | |      S )a  Compute the Cholesky decomposition of a matrix.

  JAX implementation of :func:`scipy.linalg.cholesky`.

  The Cholesky decomposition of a matrix `A` is:

  .. math::

     A = U^HU = LL^H

  where `U` is an upper-triangular matrix and `L` is a lower-triangular matrix.

  Args:
    a: input array, representing a (batched) positive-definite hermitian matrix.
      Must have shape ``(..., N, N)``.
    lower: if True, compute the lower Cholesky decomposition `L`. if False
      (default), compute the upper Cholesky decomposition `U`.
    overwrite_a: unused by JAX
    check_finite: unused by JAX

  Returns:
    array of shape ``(..., N, N)`` representing the cholesky decomposition
    of the input.

  See Also:
   - :func:`jax.numpy.linalg.cholesky`: NumPy-stype Cholesky API
   - :func:`jax.lax.linalg.cholesky`: XLA-style Cholesky API
   - :func:`jax.scipy.linalg.cho_factor`
   - :func:`jax.scipy.linalg.cho_solve`

  Examples:
    A small real Hermitian positive-definite matrix:

    >>> x = jnp.array([[2., 1.],
    ...                [1., 2.]])

    Upper Cholesky factorization:

    >>> jax.scipy.linalg.cholesky(x)
    Array([[1.4142135 , 0.70710677],
           [0.        , 1.2247449 ]], dtype=float32)

    Lower Cholesky factorization:

    >>> jax.scipy.linalg.cholesky(x, lower=True)
    Array([[1.4142135 , 0.        ],
           [0.70710677, 1.2247449 ]], dtype=float32)

    Reconstructing ``x`` from its factorization:

    >>> L = jax.scipy.linalg.cholesky(x, lower=True)
    >>> jnp.allclose(x, L @ L.T)
    Array(True, dtype=bool)
  )r'   r   r   overwrite_acheck_finites       r&   r"   r"   3   s    p <	1e	r(   c                $    ~~t        | |      |fS )a  Factorization for Cholesky-based linear solves

  JAX implementation of :func:`scipy.linalg.cho_factor`. This function returns
  a result suitable for use with :func:`jax.scipy.linalg.cho_solve`. For direct
  Cholesky decompositions, prefer :func:`jax.scipy.linalg.cholesky`.

  Args:
    a: input array, representing a (batched) positive-definite hermitian matrix.
      Must have shape ``(..., N, N)``.
    lower: if True, compute the lower triangular Cholesky decomposition (default: False).
    overwrite_a: unused by JAX
    check_finite: unused by JAX

  Returns:
    ``(c, lower)``: ``c`` is an array of shape ``(..., N, N)`` representing the lower or
    upper cholesky decomposition of the input; ``lower`` is a boolean specifying whether
    this is the lower or upper decomposition.

  See Also:
    - :func:`jax.scipy.linalg.cholesky`
    - :func:`jax.scipy.linalg.cho_solve`

  Examples:
    A small real Hermitian positive-definite matrix:

    >>> x = jnp.array([[2., 1.],
    ...                [1., 2.]])

    Compute the cholesky factorization via :func:`~jax.scipy.linalg.cho_factor`,
    and use it to solve a linear equation via :func:`~jax.scipy.linalg.cho_solve`.

    >>> b = jnp.array([3., 4.])
    >>> cfac = jax.scipy.linalg.cho_factor(x)
    >>> y = jax.scipy.linalg.cho_solve(cfac, b)
    >>> y
    Array([0.6666666, 1.6666666], dtype=float32)

    Check that the result is consistent:

    >>> jnp.allclose(x @ y, b)
    Array(True, dtype=bool)
  r   )r"   r*   s       r&   
cho_factorr.   o   s    X <
1E
"E	**r(   c                   t        t        j                  |       t        j                  |            \  } }t        j                  | |       t        j
                  | |d|| |       }t        j
                  | |d|||      }|S )NT)	left_sider   transpose_aconjugate_a)r   r   r    r!   _check_solve_shapestriangular_solve)cbr   s      r&   
_cho_solver7      sw    	AA	?$!Q  A&!!!Q$e27iYP!!!!Q$e.3H!	
(r(   c                *    ~~| \  }}t        |||      S )a:  Solve a linear system using a Cholesky factorization

  JAX implementation of :func:`scipy.linalg.cho_solve`. Uses the output
  of :func:`jax.scipy.linalg.cho_factor`.

  Args:
    c_and_lower: ``(c, lower)``, where ``c`` is an array of shape ``(..., N, N)``
      representing the lower or upper cholesky decomposition of the matrix, and
      ``lower`` is a boolean specifying whether this is the lower or upper decomposition.
    b: right-hand-side of linear system. Must have shape ``(..., N)``
    overwrite_a: unused by JAX
    check_finite: unused by JAX

  Returns:
    Array of shape ``(..., N)`` representing the solution of the linear system.

  See Also:
    - :func:`jax.scipy.linalg.cholesky`
    - :func:`jax.scipy.linalg.cho_factor`

  Examples:
    A small real Hermitian positive-definite matrix:

    >>> x = jnp.array([[2., 1.],
    ...                [1., 2.]])

    Compute the cholesky factorization via :func:`~jax.scipy.linalg.cho_factor`,
    and use it to solve a linear equation via :func:`~jax.scipy.linalg.cho_solve`.

    >>> b = jnp.array([3., 4.])
    >>> cfac = jax.scipy.linalg.cho_factor(x)
    >>> y = jax.scipy.linalg.cho_solve(cfac, b)
    >>> y
    Array([0.6666666, 1.6666666], dtype=float32)

    Check that the result is consistent:

    >>> jnp.allclose(x @ y, b)
    Array(True, dtype=bool)
  )r7   )c_and_lowerr6   overwrite_br,   r5   r   s         r&   	cho_solver;      s"    T <(!U	Aq%	  r(   c                    y N xfull_matrices
compute_uvs      r&   _svdrC      s    ilr(   c                    y r=   r>   r?   s      r&   rC   rC      s    UXr(   c                    y r=   r>   r?   s      r&   rC   rC      s    hkr(   rA   rB   c               r    t        t        j                  |             \  } t        j                  | ||      S )NrF   )r   r   r    r!   svd)r   rA   rB   s      r&   rC   rC      s)    ckk!n-"!	:	NNr(   gesddc                     y r=   r>   r   rA   rB   r+   r,   lapack_drivers         r&   rH   rH      s	     FIr(   c                     y r=   r>   rK   s         r&   rH   rH           14r(   )r+   r,   rL   c                    y r=   r>   rK   s         r&   rH   rH      rN   r(   c                     y r=   r>   rK   s         r&   rH   rH      s	     NQr(   c                $    ~~~t        | ||      S )a	  Compute the singular value decomposition.

  JAX implementation of :func:`scipy.linalg.svd`.

  The SVD of a matrix `A` is given by

  .. math::

     A = U\Sigma V^H

  - :math:`U` contains the left singular vectors and satisfies :math:`U^HU=I`
  - :math:`V` contains the right singular vectors and satisfies :math:`V^HV=I`
  - :math:`\Sigma` is a diagonal matrix of singular values.

  Args:
    a: input array, of shape ``(..., N, M)``
    full_matrices: if True (default) compute the full matrices; i.e. ``u`` and ``vh`` have
      shape ``(..., N, N)`` and ``(..., M, M)``. If False, then the shapes are
      ``(..., N, K)`` and ``(..., K, M)`` with ``K = min(N, M)``.
    compute_uv: if True (default), return the full SVD ``(u, s, vh)``. If False then return
      only the singular values ``s``.
    overwrite_a: unused by JAX
    check_finite: unused by JAX
    lapack_driver: unused by JAX. If you want to select a non-default SVD driver, please
      check :func:`jax.lax.linalg.svd` which provides such functionality.

  Returns:
    A tuple of arrays ``(u, s, vh)`` if ``compute_uv`` is True, otherwise the array ``s``.

    - ``u``: left singular vectors of shape ``(..., N, N)`` if ``full_matrices`` is True
      or ``(..., N, K)`` otherwise.
    - ``s``: singular values of shape ``(..., K)``
    - ``vh``: conjugate-transposed right singular vectors of shape ``(..., M, M)``
      if ``full_matrices`` is True or ``(..., K, M)`` otherwise.

    where ``K = min(N, M)``.

  See also:
    - :func:`jax.numpy.linalg.svd`: NumPy-style SVD API
    - :func:`jax.lax.linalg.svd`: XLA-style SVD API

  Examples:
    Consider the SVD of a small real-valued array:

    >>> x = jnp.array([[1., 2., 3.],
    ...                [6., 5., 4.]])
    >>> u, s, vt = jax.scipy.linalg.svd(x, full_matrices=False)
    >>> s  # doctest: +SKIP
    Array([9.361919 , 1.8315067], dtype=float32)

    The singular vectors are in the columns of ``u`` and ``v = vt.T``. These vectors are
    orthonormal, which can be demonstrated by comparing the matrix product with the
    identity matrix:

    >>> jnp.allclose(u.T @ u, jnp.eye(2), atol=1E-5)
    Array(True, dtype=bool)
    >>> v = vt.T
    >>> jnp.allclose(v.T @ v, jnp.eye(2), atol=1E-5)
    Array(True, dtype=bool)

    Given the SVD, ``x`` can be reconstructed via matrix multiplication:

    >>> x_reconstructed = u @ jnp.diag(s) @ vt
    >>> jnp.allclose(x_reconstructed, x)
    Array(True, dtype=bool)
  rF   )rC   rK   s         r&   rH   rH      s    J <	a}	DDr(   c                0    ~~t        j                  |       S )a  Compute the determinant of a matrix

  JAX implementation of :func:`scipy.linalg.det`.

  Args:
    a: input array, of shape ``(..., N, N)``
    overwrite_a: unused by JAX
    check_finite: unused by JAX

  Returns
    Determinant of shape ``a.shape[:-2]``

  See Also:
    :func:`jax.numpy.linalg.det`: NumPy-style determinant API

  Examples:
    Determinant of a small 2D array:

    >>> x = jnp.array([[1., 2.],
    ...                [3., 4.]])
    >>> jax.scipy.linalg.det(x)
    Array(-2., dtype=float32)

    Batch-wise determinant of multiple 2D arrays:

    >>> x = jnp.array([[[1., 2.],
    ...                 [3., 4.]],
    ...                [[8., 5.],
    ...                 [7., 9.]]])
    >>> jax.scipy.linalg.det(x)
    Array([-2., 37.], dtype=float32)
  )
jnp_linalgdetr   r+   r,   s      r&   rT   rT   C  s    B <		r(   c                     y r=   r>   r   r6   r   eigvals_onlyeigvalstypes         r&   _eighr[   h  s    .1r(   c                     y r=   r>   rW   s         r&   r[   r[   l  s    <?r(   c                     y r=   r>   rW   s         r&   r[   r[   p  s    DGr(   )r   rX   rY   rZ   c                    |t        d      |dk7  rt        d      |t        d      t        t        j                  |             \  } t	        j
                  | |      \  }}|r|S ||fS )Nz+Only the b=None case of eigh is implemented   z,Only the type=1 case of eigh is implemented.z2Only the eigvals=None case of eigh is implemented.r   )NotImplementedErrorr   r   r    r!   eigh)r   r6   r   rX   rY   rZ   vws           r&   r[   r[   t  sy     ]
K
LL	QY
L
MM
<> > ckk!n-"!	%	($!QHa4Kr(   r_   c
                     y r=   r>   
r   r6   r   rX   r+   r:   turborY   rZ   r,   s
             r&   ra   ra     s	     LOr(   )r+   r:   rf   rY   rZ   r,   c                    y r=   r>   re   s
             r&   ra   ra          >Ar(   c
                     y r=   r>   re   s
             r&   ra   ra     rh   r(   c
                     y r=   r>   re   s
             r&   ra   ra     s	     TWr(   c
                *    ~~~~	t        | |||||      S )ax  Compute eigenvalues and eigenvectors for a Hermitian matrix

  JAX implementation of :func:`scipy.linalg.eigh`.

  Only the standard eigenvalue problem is supported: ``a @ v = lambda * v``.
    The parameter `b` must be None; the generalized problem (``a @ v = lambda * b @ v``)
    is not implemented.

  Args:
    a: Hermitian input array of shape ``(..., N, N)``
    b: Must be None. The generalized eigenvalue problem is not supported.
    lower: if True (default) access only the lower portion of the input matrix.
      Otherwise access only the upper portion.
    eigvals_only: If True, compute only the eigenvalues. If False (default) compute
      both eigenvalues and eigenvectors.
    type: Not used. Only type=1 is supported.

    eigvals: Not used. Only eigvals=None is supported.
    overwrite_a: unused by JAX.
    overwrite_b: unused by JAX.
    turbo: unused by JAX.
    check_finite: unused by JAX.

  Returns:
    A tuple of arrays ``(eigvals, eigvecs)`` if ``eigvals_only`` is False, otherwise
    an array ``eigvals``.

    - ``eigvals``: array of shape ``(..., N)`` containing the eigenvalues.
    - ``eigvecs``: array of shape ``(..., N, N)`` containing the eigenvectors.

  Raise:
    NotImplementedError: If `b` is not None.

  See also:
    - :func:`jax.numpy.linalg.eigh`: NumPy-style eigh API.
    - :func:`jax.lax.linalg.eigh`: XLA-style eigh API.
    - :func:`jax.numpy.linalg.eig`: non-hermitian eigenvalue problem.
    - :func:`jax.scipy.linalg.eigh_tridiagonal`: tri-diagonal eigenvalue problem.

  Examples:
    Compute the standard eigenvalue decomposition of a simple 2x2 matrix:

    >>> a = jnp.array([[2., 1.],
    ...                [1., 2.]])
    >>> eigvals, eigvecs = jax.scipy.linalg.eigh(a)
    >>> eigvals
    Array([1., 3.], dtype=float32)
    >>> eigvecs
    Array([[-0.70710677,  0.70710677],
           [ 0.70710677,  0.70710677]], dtype=float32)

    Eigenvectors are orthonormal:

    >>> jnp.allclose(eigvecs.T @ eigvecs, jnp.eye(2), atol=1E-5)
    Array(True, dtype=bool)

    Solution satisfies the eigenvalue problem:

    >>> jnp.allclose(a @ eigvecs, eigvecs @ jnp.diag(eigvals))
    Array(True, dtype=bool)
  )r[   re   s
             r&   ra   ra     s#    B ;|	q!UL'4	88r(   outputc                    |dk(  r.| j                  t        j                  | j                              } t	        j
                  |       S )Ncomplex)astyper	   to_complex_dtypedtyper!   schurr   rm   s     r&   _schurru     s8    y	((12A			!	r(   c                @    |dvrt        d|d      t        | |      S )a  Compute the Schur decomposition

  Only implemented on CPU.

  JAX implementation of :func:`scipy.linalg.schur`.

  The Schur form `T` of a matrix `A` satisfies:

  .. math::

     A = Z T Z^H

  where `Z` is unitary, and `T` is upper-triangular for the complex-valued Schur
  decomposition (i.e. ``output="complex"``) and is quasi-upper-triangular for the
  real-valued Schur decomposition (i.e. ``output="real"``). In the quasi-triangular
  case, the diagonal may include 2x2 blocks associated with complex-valued
  eigenvalue pairs of `A`.

  Args:
    a: input array of shape ``(..., N, N)``
    output: Specify whether to compute the ``"real"`` (default) or ``"complex"``
      Schur decomposition.

  Returns:
    A tuple of arrays ``(T, Z)``

    - ``T`` is a shape ``(..., N, N)`` array containing the upper-triangular
      Schur form of the input.
    - ``Z`` is a shape ``(..., N, N)`` array containing the unitary Schur
      transformation matrix.

  See also:
    - :func:`jax.scipy.linalg.rsf2csf`: convert real Schur form to complex Schur form.
    - :func:`jax.lax.linalg.schur`: XLA-style API for Schur decomposition.

  Examples:
    A Schur decomposition of a 3x3 matrix:

    >>> a = jnp.array([[1., 2., 3.],
    ...                [1., 4., 2.],
    ...                [3., 2., 1.]])
    >>> T, Z = jax.scipy.linalg.schur(a)

    The Schur form ``T`` is quasi-upper-triangular in general, but is truly
    upper-triangular in this case because the input matrix is symmetric:

    >>> T  # doctest: +SKIP
    Array([[-2.0000005 ,  0.5066295 , -0.43360388],
           [ 0.        ,  1.5505103 ,  0.74519426],
           [ 0.        ,  0.        ,  6.449491  ]], dtype=float32)

    The transformation matrix ``Z`` is unitary:

    >>> jnp.allclose(Z.T @ Z, jnp.eye(3), atol=1E-5)
    Array(True, dtype=bool)

    The input can be reconstructed from the outputs:

    >>> jnp.allclose(Z @ T @ Z.T, a)
    Array(True, dtype=bool)
  )realro   z?Expected 'output' to be either 'real' or 'complex', got output=.)
ValueErrorru   rt   s     r&   rs   rs     s6    | &&
H	KM M	6	r(   c                0    ~~t        j                  |       S )a  Return the inverse of a square matrix

  JAX implementation of :func:`scipy.linalg.inv`.

  Args:
    a: array of shape ``(..., N, N)`` specifying square array(s) to be inverted.
    overwrite_a: unused in JAX
    check_finite: unused in JAX

  Returns:
    Array of shape ``(..., N, N)`` containing the inverse of the input.

  Notes:
    In most cases, explicitly computing the inverse of a matrix is ill-advised. For
    example, to compute ``x = inv(A) @ b``, it is more performant and numerically
    precise to use a direct solve, such as :func:`jax.scipy.linalg.solve`.

  See Also:
    - :func:`jax.numpy.linalg.inv`: NumPy-style API for matrix inverse
    - :func:`jax.scipy.linalg.solve`: direct linear solver

  Examples:
    Compute the inverse of a 3x3 matrix

    >>> a = jnp.array([[1., 2., 3.],
    ...                [2., 4., 2.],
    ...                [3., 2., 1.]])
    >>> a_inv = jax.scipy.linalg.inv(a)
    >>> a_inv  # doctest: +SKIP
    Array([[ 0.        , -0.25      ,  0.5       ],
           [-0.25      ,  0.5       , -0.25000003],
           [ 0.5       , -0.25      ,  0.        ]], dtype=float32)

    Check that multiplying with the inverse gives the identity:

    >>> jnp.allclose(a @ a_inv, jnp.eye(3), atol=1E-5)
    Array(True, dtype=bool)

    Multiply the inverse by a vector ``b``, to find a solution to ``a @ x = b``

    >>> b = jnp.array([1., 4., 2.])
    >>> a_inv @ b
    Array([ 0.  ,  1.25, -0.5 ], dtype=float32)

    Note, however, that explicitly computing the inverse in such a case can lead
    to poor performance and loss of precision as the size of the problem grows.
    Instead, you should use a direct solver like :func:`jax.scipy.linalg.solve`:

    >>> jax.scipy.linalg.solve(a, b)
     Array([ 0.  ,  1.25, -0.5 ], dtype=float32)
  )rS   invrU   s      r&   r{   r{   -  s    h <		r(   )r+   r,   c                    ~~t        t        j                  |             \  } t        j                  |       \  }}}||fS )a  Factorization for LU-based linear solves

  JAX implementation of :func:`scipy.linalg.lu_factor`.

  This function returns a result suitable for use with :func:`jax.scipy.linalg.lu_solve`.
  For direct LU decompositions, prefer :func:`jax.scipy.linalg.lu`.

  Args:
    a: input array of shape ``(..., M, N)``.
    overwrite_a: unused by JAX
    check_finite: unused by JAX

  Returns:
    A tuple ``(lu, piv)``

    - ``lu`` is an array of shape ``(..., M, N)``, containing ``L`` in its
      lower triangle and ``U`` in its upper.
    - ``piv`` is an array of shape ``(..., K)`` with ``K = min(M, N)``,
      which encodes the pivots.

  See Also:
    - :func:`jax.scipy.linalg.lu`
    - :func:`jax.scipy.linalg.lu_solve`

  Examples:
    Solving a small linear system via LU factorization:

    >>> a = jnp.array([[2., 1.],
    ...                [1., 2.]])

    Compute the lu factorization via :func:`~jax.scipy.linalg.lu_factor`,
    and use it to solve a linear equation via :func:`~jax.scipy.linalg.lu_solve`.

    >>> b = jnp.array([3., 4.])
    >>> lufac = jax.scipy.linalg.lu_factor(a)
    >>> y = jax.scipy.linalg.lu_solve(lufac, b)
    >>> y
    Array([0.6666666, 1.6666667], dtype=float32)

    Check that the result is consistent:

    >>> jnp.allclose(a @ y, b)
    Array(True, dtype=bool)
  )r   r   r    r!   lu)r   r+   r,   r}   pivots_s         r&   	lu_factorr   e  s<    \ <ckk!n-"!--"-"fa	Vr(   )transr:   r,   c                    ~~| \  }}|j                   dd \  }}t        j                  ||      }	t        j                  ||	||      S )a  Solve a linear system using an LU factorization

  JAX implementation of :func:`scipy.linalg.lu_solve`. Uses the output
  of :func:`jax.scipy.linalg.lu_factor`.

  Args:
    lu_and_piv: ``(lu, piv)``, output of :func:`~jax.scipy.linalg.lu_factor`.
      ``lu`` is an array of shape ``(..., M, N)``, containing ``L`` in its lower
      triangle and ``U`` in its upper. ``piv`` is an array of shape ``(..., K)``,
      with ``K = min(M, N)``, which encodes the pivots.
    b: right-hand-side of linear system. Must have shape ``(..., M)``
    trans: type of system to solve. Options are:

      - ``0``: :math:`A x = b`
      - ``1``: :math:`A^Tx = b`
      - ``2``: :math:`A^Hx = b`

    overwrite_b: unused by JAX
    check_finite: unused by JAX

  Returns:
    Array of shape ``(..., N)`` representing the solution of the linear system.

  See Also:
    - :func:`jax.scipy.linalg.lu`
    - :func:`jax.scipy.linalg.lu_factor`

  Examples:
    Solving a small linear system via LU factorization:

    >>> a = jnp.array([[2., 1.],
    ...                [1., 2.]])

    Compute the lu factorization via :func:`~jax.scipy.linalg.lu_factor`,
    and use it to solve a linear equation via :func:`~jax.scipy.linalg.lu_solve`.

    >>> b = jnp.array([3., 4.])
    >>> lufac = jax.scipy.linalg.lu_factor(a)
    >>> y = jax.scipy.linalg.lu_solve(lufac, b)
    >>> y
    Array([0.6666666, 1.6666667], dtype=float32)

    Check that the result is consistent:

    >>> jnp.allclose(a @ y, b)
    Array(True, dtype=bool)
  N)shaper!   lu_pivots_to_permutationlu_solve)

lu_and_pivr6   r   r:   r,   r}   r~   mr   perms
             r&   r   r     sO    d <*"f	"#$!Q		,	,VQ	7$			Rq%	00r(   c                     y r=   r>   r   	permute_ls     r&   _lur     s    HKr(   c                     y r=   r>   r   s     r&   r   r     s    PSr(   c                     y r=   r>   r   s     r&   r   r     s    \_r(   r_   )static_argnumsc           	        t        t        j                  |             \  } t        j                  |       \  }}}t        j                  |       }t        j                  |       \  }}t        j                  t        j                  |d d d f   t        j                  ||j                        d d d f   k(  |            }t        ||      }	t        j                  |d      d d d |	f   t        j                  ||	|      z   }
t        j                  |      d |	d d f   }|r2t        j                   ||
t
        j"                  j$                        |fS ||
|fS )Nrr   	precision)r   r   r    r!   r}   r
   rr   npr   rw   arrayarangemintrileyetriumatmul	PrecisionHIGHEST)r   r   r}   r   permutationrr   r   npkr%   us               r&   r   r     s   ckk!n-"!!}}Q'"a
))A,%	!$!Q	hhsyyT1W-A[EVEV1WXY[_X_1``hmno!	!Qi!	hhr2q"1"u1E ::!	hhrl2A2q5!::acmm&;&;<a??a7Nr(   c                     y r=   r>   r   r   r+   r,   s       r&   r}   r}     s    ADr(   c                     y r=   r>   r   s       r&   r}   r}     s    :=r(   c                     y r=   r>   r   s       r&   r}   r}     s    WZr(   )r   r+   r,   c                    ~~t        | |      S )ac  Compute the LU decomposition

  JAX implementation of :func:`scipy.linalg.lu`.

  The LU decomposition of a matrix `A` is:

  .. math::

     A = P L U

  where `P` is a permutation matrix, `L` is lower-triangular and `U` is upper-triangular.

  Args:
    a: array of shape ``(..., M, N)`` to decompose.
    permute_l: if True, then permute ``L`` and return ``(P @ L, U)`` (default: False)
    overwrite_a: not used by JAX
    check_finite: not used by JAX

  Returns:
    A tuple of arrays ``(P @ L, U)`` if ``permute_l`` is True, else ``(P, L, U)``:

    - ``P`` is a permutation matrix of shape ``(..., M, M)``
    - ``L`` is a lower-triangular matrix of shape ``(... M, K)``
    - ``U`` is an upper-triangular matrix of shape ``(..., K, N)``

    with ``K = min(M, N)``

  See also:
    - :func:`jax.numpy.linalg.lu`: NumPy-style API for LU decomposition.
    - :func:`jax.lax.linalg.lu`: XLA-style API for LU decomposition.
    - :func:`jax.scipy.linalg.lu_solve`: LU-based linear solver.

  Examples:
    An LU decomposition of a 3x3 matrix:

    >>> a = jnp.array([[1., 2., 3.],
    ...                [5., 4., 2.],
    ...                [3., 2., 1.]])
    >>> P, L, U = jax.scipy.linalg.lu(a)

    ``P`` is a permutation matrix: i.e. each row and column has a single ``1``:

    >>> P
    Array([[0., 1., 0.],
           [1., 0., 0.],
           [0., 0., 1.]], dtype=float32)

    ``L`` and ``U`` are lower-triangular and upper-triangular matrices:

    >>> with jnp.printoptions(precision=3):
    ...   print(L)
    ...   print(U)
    [[ 1.     0.     0.   ]
     [ 0.2    1.     0.   ]
     [ 0.6   -0.333  1.   ]]
    [[5.    4.    2.   ]
     [0.    1.2   2.6  ]
     [0.    0.    0.667]]

    The original matrix can be reconstructed by multiplying the three together:

    >>> a_reconstructed = P @ L @ U
    >>> jnp.allclose(a, a_reconstructed)
    Array(True, dtype=bool)
  )r   r   s       r&   r}   r}     s    H <	Q		r(   c                     y r=   r>   r   modepivotings      r&   _qrr   >  s    r(   c                     y r=   r>   r   s      r&   r   r   B      !$r(   c                     y r=   r>   r   s      r&   r   r   F  r   r(   c                     y r=   r>   r   s      r&   r   r   J  s    (+r(   c                     y r=   r>   r   s      r&   r   r   N  s    03r(   c                     y r=   r>   r   s      r&   r   r   R  s    >Ar(   c                     y r=   r>   r   s      r&   r   r   V      MPr(   )r   r   c                    |dv rd}n|dk(  rd}nt        d| d      t        t        j                  |             \  } t	        j
                  | ||      ^}}}|dk(  r|r||d	   fS |fS |r|||d	   fS ||fS )
N)fullrTeconomicFz#Unsupported QR decomposition mode '')r   rA   r   r   )ry   r   r   r    r!   qr)r   r   r   rA   qr   r   s          r&   r   r   [  s     
]MzM
:4&B
CCckk!n-"!]]1x}M(!Q	S[!Wn4Ka1:	
A+r(   )r   r,   c                    y r=   r>   r   r+   lworkr   r   r,   s         r&   r   r   o  s     ;>r(   c                    y r=   r>   r   s         r&   r   r   t  s	     BEr(   c                    y r=   r>   r   s         r&   r   r   y  rh   r(   c                    y r=   r>   r   s         r&   r   r     s     r(   c                    y r=   r>   r   s         r&   r   r     s     !$r(   c                    y r=   r>   r   s         r&   r   r     s     03r(   c                     y r=   r>   r   s         r&   r   r     s	     MPr(   c                "    ~~~t        | ||      S )a
  Compute the QR decomposition of an array

  JAX implementation of :func:`scipy.linalg.qr`.

  The QR decomposition of a matrix `A` is given by

  .. math::

     A = QR

  Where `Q` is a unitary matrix (i.e. :math:`Q^HQ=I`) and `R` is an upper-triangular
  matrix.

  Args:
    a: array of shape (..., M, N)
    mode: Computational mode. Supported values are:

      - ``"full"`` (default): return `Q` of shape ``(M, M)`` and `R` of shape ``(M, N)``.
      - ``"r"``: return only `R`
      - ``"economic"``: return `Q` of shape ``(M, K)`` and `R` of shape ``(K, N)``,
        where K = min(M, N).

    pivoting: Allows the QR decomposition to be rank-revealing. If ``True``, compute
      the column-pivoted decomposition ``A[:, P] = Q @ R``, where ``P`` is chosen such
      that the diagonal of ``R`` is non-increasing.
    overwrite_a: unused in JAX
    lwork: unused in JAX
    check_finite: unused in JAX

  Returns:
    A tuple ``(Q, R)`` or ``(Q, R, P)``, if ``mode`` is not ``"r"`` and ``pivoting`` is
    respectively ``False`` or ``True``, otherwise an array ``R`` or tuple ``(R, P)`` if
    mode is ``"r"``, and ``pivoting`` is respectively ``False`` or ``True``, where:

    - ``Q`` is an orthogonal matrix of shape ``(..., M, M)`` (if ``mode`` is ``"full"``)
      or ``(..., M, K)`` (if ``mode`` is ``"economic"``),
    - ``R`` is an upper-triangular matrix of shape ``(..., M, N)`` (if ``mode`` is
      ``"r"`` or ``"full"``) or ``(..., K, N)`` (if ``mode`` is ``"economic"``),
    - ``P`` is an index vector of shape ``(..., N)``.

    with ``K = min(M, N)``.

  Notes:
    - At present, pivoting is only implemented on the CPU and GPU backends. For further
      details about the GPU implementation, see the documentation for
      :func:`jax.lax.linalg.qr`.

  See also:
    - :func:`jax.numpy.linalg.qr`: NumPy-style QR decomposition API
    - :func:`jax.lax.linalg.qr`: XLA-style QR decomposition API

  Examples:
    Compute the QR decomposition of a matrix:

    >>> a = jnp.array([[1., 2., 3., 4.],
    ...                [5., 4., 2., 1.],
    ...                [6., 3., 1., 5.]])
    >>> Q, R = jax.scipy.linalg.qr(a)
    >>> Q  # doctest: +SKIP
    Array([[-0.12700021, -0.7581426 , -0.6396022 ],
           [-0.63500065, -0.43322435,  0.63960224],
           [-0.7620008 ,  0.48737738, -0.42640156]], dtype=float32)
    >>> R  # doctest: +SKIP
    Array([[-7.8740077, -5.080005 , -2.4130025, -4.953006 ],
           [ 0.       , -1.7870499, -2.6534991, -1.028908 ],
           [ 0.       ,  0.       , -1.0660033, -4.050814 ]], dtype=float32)

    Check that ``Q`` is orthonormal:

    >>> jnp.allclose(Q.T @ Q, jnp.eye(3), atol=1E-5)
    Array(True, dtype=bool)

    Reconstruct the input:

    >>> jnp.allclose(Q @ R, a)
    Array(True, dtype=bool)
  )r   r   s         r&   r   r     s    ` 5,	Qh	r(   )assume_ar   c           	     "    |dk7  rt        j                   |      S t        t        j                         t        j                  |            \   }t        j                   |       t        t        j                         |      t        t        j                   fdfdd      } j                  |j                  dz   k(  r ||      S  t        ||j                  dz
  t         j                  |j                        dz
        |      S )Nposr   c                0    t        j                  |       S r=   )r!   _broadcasted_matvec)r@   r   s    r&   <lambda>z_solve.<locals>.<lambda>  s    
..q!4 r(   c                    t        |      S r=   )r;   )r   r@   factorss     r&   r   z_solve.<locals>.<lambda>  s    7A. r(   T)solve	symmetricr_   )rS   r   r   r   r    r!   r3   r.   r
   stop_gradientr   custom_linear_solvendimr   max)r   r6   r   r   custom_solver   s   `    @r&   _solver     s    Aq!!	AA	?$!Q  A& s((+59'	4.	,
 VVqvvz? C4affqj#affaff*=*AB1EEr(   c                X    ~~~~g d}||vrt        d| d|      t        | |||      S )aI  Solve a linear system of equations.

  JAX implementation of :func:`scipy.linalg.solve`.

  This solves a (batched) linear system of equations ``a @ x = b`` for ``x``
  given ``a`` and ``b``.

  If ``a`` is singular, this will return ``nan`` or ``inf`` values.

  Args:
    a: array of shape ``(..., N, N)``.
    b: array of shape ``(..., N)`` or ``(..., N, M)``
    lower: Referenced only if ``assume_a != 'gen'``. If True, only use the lower
      triangle of the input, If False (default), only use the upper triangle.
    assume_a: specify what properties of ``a`` can be assumed. Options are:

      - ``"gen"``: generic matrix (default)
      - ``"sym"``: symmetric matrix
      - ``"her"``: hermitian matrix
      - ``"pos"``: positive-definite matrix

    overwrite_a: unused by JAX
    overwrite_b: unused by JAX
    debug: unused by JAX
    check_finite: unused by JAX

  Returns:
    An array of the same shape as ``b`` containing the solution to the linear
    system if ``a`` is non-singular.
    If ``a`` is singular, the result contains ``nan`` or ``inf`` values.

  See also:
    - :func:`jax.scipy.linalg.lu_solve`: Solve via LU factorization.
    - :func:`jax.scipy.linalg.cho_solve`: Solve via Cholesky factorization.
    - :func:`jax.scipy.linalg.solve_triangular`: Solve a triangular system.
    - :func:`jax.numpy.linalg.solve`: NumPy-style API for solving linear systems.
    - :func:`jax.lax.custom_linear_solve`: matrix-free linear solver.

  Examples:
    A simple 3x3 linear system:

    >>> A = jnp.array([[1., 2., 3.],
    ...                [2., 4., 2.],
    ...                [3., 2., 1.]])
    >>> b = jnp.array([14., 16., 10.])
    >>> x = jax.scipy.linalg.solve(A, b)
    >>> x
    Array([1., 2., 3.], dtype=float32)

    Confirming that the result solves the system:

    >>> jnp.allclose(A @ x, b)
    Array(True, dtype=bool)
  )gensymherr   zExpected assume_a to be one of ; got )ry   r   )	r   r6   r   r+   r:   debugr,   r   valid_assume_as	            r&   r   r      sF    r ;|/.^#
6~6FfXLY
ZZ	1h	&&r(   )r   r   unit_diagonalc           	        |dk(  s|dk(  rd\  }}n.|dk(  s|dk(  rd\  }}n|dk(  s|dk(  rd	\  }}nt        d
|       t        t        j                  |       t        j                  |            \  } }t	        j
                  |       t	        j
                  |      dz   k(  }|r|d   }t        j                  | |d||||      }|r|d   S |S )Nr   N)FFr_   T)TF   C)TTzInvalid 'trans' value ).NT)r0   r   r1   r2   r   ).r   )ry   r   r   r    r   r   r!   r4   )	r   r6   r   r   r   r1   r2   b_is_vectorouts	            r&   _solve_triangularr   ?  s     aZ5C<+KzUc\*KzUc\)K
-eW5
66	AA	?$!Q 
bggaj1n,+	)A##AqD0;0;2?	A# v;Jr(   c                &    ~~~t        | ||||      S )aE  Solve a triangular linear system of equations

  JAX implementation of :func:`scipy.linalg.solve_triangular`.

  This solves a (batched) linear system of equations ``a @ x = b`` for ``x``
  given a triangular matrix ``a`` and a vector or matrix ``b``.

  Args:
    a: array of shape ``(..., N, N)``. Only part of the array will be accessed,
      depending on the ``lower`` and ``unit_diagonal`` arguments.
    b: array of shape ``(..., N)`` or ``(..., N, M)``
    lower: If True, only use the lower triangle of the input, If False (default),
      only use the upper triangle.
    unit_diagonal: If True, ignore diagonal elements of ``a`` and assume they are
      ``1`` (default: False).
    trans: specify what properties of ``a`` can be assumed. Options are:

      - ``0`` or ``'N'``: solve :math:`Ax=b`
      - ``1`` or ``'T'``: solve :math:`A^Tx=b`
      - ``2`` or ``'C'``: solve :math:`A^Hx=b`

    overwrite_b: unused by JAX
    debug: unused by JAX
    check_finite: unused by JAX

  Returns:
    An array of the same shape as ``b`` containing the solution to the linear system.

  See also:
    :func:`jax.scipy.linalg.solve`: Solve a general linear system.

  Examples:
    A simple 3x3 triangular linear system:

    >>> A = jnp.array([[1., 2., 3.],
    ...                [0., 3., 2.],
    ...                [0., 0., 5.]])
    >>> b = jnp.array([10., 8., 5.])
    >>> x = jax.scipy.linalg.solve_triangular(A, b)
    >>> x
    Array([3., 2., 1.], dtype=float32)

    Confirming that the result solves the system:

    >>> jnp.allclose(A @ x, b)
    Array(True, dtype=bool)

    Computing the transposed problem:

    >>> x = jax.scipy.linalg.solve_triangular(A, b, trans='T')
    >>> x
    Array([10. , -4. , -3.4], dtype=float32)

    Confirming that the result solves the system:

    >>> jnp.allclose(A.T @ x, b)
    Array(True, dtype=bool)
  )r   )r   r6   r   r   r   r:   r   r,   s           r&   solve_triangularr   [  s    z 5,	1a}	==r(   upper_triangularmax_squarings   c                  t        |       \  } | j                  dk  s| j                  d   | j                  d   k7  rt        d| j                  d      | j                  dkD  r- t	        j
                  t        t              d      |       S t        t        j                  |             \  }}d	 }fd
}t        j                  kD  ||| ||f      }|S )a)  Compute the matrix exponential

  JAX implementation of :func:`scipy.linalg.expm`.

  Args:
    A: array of shape ``(..., N, N)``
    upper_triangular: if True, then assume that ``A`` is upper-triangular. Default=False.
    max_squarings: The number of squarings in the scaling-and-squaring approximation method
     (default: 16).

  Returns:
    An array of shape ``(..., N, N)`` containing the matrix exponent of ``A``.

  Notes:
    This uses the scaling-and-squaring approximation method, with computational complexity
    controlled by the optional ``max_squarings`` argument. Theoretically, the number of
    required squarings is ``max(0, ceil(log2(norm(A))) - c)`` where ``norm(A)`` is the L1
    norm and ``c=2.42`` for float64/complex128, or ``c=1.97`` for float32/complex64.

  See Also:
    :func:`jax.scipy.linalg.expm_frechet`

  Examples:

    ``expm`` is the matrix exponential, and has similar properties to the more
    familiar scalar exponential. For scalars ``a`` and ``b``, :math:`e^{a + b}
    = e^a e^b`. However, for matrices, this property only holds when ``A`` and
    ``B`` commute (``AB = BA``). In this case, ``expm(A+B) = expm(A) @ expm(B)``

    >>> A = jnp.array([[2, 0],
    ...                [0, 1]])
    >>> B = jnp.array([[3, 0],
    ...                [0, 4]])
    >>> jnp.allclose(jax.scipy.linalg.expm(A+B),
    ...              jax.scipy.linalg.expm(A) @ jax.scipy.linalg.expm(B),
    ...              rtol=0.0001)
    Array(True, dtype=bool)

    If a matrix ``X`` is invertible, then
    ``expm(X @ A @ inv(X)) = X @ expm(A) @ inv(X)``

    >>> X = jnp.array([[3, 1],
    ...                [2, 5]])
    >>> X_inv = jax.scipy.linalg.inv(X)
    >>> jnp.allclose(jax.scipy.linalg.expm(X @ A @ X_inv),
    ...              X @ jax.scipy.linalg.expm(A) @ X_inv)
    Array(True, dtype=bool)
  r   r   r   z8Expected A to be a (batched) square matrix, got A.shape=rx   r   z(n,n)->(n,n)	signaturec                R    | ^}}t        j                  |t        j                        S r=   )r   	full_liker   nan)argsAr   s      r&   _nanzexpm.<locals>._nan  s     EA==BFF##r(   c                H    | \  }}}t        ||      }t        |      }|S r=   )
_solve_P_Q	_squaring)r   r   PQRr   n_squaringsr   s        r&   _computezexpm.<locals>._compute  s0    GAq!1a)*A![-0AHr(   )r   r   r   ry   jnp_vectorizer   r   expm	_calc_P_Qr   r    r
   cond)	r   r   r   r   r   r   r   r   r   s	    ``     @r&   r  r    s    d a "!VVaZ1772;!''"+-
PzQRS
TTVVaZ =""d%5]S  !# #  A/!Q$ 
hh{]*D(Q1IF!	
(r(   c           	        | j                   dk7  s| j                  d   | j                  d   k7  rt        d      t        j                  | d      }| j
                  dk(  s| j
                  dk(  rd}t        j                  dt        j                  t        j                  ||z                    }| d|j                  | j
                        z  z  } t        j                  g d|j
                  	      }t        j                  ||      }t        j                  |t        t         t"        t$        t&        g|       \  }}n| j
                  d
k(  s| j
                  dk(  rd}t        j                  dt        j                  t        j                  ||z                    }| d|j                  | j
                        z  z  } t        j                  ddg|j
                  	      }t        j                  ||      }t        j                  |t        t         t"        g|       \  }}nt)        d| j
                   d      ||z   }| |z   }	||	|fS )Nr   r   r_   z expected A to be a square matrixfloat64
complex128gC|@)g ,?g|zی@?gQi?gd @r   float32	complex64gj%eg@g#"ՀA?gNj?zA.dtype=z is not supported.)r   r   ry   rS   normrr   r   maximumfloorlog2rp   r   digitizer
   switch_pade3_pade5_pade7_pade9_pade13	TypeError)
r   A_L1maxnormr   condsidxUVr   r   s
             r&   r  r    s   VVq[AGGAJ!''!*,
7
88	1	$ WW	QWW47Q		#((4'>*B CD;1""177+++199 F JJ(5 
dE	"3
**S66667CQ
G41aww)qww+5G++a388D7N+C!DEK	A##AGG,,,AII-/EF JJ(E
,,tU
#C::cFFF3Q7DAq
hqwwi'9:
;;!e!b1f!	
A{	r(   c                J    |rt        ||       S t        j                  ||       S r=   )r   rS   r   )r   r   r   s      r&   r   r     s%    Aq!!Aq!!r(   c                b    t        j                  | |t        j                  j                        S )Nr   )r   dotr
   r   r   )r   Bs     r&   _precise_dotr    s    	A!6!6	77r(   r   c                    d d fd}t        j                  || t        j                  |j                              \  }}|S )Nc                    t        | |       S r=   )r  r@   s    r&   _squaring_precisez$_squaring.<locals>._squaring_precise  s    1r(   c                    | S r=   r>   r"  s    r&   	_identityz_squaring.<locals>._identity  s    Hr(   c                >    t        j                  |k  |       d fS r=   )r
   r  )r5   ir%  r#  r   s     r&   _scan_fz_squaring.<locals>._scan_f  s"    88AO%6	1EtKKr(   r   )r
   scanr   r   rr   )r   r   r   r(  resr   r%  r#  s    `    @@r&   r   r     s?    L88GQ

=@Q@Q RS&#q	*r(   c                    d}| j                   \  }}t        j                  ||| j                        }t	        | |       }t	        | |d   |z  |d   |z  z         }|d   |z  |d   |z  z   }||fS )N)g      ^@g      N@g      (@      ?r      r_   r   r   r   r   r   rr   r  )r   r6   Mr   identA2r  r  s           r&   r  r    sz    !	
$!Q
''!Qagg
&%Aq"1qtBw1e+-!qT"WqtEz!!	
A+r(   c                   d}| j                   \  }}t        j                  ||| j                        }t	        | |       }t	        ||      }t	        | |d   |z  |d   |z  z   |d   |z  z         }|d   |z  |d   |z  z   |d   |z  z   }||fS )	N)g     @g     @g     @@g     @z@g      >@r,  r      r-  r_      r   r   r.  )	r   r6   r/  r   r0  r1  A4r  r  s	            r&   r  r  '  s    ,!	
$!Q
''!Qagg
&%Aq"B"1ad2g!R'!A$u*45!qT"WqtBw1e+!	
A+r(   c                X   d}| j                   \  }}t        j                  ||| j                        }t	        | |       }t	        ||      }t	        ||      }t	        | |d   |z  |d   |z  z   |d   |z  z   |d   |z  z         }|d   |z  |d   |z  z   |d	   |z  z   |d
   |z  z   }	||	fS )N)g    ~pAg    ~`Ag    @t>Ag    @Ag     @g     @g      L@r,  r      r3  r-  r_      r4  r   r   r.  
r   r6   r/  r   r0  r1  r5  A6r  r  s
             r&   r  r  1  s    F!	
$!Q
''!Qagg
&%Aq"B"B"1ad2g!R'!A$r'1AaDJ>?!d2g!R!A$r'!AaDJ.!	
1*r(   c                   d}| j                   \  }}t        j                  ||| j                        }t	        | |       }t	        ||      }t	        ||      }t	        ||      }t	        | |d   |z  |d   |z  z   |d   |z  z   |d   |z  z   |d   |z  z         }	|d   |z  |d	   |z  z   |d
   |z  z   |d   |z  z   |d   |z  z   }
|	|
fS )N)
g   ynBg   yn Bg    Ag   @
Ag    2|Ag    ~@Ag     @g     @g     V@r,  r   	   r7  r3  r-  r_      r8  r4  r   r   r.  )r   r6   r/  r   r0  r1  r5  r:  A8r  r  s              r&   r  r  <  s    *!	
$!Q
''!Qagg
&%Aq"B"B"B"1ad2g!R'!A$r'1AaDG;ad5jHI!d2g!R!A$r'!AaDG+ad5j8!	
1*r(   c           	        d}| j                   \  }}t        j                  ||| j                        }t	        | |       }t	        ||      }t	        ||      }t	        | t	        ||d   |z  |d   |z  z   |d   |z  z         |d   |z  z   |d   |z  z   |d   |z  z   |d	   |z  z         }t	        ||d
   |z  |d   |z  z   |d   |z  z         |d   |z  z   |d   |z  z   |d   |z  z   |d   |z  z   }	||	fS )N)g D`lCg D`\Cg `=Hb;Cg 	eCg JXBg  "5Bg  /cBg   \L8Bg   pķAg    syAg    S-Ag     @g     f@r,  r         r<  r7  r3  r-  r_      
   r=  r8  r4  r   r   r.  r9  s
             r&   r  r  I  s<   H! 
$!Q
''!Qagg
&%Aq"B"B"1l2quRx!B%(':QqT"W'DE!RORSTURVWYRYY\]^_\`ac\ccfghifjkpfppq!2quRx!B%(*QqT"W45!R?!A$r'IAaDQSGSVWXYVZ[`V``!	
1*r(   )methodcompute_expmrD  c                    y r=   r>   r   ErD  rE  s       r&   expm_frechetrI  W  r   r(   )rD  c                    y r=   r>   rG  s       r&   rI  rI  [  s    9<r(   c                    y r=   r>   rG  s       r&   rI  rI  _  s    LOr(   c               D   ~t        j                  |       }t        j                  |      }|j                  dk  s|j                  d   |j                  d   k7  rt	        d|j                         |j                  dk  s|j                  d   |j                  d   k7  rt	        d|j                         |j                  |j                  k7  r%t	        d|j                   d|j                         t        t        d	d
      }t        ||f|f      \  }}|r||fS |S )ai  Compute the Frechet derivative of the matrix exponential.

  JAX implementation of :func:`scipy.linalg.expm_frechet`

  Args:
    A: array of shape ``(..., N, N)``
    E: array of shape ``(..., N, N)``; specifies the direction of the derivative.
    compute_expm: if True (default) then compute and return ``expm(A)``.
    method: ignored by JAX

  Returns:
    A tuple ``(expm_A, expm_frechet_AE)`` if ``compute_expm`` is True, else
    the array ``expm_frechet_AE``. Both returned arrays have shape ``(..., N, N)``.

  See also:
    :func:`jax.scipy.linalg.expm`

  Examples:
    We can use this API to compute the matrix exponential of ``A``, as well as its
    derivative in the direction ``E``:

    >>> key1, key2 = jax.random.split(jax.random.key(3372))
    >>> A = jax.random.normal(key1, (3, 3))
    >>> E = jax.random.normal(key2, (3, 3))
    >>> expmA, expm_frechet_AE = jax.scipy.linalg.expm_frechet(A, E)

    This can be equivalently computed using JAX's automatic differentiation methods;
    here we'll compute the derivative of :func:`~jax.scipy.linalg.expm` in the
    direction of ``E`` using :func:`jax.jvp`, and find the same results:

    >>> expmA2, expm_frechet_AE2 = jax.jvp(jax.scipy.linalg.expm, (A,), (E,))
    >>> jnp.allclose(expmA, expmA2)
    Array(True, dtype=bool)
    >>> jnp.allclose(expm_frechet_AE, expm_frechet_AE2)
    Array(True, dtype=bool)
  r   r   r_   z8expected A to be a (batched) square matrix, got A.shape=r   z8expected E to be a (batched) square matrix, got E.shape=z3expected A and E to be the same shape, got A.shape=z	 E.shape=Fr   r   )r   r    r   r   ry   r   r  r   )	r   rH  rD  rE  A_arrE_arr	bound_funexpm_Aexpm_frechet_AEs	            r&   rI  rI  d  s   N 
++a.%
++a.%
ZZ!^u{{2%++a.8
OPUP[P[}]
^^
ZZ!^u{{2%++b/9
OPUP[P[}]
^^
[[EKK
   %}Iekk]D E EdU"E)	E8eX>&/?""r(   c            	        t        |       dk(  rt        j                  d      f} t        t	        |        } t        |       D cg c]   \  }}t        j                  |      dkD  s|" }}}|r$t        dj                  | |d      |d               | D cg c]  }t        j                  |       }}t        j                  |d         }t        d |D              }g }d}|D ]X  }	|	j                  d   }
d|||
z
  |z
  dff}|j                  t        j                   |	|j#                  d      |             ||
z  }Z t        j$                  |d      S c c}}w c c}w )	a  Create a block diagonal matrix from input arrays.

  JAX implementation of :func:`scipy.linalg.block_diag`.

  Args:
    *arrs: arrays of at most two dimensions

  Returns:
    2D block-diagonal array constructed by placing the input arrays
    along the diagonal.

  Examples:
    >>> A = jnp.ones((1, 1))
    >>> B = jnp.ones((2, 2))
    >>> C = jnp.ones((3, 3))
    >>> jax.scipy.linalg.block_diag(A, B, C)
    Array([[1., 0., 0., 0., 0., 0.],
           [0., 1., 1., 0., 0., 0.],
           [0., 1., 1., 0., 0., 0.],
           [0., 0., 0., 1., 1., 1.],
           [0., 0., 0., 1., 1., 1.],
           [0., 0., 0., 1., 1., 1.]], dtype=float32)
  r   )r_   r   r   z_Arguments to jax.scipy.linalg.block_diag must have at most 2 dimensions, got {} at argument {}.c              3  :   K   | ]  }|j                   d      yw)r_   Nr   ).0r   s     r&   	<genexpr>zblock_diag.<locals>.<genexpr>  s     6!1771:6s   r_   )r   r   r   axis)lenr   zerostupler   	enumerater   r   ry   format
atleast_2dr
   rr   sumr   appendpadrZ   concatenate)arrsr'  r   
bad_shapesconverted_arrsrr   
total_colspadded_arrscurrent_colarrcolspadding_configs               r&   
block_diagrl    sW   2 	Y!^IIfD	~t$	%$'o@daa@*@
 AfT*Q-0*Q-@B B 044!CNN1%4.4
))N1%
&%6~66*++ c99Q<D+zD/@;/NPQ!RSNswwsEJJqM>BC4K	
 
1	--! A
 5s    E%EE)rX   selectselect_range)rX   rm  rn  tolro  c               

   ! |st        d      d t        j                  |       t        j                  |      }t        j                  t        j
                  t        j                  t        j                  f}j                  |j                  k7  r%t        dj                   d|j                         j                  |vs|j                  |vr%t        dj                   d|j                         j                  d   }|dk  rt        j                        S t        j                  j                  t        j                        rVt        j                        t        j                  |t        j                  |      z        t        j                         }	n*t        j"                  |      }	t        j$                  |      t        j&                  |	dd |	dd	 |	dd z   |	d	d gd
      }
t        j(                  |
z         }t        j*                  |
z
        }t        j,                  t        j"                  |      t        j"                  |            }t        j.                  j                        }t        j0                  g j                        }t        j,                  ||j2                  z  ||j4                  z   |j6                  z        }|t        j,                  dt        j(                              z   t        j$                  |j4                  |	d   z        |j4                  |z  |t        j,                  |      |j8                  dz   |dk(  r&t        j:                  |t        j<                        !ns|dk(  rS|t?        d      |d   |d   kD  rt?        d      t        j:                  |d   |d   dz   t        j<                        !n|dk(  rt        d      t?        d      d}t        j@                  |j                        |z  |j4                  z  |z  }||z
  d|z   z  z
  }||z   | z  z   }t        j                  !      }t        jB                  ||      }t        jB                  ||      }d||z   z  }t        jB                   |       t        jB                  |      fd} !fd}tE        jF                  ||d|||f      \  }}}}|S )a  Solve the eigenvalue problem for a symmetric real tridiagonal matrix

  JAX implementation of :func:`scipy.linalg.eigh_tridiagonal`.

  Args:
    d: real-valued array of shape ``(N,)`` specifying the diagonal elements.
    e: real-valued array of shape ``(N - 1,)`` specifying the off-diagonal elements.
    eigvals_only: If True, return only the eigenvalues (default: False). Computation
      of eigenvectors is not yet implemented, so ``eigvals_only`` must be set to True.
    select: specify which eigenvalues to calculate. Supported values are:

      - ``'a'``: all eigenvalues
      - ``'i'``: eigenvalues with indices ``select_range[0] <= i <= select_range[1]``

      JAX does not currently implement ``select = 'v'``.
    select_range: range of values used when ``select='i'``.
    tol: absolute tolerance to use when solving for the eigenvalues.

  Returns:
    An array of eigenvalues with shape ``(N,)``.

  See also:
    :func:`jax.scipy.linalg.eigh`: general Hermitian eigenvalue solver

  Examples:
    >>> d = jnp.array([1., 2., 3., 4.])
    >>> e = jnp.array([1., 1., 1.])
    >>> eigvals = jax.scipy.linalg.eigh_tridiagonal(d, e, eigvals_only=True)
    >>> eigvals
    Array([0.2547188, 1.8227171, 3.1772828, 4.745281 ], dtype=float32)

    For comparison, we can construct the full matrix and compute the same result
    using :func:`~jax.scipy.linalg.eigh`:

    >>> A = jnp.diag(d) + jnp.diag(e, 1) + jnp.diag(e, -1)
    >>> A
    Array([[1., 1., 0., 0.],
           [1., 2., 1., 0.],
           [0., 1., 3., 1.],
           [0., 0., 1., 4.]], dtype=float32)
    >>> eigvals_full = jax.scipy.linalg.eigh(A, eigvals_only=True)
    >>> jnp.allclose(eigvals, eigvals_full)
    Array(True, dtype=bool)
  z.Calculation of eigenvectors is not implementedc                     j                   d   t        j                  j                   t        j                        t        j
                  j                   t        j                         fd} fd |       \  }}d}d}	dz
  |z  }
|
fd} ||	||f      \  }	}}|fd}t        j                  |||	||f      \  }}}|S )	z)Implements the Sturm sequence recurrence.r   r   c                     d   z
  } t        j                  | dk        }t        j                  d   k(  |       } | |fS Nr   r   where)r   countalphaalpha0_perturbationonesr@   rZ  s     r&   sturm_step0z5eigh_tridiagonal.<locals>._sturm.<locals>.sturm_step0  sJ    
(Q,aiiAtU+e
))E!HM#6
:aXor(   c                    |    | dz
     |z  z
  z
  }t        j                  |k  |dz   |      }t        j                  |k  t        j                  |       |      }||fS )Nr_   )r   ru  minimum)r'  r   rv  rw  beta_sqpivminr@   s      r&   
sturm_stepz4eigh_tridiagonal.<locals>._sturm.<locals>.sturm_step  si    
(WQU^a'
'!
+aiiVUQY6e
))AKQ!8!
<aXor(   r   r_   c                `    | \  }}}t              D ]  } ||z   ||      \  }} |z   ||fS r=   )range)r   startr   rv  jr  
unroll_cnts        r&   unrolled_stepsz8eigh_tridiagonal.<locals>._sturm.<locals>.unrolled_steps  sJ    oeQZ  3!eaiE253ZE))r(   c                <    | \  }}}t        j                  |      S r=   )r   less)iqcr'  r   rv  r   s       r&   r  z.eigh_tridiagonal.<locals>._sturm.<locals>.cond)  s    kaEXXa^r(   )r   r   rZ  r   int32ry  r
   
while_loop)rw  r}  r~  rx  r@   rz  r   rv  	blocksizer'  peelr  r  r   r   ry  r  r  rZ  s   `````         @@@@@r&   _sturmz eigh_tridiagonal.<locals>._sturm  s    AAIIaggRXX.E88AGG288,D  }HAu I	AEYDJ* !!Q/KAq% J ..~1e}EKAq%Lr(   z;diagonal and off-diagonal values must have same dtype, got z and zbOnly float32 and float64 inputs are supported as inputs to jax.scipy.linalg.eigh_tridiagonal, got r   r_   Nr   rW  r   r   r'  z/for select='i', select_range must be specified.z&Got empty index range in select_range.rb   z4eigh_tridiagonal(..., select='v') is not implementedz-'select must have a value in {'a', 'i', 'v'}.g @r   rT        ?c           
         | \  }}}}t        j                  t        j                  |      t        j                  t        j                  ||z
                    S r=   )r   logical_andr  amax)r   r'  r   r   upperabs_tolmax_its        r&   r  zeigh_tridiagonal.<locals>.cond  sK    Aua??F#((55=124 4r(   c                    | \  }}}} 	
|      }t        j                  |k  ||      }t        j                  |kD  ||      }d||z   z  }|dz   |||fS )Nr  r_   rt  )r   r'  r   midr  countsr  rw  rx  r}  r~  target_countss         r&   bodyzeigh_tridiagonal.<locals>.body  ss    Auc5E7F,?EFIIf-sE:EIIf},c59E

Cq5%e##r(   )$r`   r   r    r   r  r  r  r  rr   r  r   rw   r	   
issubdtypecomplexfloatingr#   sqrtabssquarerb  r  aminr
  finfory  r   epstinynmantr   r  ry   r   broadcast_tor
   r  )"derX   rm  rn  ro  betasupported_dtypesr   beta_absoff_diag_abs_row_sumlambda_est_maxlambda_est_mint_normr  onesafeminfudge
norm_slackr   r  target_shaper  r  r  r   r  r  rw  rx  r}  r  r~  r  s"                             @@@@@@@@r&   eigh_tridiagonalr    s;   ` 

N
OO.` ++a.%	Q$jj"**bllBMMJ
[[DJJ
  ;;-uTZZL: ; ;
[[((DJJ>N,N
 A{{m56 7 7 kk!n!!V88E?u{{B$6$67HHUOEhhtchhtn,-Gxx Hwwt}HjjG |Xcr]Xab\18BC=AK88E$889.88E$889.;;sww~.0GH& ((5;;
%
%++&#JJsUYYuyyEJJ(FG'S[[CHHW$566&

599x{#:;II'_kk#w'G ;;?& s]JJq1M}HIIAa(?@@JJ|AQ!0C288TM}
 , - - D
EE
 %yyEKK(50599<vE*
:
%E	F(:
:%
:
%
6% -(,


5
5%


5
5%uu}#FL1&(()<lK4$ $ dQsE,BC,!QQ	*r(   )siderD  r  r   )rD  r  max_iterationsc               x   t        j                  |       }|j                  dk7  rt        d      |dvrt        d      |j                  \  }}|dk(  r||k\  r&|dk(  r!t        j
                  |d|      \  }}	}
}
||	fS ||k  rt|d	k(  ro|j                  j                         }t        j
                  |d|      \  }}	}
}
|	j                  j                         }	|j                  j                         }||	fS t        d
|j                   d|      |dk(  rt        j                  |d      \  }}}|j                  |j                        }||z  }|dk(  r+|j                  j                         |dddf   z  |z  }	||	fS ||dddf   z  |j                  j                         z  }	||	fS t        d| d      )aX  Computes the polar decomposition.

  Given the :math:`m \times n` matrix :math:`a`, returns the factors of the polar
  decomposition :math:`u` (also :math:`m \times n`) and :math:`p` such that
  :math:`a = up` (if side is ``"right"``; :math:`p` is :math:`n \times n`) or
  :math:`a = pu` (if side is ``"left"``; :math:`p` is :math:`m \times m`),
  where :math:`p` is positive semidefinite.  If :math:`a` is nonsingular,
  :math:`p` is positive definite and the
  decomposition is unique. :math:`u` has orthonormal columns unless
  :math:`n > m`, in which case it has orthonormal rows.

  Writing the SVD of :math:`a` as
  :math:`a = u_\mathit{svd} \cdot s_\mathit{svd} \cdot v^h_\mathit{svd}`, we
  have :math:`u = u_\mathit{svd} \cdot v^h_\mathit{svd}`. Thus the unitary
  factor :math:`u` can be constructed as the application of the sign function to
  the singular values of :math:`a`; or, if :math:`a` is Hermitian, the
  eigenvalues.

  Several methods exist to compute the polar decomposition. Currently two
  are supported:

  * ``method="svd"``:

    Computes the SVD of :math:`a` and then forms
    :math:`u = u_\mathit{svd} \cdot v^h_\mathit{svd}`.

  * ``method="qdwh"``:

    Applies the `QDWH`_ (QR-based Dynamically Weighted Halley) algorithm.

  Args:
    a: The :math:`m \times n` input matrix.
    side: Determines whether a right or left polar decomposition is computed.
      If ``side`` is ``"right"`` then :math:`a = up`. If ``side`` is ``"left"``
      then :math:`a = pu`. The default is ``"right"``.
    method: Determines the algorithm used, as described above.
    precision: :class:`~jax.lax.Precision` object specifying the matmul precision.
    eps: The final result will satisfy
      :math:`\left|x_k - x_{k-1}\right| < \left|x_k\right| (4\epsilon)^{\frac{1}{3}}`,
      where :math:`x_k` are the QDWH iterates. Ignored if ``method`` is not
      ``"qdwh"``.
    max_iterations: Iterations will terminate after this many steps even if the
      above is unsatisfied.  Ignored if ``method`` is not ``"qdwh"``.

  Returns:
    A ``(unitary, posdef)`` tuple, where ``unitary`` is the unitary factor
    (:math:`m \times n`), and ``posdef`` is the positive-semidefinite factor.
    ``posdef`` is either :math:`n \times n` or :math:`m \times m` depending on
    whether ``side`` is ``"right"`` or ``"left"``, respectively.

  Examples:

    Polar decomposition of a 3x3 matrix:

    >>> a = jnp.array([[1., 2., 3.],
    ...                [5., 4., 2.],
    ...                [3., 2., 1.]])
    >>> U, P = jax.scipy.linalg.polar(a)

    U is a Unitary Matrix:

    >>> jnp.round(U.T @ U)  # doctest: +SKIP
    Array([[ 1., -0., -0.],
           [-0.,  1.,  0.],
           [-0.,  0.,  1.]], dtype=float32)

    P is positive-semidefinite Matrix:

    >>> with jnp.printoptions(precision=2, suppress=True):
    ...     print(P)
    [[4.79 3.25 1.23]
     [3.25 3.06 2.01]
     [1.23 2.01 2.91]]

    The original matrix can be reconstructed by multiplying the U and P:

    >>> a_reconstructed = U @ P
    >>> jnp.allclose(a, a_reconstructed)
    Array(True, dtype=bool)

  .. _QDWH: https://epubs.siam.org/doi/abs/10.1137/090774999
  r   z"The input `a` must be a 2-D array.)rightleftz5The argument `side` must be either 'right' or 'left'.r   r  F)is_hermitianr  r  zdmethod='qdwh' only supports mxn matrices where m < n where side='right' and m >= n side='left', got z with side=rH   )rA   Nz#Unknown polar decomposition method rx   )r   r    r   ry   r   r   r   r#   r`   r!   rH   rp   rr   )r   r  rD  r  r  ri  r   r   unitaryposdefr   u_svds_svdvh_svds                 r&   polarr    s   l 	A#XX]
9
::	""
L
MM	$!QvAv$'/"ii%SIgvq!. 
&- 
Q46>EEJJLc"ii%SIgvq!xx}}f		 g$ 
&!   !447II;lTG!M N N %>>#UCE5&LL%EfnGw%a.0F:f 
&	 dAg&577<<>:f 
& :6(!D
EEr(   c                     t        j                  t        j                               j                  }t        j                        } fdfd}t	        j
                  d|||      }|S )u   
  Implements Björck, Å., & Hammarling, S. (1983).
      "A Schur method for the square root of a matrix". Linear algebra and
      its applications", 52, 127-140.
  c                   |\  dz
  | z
  t        j                  dz   fdd      }t        j                  f   |k(  df   |z
        z   z        }j                  f   j                  |      fS )Nr_   c                (    || f   | f   z  z   S r=   r>   )r   valr  r'  r  s     r&   r   z-_sqrtm_triu.<locals>.i_loop.<locals>.<lambda>  s!    sQq!tWqAw5F/F r(           )r
   	fori_loopr   ru  atset)	r%   datasvaluer  r'  r  r   diags	       @@@r&   i_loopz_sqrtm_triu.<locals>.i_loop  s    DAq	A	Aa!eQ FLAIIa1glCAw{tAwa'89;Eadd1a4jnnU###r(   c                B    t        j                  d| | |f      \  }}|S rs  )r
   r  )r  r  r   r  s      r&   j_loopz_sqrtm_triu.<locals>.j_loop!  s$    ==Av1v.DAqHr(   r   )r   r  r  sizer
   r  )r   r   r  r  r  r  s   `   @@r&   _sqrtm_triur    sV     
#((1+	$
ii!	hhtn!$ 
mmAq&!$!	
(r(   c                .   t        | d      \  }}t        |      }t        j                  t        j                  ||t        j
                  j                        t        j                  |j                        t        j
                  j                        S )Nro   rl   r   )	rs   r  r   r   r
   r   r   r#   r   )r   r   Zsqrt_Ts       r&   _sqrtmr  (  sb    	q	#$!Qq>&	CJJq&CMM4I4IJHHQSSMS]]-B-B
D Dr(   c                8    |dkD  rt        d      t        |       S )u[  Compute the matrix square root

  This function is implemented using :func:`scipy.linalg.schur`, which is only
  supported on CPU.

  JAX implementation of :func:`scipy.linalg.sqrtm`.

  Args:
    A: array of shape ``(N, N)``
    blocksize: Not supported in JAX; JAX always uses ``blocksize=1``.

  Returns:
    An array of shape ``(N, N)`` containing the matrix square root of ``A``

  See Also:
    :func:`jax.scipy.linalg.expm`

  Examples:
    >>> a = jnp.array([[1., 2., 3.],
    ...                [2., 4., 2.],
    ...                [3., 2., 1.]])
    >>> sqrt_a = jax.scipy.linalg.sqrtm(a)
    >>> with jnp.printoptions(precision=2, suppress=True):
    ...   print(sqrt_a)
    [[0.92+0.71j 0.54+0.j   0.92-0.71j]
     [0.54+0.j   1.85+0.j   0.54-0.j  ]
     [0.92-0.71j 0.54-0.j   0.92+0.71j]]

    By definition, matrix multiplication of the matrix square root with itself should
    equal the input:

    >>> jnp.allclose(a, sqrt_a @ sqrt_a)
    Array(True, dtype=bool)

  Notes:
    This function implements the complex Schur method described in [1]_.  It does not use
    recursive blocking to speed up computations as a Sylvester Equation solver is not
    yet available in JAX.

  References:
    .. [1] Björck, Å., & Hammarling, S. (1983). "A Schur method for the square root of a matrix".
           Linear algebra and its applications, 52, 127-140.
  r_   z'Blocked version is not implemented yet.)r`   r  )r   r  s     r&   sqrtmr  0  s"    X ] IJJ	r(   )r,   c                   ~t        j                  |       }t        j                  |      }|j                  dk7  s|j                  d   |j                  d   k7  rt	        d      |j                  dk7  s|j                  d   |j                  d   k7  rt	        d      |j                  d   |j                  d   k7  r%t	        d|j                   d|j                         t        ||      \  }}t        j                  |j                        j                  |j                  d   dk(  r||fS fdfd	}t        j                  d|||f      S )
a+  Convert real Schur form to complex Schur form.

  JAX implementation of :func:`scipy.linalg.rsf2csf`.

  Args:
    T: array of shape ``(..., N, N)`` containing the real Schur form of the input.
    Z: array of shape ``(..., N, N)`` containing the corresponding Schur transformation
      matrix.
    check_finite: unused by JAX

  Returns:
    A tuple of arrays ``(T, Z)`` of the same shape as the inputs, containing the
    Complex Schur form and the associated Schur transformation matrix.

  See Also:
    :func:`jax.scipy.linalg.schur`: Schur decomposition

  Examples:
    >>> A = jnp.array([[0., 3., 3.],
    ...                [0., 1., 2.],
    ...                [2., 0., 1.]])
    >>> Tr, Zr = jax.scipy.linalg.schur(A)
    >>> Tc, Zc = jax.scipy.linalg.rsf2csf(Tr, Zr)

    Both the real and complex form can be used to reconstruct the input matrix
    to float32 precision:

    >>> jnp.allclose(Zr @ Tr @ Zr.T, A, atol=1E-5)
    Array(True, dtype=bool)
    >>> jnp.allclose(Zc @ Tc @ Zc.conj().T, A, atol=1E-5)
    Array(True, dtype=bool)

    The real-valued Schur form is only quasi-upper-triangular, as we can see in this case:

    >>> with jax.numpy.printoptions(precision=2, suppress=True):
    ...   print(Tr)
    [[ 3.76 -2.17  1.38]
     [ 0.   -0.88 -0.35]
     [ 0.    2.37 -0.88]]

    By contrast, the complex form is truly upper-triangular:

    >>> with jnp.printoptions(precision=2, suppress=True):
    ...   print(Tc)
    [[ 3.76+0.j    1.29-0.78j  2.02-0.5j ]
     [ 0.  +0.j   -0.88+0.91j -2.02+0.j  ]
     [ 0.  +0.j    0.  +0.j   -0.88-0.91j]]
  r   r   r_   zInput 'T' must be square.zInput 'Z' must be square.z"Input array shapes must match: Z: z vs. T: c           	        t        j                  t        j                  || dz
  | dz
  fd            || | f   z
  }t        j                  t        j                  |d   || | dz
  f   g            j                  |j                        }|d   |z  }|| | dz
  f   |z  }t        j                  |j                         |g| |gg|j                        }t        j                  || dz
  dd      }t        j                        | dz
  k\  }	|t        j                  |	|d      z  }
t        j                  |	 ||
      }t        j                  ||| dz
  d      }t        j                  || dz
  dd      }t        j                        d d t        j                  f   | dz   k  }t        j                  ||d      |j                         j                   z  }t        j                  | ||      }t        j                  ||| dz
  d      }t        j                  || dz
  dd      }t        j                  |||j                         j                   z  | dz
  d      }||fS )Nr_   )r   r   r   r   r   rW  )rS   rY   r
   dynamic_slicer	  r   r   rp   rr   r#   dynamic_slice_in_dimr   ru  dynamic_update_slice_in_dimr   newaxisr   )r   r   r  mur   r5   r  GT_rowscol_maskG_dot_T_zeroed_cols
T_rows_newT_colsrow_maskT_zeroed_rows_dot_GH
T_cols_newZ_colsr   s                    r&   _update_T_Zzrsf2csf.<locals>._update_T_Z  s   			C--a!A#qsVD	E!Q$	OB		2a5!AqsF)"456==aggFA
1	A	!QqS&	AA		AFFHa=A2q'*!'':A %%a1aa8Fzz!}!#Hcii&!<<H9f.ABJ'':qsCA %%a1aa8Fzz!}Q

]+ac1H99Xvq9AFFHJJFH9f.BCJ'':qsCA %%a1aa8F''6AFFHJJ+>!!LAa4Kr(   c           
     V   | z
  }|\  }}t        j                  t        j                  |||dz
  f         t        j                  ||dz
  |dz
  f         t        j                  |||f         z   z  kD  d |||      \  }}|j                  ||dz
  f   j                  d      }||fS )Nr_   c                
    ||fS r=   r>   )r   r   r  s      r&   r   z0rsf2csf.<locals>._rsf2scf_iter.<locals>.<lambda>  s
    q!f r(   r  )r
   r  r   r  r  r  )r'  TZr   r   r  r   r  r  s        r&   _rsf2scf_iterzrsf2csf.<locals>._rsf2scf_iter  s    	!ADAq88	gga1Q3i3!A#qs( 4swwqAw7G GHHA	DAq
 	
Q!VAa4Kr(   )r   r    r   r   ry   r   r	   r  rr   r  r
   r  )	r   r  r,   T_arrZ_arrr  r   r  r  s	         @@@r&   rsf2csfr  a  s#   d 
++a.%
++a.%
ZZ1_A%++a.8
0
11
ZZ1_A%++a.8
0
11
[[^u{{1~%
9%++hu{{m\
]]'u5,%U[[!%%#kk!n!!V%<4	 
q!]UEN	;;r(   c                    y r=   r>   r   calc_qr+   r,   s       r&   
hessenbergr    s    47r(   c                    y r=   r>   r  s       r&   r  r    s    BEr(   )r  r,   r+   )r  r+   r,   c          	        ~~t        j                  |       d   }|dk(  rA|r*t        j                  |       t        j                  |       fS t        j                  |       S t	        j
                  |       \  }}t        j                  |d      }|rt	        j                  |dddddf   |      }|j                  dd }	t        j                  t        j                  |	dz   |j                        t        j                  |	d|dz
  fz   |j                        gt        j                  |	|dz
  dfz   |j                        |gg      }||fS |S )	a  Compute the Hessenberg form of the matrix

  JAX implementation of :func:`scipy.linalg.hessenberg`.

  The Hessenberg form `H` of a matrix `A` satisfies:

  .. math::

     A = Q H Q^H

  where `Q` is unitary and `H` is zero below the first subdiagonal.

  Args:
    a : array of shape ``(..., N, N)``
    calc_q: if True, calculate the ``Q`` matrix (default: False)
    overwrite_a: unused by JAX
    check_finite: unused by JAX

  Returns:
    A tuple of arrays ``(H, Q)`` if ``calc_q`` is True, else an array ``H``

    - ``H`` has shape ``(..., N, N)`` and is the Hessenberg form of ``a``
    - ``Q`` has shape ``(..., N, N)`` and is the associated unitary matrix

  Examples:
    Computing the Hessenberg form of a 4x4 matrix

    >>> a = jnp.array([[1., 2., 3., 4.],
    ...                [1., 4., 2., 3.],
    ...                [3., 2., 1., 4.],
    ...                [2., 3., 2., 2.]])
    >>> H, Q = jax.scipy.linalg.hessenberg(a, calc_q=True)
    >>> with jnp.printoptions(suppress=True, precision=3):
    ...   print(H)
    [[ 1.    -5.078  1.167  1.361]
     [-3.742  5.786 -3.613 -1.825]
     [ 0.    -2.992  2.493 -0.577]
     [ 0.     0.    -0.043 -1.279]]

    Notice the zeros in the subdiagonal positions. The original matrix
    can be reconstructed using the ``Q`` vectors:

    >>> a_reconstructed = Q @ H @ Q.conj().T
    >>> jnp.allclose(a_reconstructed, a)
    Array(True, dtype=bool)
  r   r   .r_   Nr   )r_   r_   r   )r   r   r   
zeros_liker!   r  r   householder_productblockry  rr   rZ  )
r   r  r+   r,   r   a_outtaushr   
batch_dimss
             r&   r  r    s/   b <hhqk"o!!V^^Aq 111^^A%%a(+%	hhub!&&uS!"crc\':DAASb!J		CHHZ&0DIIjAq1u:5U[[IKIIjAE1:5U[[I1MO 	PA a4KHr(   c                :   |5t        d|        t        j                  t        j                  |             }nt        d| |       t	        t        j
                  t        j                  |             t        j
                  t        j                  |                  S )a  Construct a Toeplitz matrix.

  JAX implementation of :func:`scipy.linalg.toeplitz`.

  A Toeplitz matrix has equal diagonals: :math:`A_{ij} = k_{i - j}`
  for :math:`0 \le i < n` and :math:`0 \le j < n`. This function
  specifies the diagonals via the first column ``c`` and the first row
  ``r``, such that for row `i` and column `j`:

  .. math::

     A_{ij} = \begin{cases}
      c_{i - j} & i \ge j \\
      r_{j - i} & i < j
     \end{cases}

  Notice this implies that :math:`r_0` is ignored.

  Args:
    c: array of shape ``(..., N)`` specifying the first column.
    r: (optional) array of shape ``(..., M)`` specifying the first row. Leading
      dimensions must be broadcast-compatible with those of ``c``. If not specified,
      ``r`` defaults to ``conj(c)``.

  Returns:
    A Toeplitz matrix of shape ``(... N, M)``.

  Examples:
    Specifying ``c`` only:

    >>> c = jnp.array([1, 2, 3])
    >>> jax.scipy.linalg.toeplitz(c)
    Array([[1, 2, 3],
           [2, 1, 2],
           [3, 2, 1]], dtype=int32)

    Specifying ``c`` and ``r``:

    >>> r = jnp.array([-1, -2, -3])
    >>> jax.scipy.linalg.toeplitz(c, r)  # Note r[0] is ignored
    Array([[ 1, -2, -3],
           [ 2,  1, -2],
           [ 3,  2,  1]], dtype=int32)

    If specifying only complex-valued ``c``, ``r`` defaults to ``c.conj()``,
    resulting in a Hermitian matrix if ``c[0].imag == 0``:

    >>> c = jnp.array([1, 2+1j, 1+2j])
    >>> M = jax.scipy.linalg.toeplitz(c)
    >>> M
    Array([[1.+0.j, 2.-1.j, 1.-2.j],
           [2.+1.j, 1.+0.j, 2.-1.j],
           [1.+2.j, 2.+1.j, 1.+0.j]], dtype=complex64)
    >>> print("M is Hermitian:", jnp.all(M == M.conj().T))
    M is Hermitian: True

    For N-dimensional ``c`` and/or ``r``, the result is a batch of Toeplitz matrices:

    >>> c = jnp.array([[1, 2, 3], [4, 5, 6]])
    >>> jax.scipy.linalg.toeplitz(c)
    Array([[[1, 2, 3],
            [2, 1, 2],
            [3, 2, 1]],
    <BLANKLINE>
           [[4, 5, 6],
            [5, 4, 5],
            [6, 5, 4]]], dtype=int32)
  toeplitz)r   r   	conjugater    	_toeplitz
atleast_1d)r5   r   s     r&   r  r    se    J YJ"ckk!n%AJ1%	3>>#++a.13>>#++a.3Q	RRr(   z(m),(n)->(m,n)r   c                   | j                   \  }|j                   \  }|dk(  s|dk(  rAt        j                  ||ft        j                  | j                  |j                              S ||z   dz
  }t        j
                  | d d d   |dd  f      }t        j                  |j                  d|df      |fdddt        j                  j                        d   }t        j                  |d	      S )
Nr   r   r_   r   r   VALID)NTCIOTr  )dimension_numbersr   rW  )r   r   emptypromote_typesrr   rb  r
   conv_general_dilated_patchesreshaper   r   flip)r5   r   ncolsnrowsnelemselemspatchess          r&   r   r   g  s    77&%77&%
aZ5A:99eU^3+<+<QWWagg+NOO5=1&
//1TrT7AabE*
+%,,mmQN#hg1F%%' ()*' 
'	""r(   )r   c                f    t        j                  t        | dfd      }d||j                  z   dz   z  S )a  Create a Hilbert matrix of order n.

  JAX implementation of :func:`scipy.linalg.hilbert`.

  The Hilbert matrix is defined by:

  .. math::

     H_{ij} = \frac{1}{i + j + 1}

  for :math:`1 \le i \le n` and :math:`1 \le j \le n`.

  Args:
    n: the size of the matrix to create.

  Returns:
    A Hilbert matrix of shape ``(n, n)``

  Examples:
    >>> jax.scipy.linalg.hilbert(2)
    Array([[1.        , 0.5       ],
           [0.5       , 0.33333334]], dtype=float32)
    >>> jax.scipy.linalg.hilbert(3)
    Array([[1.        , 0.5       , 0.33333334],
           [0.5       , 0.33333334, 0.25      ],
           [0.33333334, 0.25      , 0.2       ]], dtype=float32)
  r_   r   )r
   broadcasted_iotafloatr   )r   r   s     r&   hilbertr  u  s2    : 
51a&!,!	
AGaKr(   )r   kindc                *   |d}g d}||vrt        d| d|       t        j                  | t        j                        }t        |dddf   |dddf         }|dk(  r|S |dk(  r|j                  S t        j                  ||j                        S )	a  Create a Pascal matrix approximation of order n.

  JAX implementation of :func:`scipy.linalg.pascal`.

  The elements of the Pascal matrix approximate the binomial coefficients. This
  implementation is not exact as JAX does not support exact factorials.

  Args:
    n: the size of the matrix to create.
    kind: (optional) must be one of ``lower``, ``upper``, or ``symmetric`` (default).

  Returns:
    A Pascal matrix of shape ``(n, n)``

  Examples:
    >>> with jnp.printoptions(precision=3):
    ...   print(jax.scipy.linalg.pascal(3, kind="lower"))
    ...   print(jax.scipy.linalg.pascal(4, kind="upper"))
    ...   print(jax.scipy.linalg.pascal(5))
    [[1. 0. 0.]
     [1. 1. 0.]
     [1. 2. 1.]]
    [[1. 1. 1. 1.]
     [0. 1. 2. 3.]
     [0. 0. 1. 3.]
     [0. 0. 0. 1.]]
    [[ 1.  1.  1.  1.  1.]
     [ 1.  2.  3.  4.  5.]
     [ 1.  3.  6. 10. 15.]
     [ 1.  4. 10. 20. 35.]
     [ 1.  5. 15. 35. 70.]]
  Nr   )r   r   r  zExpected kind to be on of: r   r   r   r  )ry   r   r   r   r  _binomr   r  )r   r  
valid_kindr   L_ns        r&   pascalr    s    D 
\D.*	
2:,fTFK
LL	jj"**%!qDz1T1W:&#	W_J	W_55L	cee	r(   c                    t        j                  | dz         }t        j                  | |z
  dz         }t        j                  |dz         }t        j                  ||z
  |z
        S )Nr,  )r
   lgammaexp)r   r   r   r6   r5   s        r&   r  r    sS    	jjS!	jjQ!	jjS!	Q	r(   c                B   	
 t        d       \   j                  \  	
	
z  }t        j                  |dz
  dd      }t        j                  	
z  fj
                        } 	
fd}t        j                  |||      \  }}|j                  	
f      S )a;  
  Solves the Sylvester equation using Bartels-Stewart algorithm
  .. math::

    RY + YS^T = F

  where R and S are upper triangular matrices following a Schur decomposition.

  Args:
    R: Matrix of shape m x m
    S: Matrix of shape n x n
    F: Matrix of shape m x n

  Returns:
    Y: Matrix of shape m x n
   _solve_sylvester_triangular_scanr_   r   r   c                4   |z  }|z  }| j                  f      }||f   }t        j                        }||kD  }|d d f   }|d d |f   }	t        j                  t        j                  |||	z  d            }
t        j                        }||kD  }||d d f   }d d |f   }t        j                  t        j                  |||z  d            }||
|z   z  }|||f   ||f   z   z  }| j
                  |z  |z      j                  |      } | d fS )Nr  )r
  r   r   r_  ru  r  r  )Y_flatr  r'  r  Yrhsk_rowr  r_rowy_colrow_termk_colr  y_rows_colcol_termr  Fr   Sr   r   s                    r&   scan_fnz1_solve_sylvester_triangular_scan.<locals>.scan_fn  s1   qAaA1vA
AqD'C JJqMEqyHadGEadGEwwsyy55=#>?H JJqMEqyHadGEadGEwwsyy55=#>?H 8hC
1a41QT7"
#CYYq1uqy!%%c*F4<r(   )	r   r   r   r   rZ  rr   r
   r)  r
  )r   r-  r,  totalflat_indicesY0r.  Y_flat_finalr   r   r   s   ```      @@r&   r  r    s    " !!CQ1M'!Q	
$!Q
a%%EAIr2.,
yy!a%)" 6 HHWb,7/,			q!f	%%r(   rs   g:0yE>)rD  ro  c                  t        d| ||      \  } }}|j                  \  }}| j                  ||fk7  s"|j                  ||fk7  s|j                  ||fk7  r2t        d| j                   d|j                   d|j                         |dk(  rt        | d      \  }}t        |j	                         j
                  d      \  }	}
|j	                         j
                  |j                  |j                        z  |
z  }t        ||	j	                         j
                  |      }||z  |
j	                         j
                  z  n|dk(  rt        j                  j                  |       \  }}t        j                  j                  |      \  }}t        ||j                  |j                        |z        }|d	d	d	f   |d	d	d	f   z   }||z  }|d	|d	|f   |d	|d	|f   z  t        |      d	|d	|f   z  nt        d
| d      t        j                  |j                  t         j"                        sj$                  t'        j(                  t        j*                  t        j,                  t        j                  j/                  |       d	d	d	f   t        j                  j/                  |      d	d	d	f   z         |k        fdfd      S )a
  
  Solves the Sylvester equation
  .. math::

    AX + XB = C

  Using one of two methods.

  (1) Bartell-Stewart (schur) algorithm (default) [CPU ONLY]:

  Where A and B are first decomposed using Schur decomposition to construct and alternate sylvester equation:
  .. math::

    RY + YS^T = F

  Where R and S are in quasitriangular form when A and B are real valued and triangular when A and B are complex.

  (2) The Eigen decomposition algorithm [CPU and GPU]

  Args:
    A: Matrix of shape m x m
    B: Matrix of shape n x n
    C: Matrix of shape m x n
    method: "schur" is the default and is accurate but slow, and "eigen" is an alternative that is faster but less accurate for ill-conditioned matrices.
    tol: How close the sum of the eigenvalues from A and B can be to zero before returning matrix of NaNs

  Returns:
    X: Matrix of shape m x n

  Examples:
    >>> A = jax.numpy.array([[1, 2], [3, 4]])
    >>> B = jax.numpy.array([[5, 6], [7, 8]])
    >>> C = jax.numpy.array([[6, 8], [10, 12]])
    >>> X = jax.scipy.linalg.solve_sylvester(A, B, C)
    >>> print(X) # doctest: +SKIP
    [[1. 0.]
     [0.  1.]]

  Notes:
    The Bartel-Stewart algorithm is robust because a Schur decomposition always exists even for defective matrices,
    and it handles complex and ill-conditioned problems better than the eigen decomposition method.
    However, there are a couple of drawbacks. First, It is computationally more expensive than
    the eigen decomposition method because you need to perform a Schur decomposition and then scan the entire solution matrix.
    Second, it requires more system memory compared to the eigen decomposition method.

    The eigen decomposition method is the fastest method to solve a sylvester equation. However, this speed brings with it a couple of drawbacks.
    First, A and B must be diagonalizable otherwise the eigenvectors will be linearly dependent and ill-conditioned leading to accuracy issues.
    Second, when the eigenvectors are not orthogonal roundoff errors are amplified.

    Additionally, for complex types as the size of the matrix increases the accuracy of the results degrades. Float64 types are most robust to degradation.

    The tol argument allows you to specify how ill-conditioned a matrix can be and still estimate a solution.
    For matrices that are ill-conditioned we recommend using float64 instead of the default float32 dtype. The solver
    can still return good estimates for ill-conditioned matrices depending on how close to zero the sums of the eigenvalues of A and B
    are.
  solve_sylvesterz/Incompatible shapes for Sylvester equation:
A: z
B: z
C: rs   ro   rl   eigenNzUnrecognized method z6. The two valid methods are either "schur" or "eigen".c                 P    t        j                         t        j                  z  S r=   )r   r  r   r   Xs   r&   r   z!solve_sylvester.<locals>.<lambda>h	  s    CNN1& r(   c                      S r=   r>   r7  s   r&   r   z!solve_sylvester.<locals>.<lambda>i	  s    A r(   )r   r   ry   rs   r#   r   rp   rr   r  r   r   eigr   r{   r	   r  r   r  rw   r
   r  anyr  rY   )r   r  r   rD  ro  r   r   r   r  r-  r  r,  r"  RAUARBUBWr8  s                     @r&   r4  r4  	  st   t !!2Aq!<'!Q	
$!QWWA!''aV+qww1a&/@
GyPUVWV]V]U^^cdedkdkclm
nnw9%DAqI.DAq 	


QXXagg&&*A 	)AFFHJJ:A 	
A

AZZ^^AFBZZ^^AFBb!((288$r)*A
1d7bqk!A	AA
2A2bqb5	Abqb!eHs2wrr"1"u~-A
+F83mn
oo			177B$6$6	7	A	GGCGGCJJ&&q)!T'2SZZ5G5G5J4QR75SSTWZZ[&
 r(   )r   r   r   boolreturnr   )FFT)
r   r   r   rA  r+   rA  r,   rA  rB  r   )
r   r   r   rA  r+   rA  r,   rA  rB  ztuple[Array, bool])r5   r   r6   r   r   rA  rB  r   )FT)
r9   ztuple[ArrayLike, bool]r6   r   r:   rA  r,   rA  rB  r   )r@   r   rA   rA  rB   Literal[True]rB  tuple[Array, Array, Array])r@   r   rA   rA  rB   Literal[False]rB  r   )r@   r   rA   rA  rB   rA  rB  "Array | tuple[Array, Array, Array])r   r   rA   rA  rB   rA  rB  rF  )TTFTrI   )r   r   rA   rA  rB   rC  r+   rA  r,   rA  rL   strrB  rD  )FTrI   )r   r   rA   rA  rB   rE  r+   rA  r,   rA  rL   rG  rB  r   )T)r   r   rA   rA  rB   rA  r+   rA  r,   rA  rL   rG  rB  rF  )r   r   r+   rA  r,   rA  rB  r   )r   r   r6   ArrayLike | Noner   rA  rX   rC  rY   NonerZ   intrB  r   )r   r   r6   rH  r   rA  rX   rE  rY   rI  rZ   rJ  rB  tuple[Array, Array])r   r   r6   rH  r   rA  rX   rA  rY   rI  rZ   rJ  rB  Array | tuple[Array, Array])	NTFFFTNr_   T)r   r   r6   rH  r   rA  rX   rE  r+   rA  r:   rA  rf   rA  rY   rI  rZ   rJ  r,   rA  rB  rK  )NT)r   r   r6   rH  r   rA  rX   rC  r+   rA  r:   rA  rf   rA  rY   rI  rZ   rJ  r,   rA  rB  r   )FFTNr_   T)r   r   r6   rH  r   rA  rX   rA  r+   rA  r:   rA  rf   rA  rY   rI  rZ   rJ  r,   rA  rB  rL  )r   r   rm   rG  rB  rK  )rw   )r   r   rm   rG  rB  rK  )r   r   r+   rA  r,   rA  rB  rK  )r   FT)r   ztuple[Array, ArrayLike]r6   r   r   rJ  r:   rA  r,   rA  rB  r   )r   r   r   rC  rB  rK  )r   r   r   rE  rB  rD  )r   r   r   rA  rB  0tuple[Array, Array] | tuple[Array, Array, Array])
r   r   r   rE  r+   rA  r,   rA  rB  rD  )
r   r   r   rC  r+   rA  r,   rA  rB  rK  )
r   r   r   rA  r+   rA  r,   rA  rB  rM  )r   r   r   Literal['r']r   rE  rB  tuple[Array])r   r   r   rN  r   rC  rB  rK  )r   r   r   Literal['full', 'economic']r   rE  rB  rK  )r   r   r   rP  r   rC  rB  rD  )r   r   r   rG  r   rE  rB  "tuple[Array] | tuple[Array, Array])r   r   r   rG  r   rC  rB  rM  )r   r   r   rG  r   rA  rB  ?tuple[Array] | tuple[Array, Array] | tuple[Array, Array, Array])FN)r   r   r+   rA  r   r   r   rP  r   rE  r,   rA  rB  rK  )r   r   r+   rA  r   r   r   rP  r   rC  r,   rA  rB  rD  )r   r   r+   rA  r   r   r   rP  r   rA  r,   rA  rB  rM  )r   r   r+   rA  r   r   r   rN  r   rE  r,   rA  rB  rO  )r   r   r+   rA  r   r   r   rN  r   rC  r,   rA  rB  rK  )r   r   r+   rA  r   r   r   rN  r   rA  r,   rA  rB  rQ  )FNr   FT)r   r   r+   rA  r   r   r   rG  r   rA  r,   rA  rB  rR  )
r   r   r6   r   r   rG  r   rA  rB  r   )FFFFTr   )r   r   r6   r   r   rA  r+   rA  r:   rA  r   rA  r,   rA  r   rG  rB  r   )r   r   r6   r   r   	int | strr   rA  r   rA  rB  r   )r   FFFNT)r   r   r6   r   r   rS  r   rA  r   rA  r:   rA  r   r   r,   rA  rB  r   )r   r   r   rA  r   rJ  rB  r   )r   r   rB  rD  )F)r   r   r   r   r   rA  rB  r   )r   r   r  r   rB  r   )r   r   r   r   r   rJ  rB  r   )r   r   rB  rK  )
r   r   rH  r   rD  
str | NonerE  rC  rB  rK  )
r   r   rH  r   rD  rT  rE  rE  rB  r   )
r   r   rH  r   rD  rT  rE  rA  rB  rL  )rc  r   rB  r   )r  r   r  r   rX   rA  rm  rG  rn  ztuple[float, float] | Nonero  float | NonerB  r   )r  )r   r   r  rG  rD  rG  r  rU  r  z
int | NonerB  rK  )r   r   rB  r   )r   r   rB  r   )r   r   r  rJ  rB  r   )r   r   r  r   r,   rA  rB  rK  )
r   r   r  rE  r+   rA  r,   rA  rB  r   )
r   r   r  rC  r+   rA  r,   rA  rB  rK  )
r   r   r  rA  r+   rA  r,   rA  rB  rL  r=   )r5   r   r   rH  rB  r   )r5   r   r   r   rB  r   )r   rJ  rB  r   )r   rJ  r  rT  rB  r   )r   r   r-  r   r,  r   rB  r   )r   r   r  r   r   r   rD  rG  ro  r  rB  r   )[
__future__r   	functoolsr   textwraptypingr   r   r   r   r   jax._srcr   r	   r
   r   jax._src.apir   r   r   jax._src.laxr   r!   jax._src.numpyrS   r   r   jax._src.numpy.utilr   r   r   r   r   jax._src.tpu.linalgr   jax._src.typingr   r   dedent_no_chkfinite_doc_no_overwrite_and_chkfinite_docr'   r"   r.   r7   r;   rC   rH   rT   r[   ra   ru   rs   r{   r   r   r   r}   r   r   r   r   r   r   r  r  r   r  r   r  r  r  r  r  rI  rl  r  default_matmul_precisionr  r  r  r  r  r  r  r   r  r  r  r  r4  r>   r(   r&   <module>re     s   #   ) )     ! ' ' - / 52 2 % , $HOO %   #46s"s Z ( !( EJ"&99+09x GL$(-+!-+-?-+^ Z  ! ?C,!,!7;,!GL,!\ 
 l 
 l	 X 
 X	 k 
 k45O 6O 
NR8<$II15II)CI 
I 
8<$441544).4 
4 
4!$441544).4 
4 
EI8<$QQ15QQ)KQ 
Q
 FJ8<$FEFE15FEFE)KFER"J 
22"2',2 
2 
@@"@':@ 
@ 
HH"H'BH 
H AB"'B C$ 
AECHHL-1O%O<@OO+/OAEO O '+O 7JO 
O
 
A:?"$TA$A37AA+/AAEA A '+A 7<A 
A
 
:?HL-1A$A37AA+/AAEA A '+A 7<A 
A
 
AE9>HL-1WW26WW+/WAEW W '+W 7RW 
W
 BF9>HL-1B9B926B9B9+/B9AEB9 B9 '+B9 7RB9H [! "
AH5p 450 60f =>MN=A51516:51FK51 ?51n 
 K 
 K	 S 
 S	 _ 
 _D  
LQ EE%?E 
E 
CH >>%8> 
> 
BG [[%U[ 
[ ABBG DD%UD CDN 
 
 
%% 
% 
%% 
% 
,&, 
, 
4.4 
4 
B<B 
B 
QKQ 
Q )*K +& 
>EJ >(>4B>>%8> 
> 
EDH E(E4AEE%?E 
E 
A;@ A(A48AA <A 
A
 
6;RV%3KO 
 
$59PT$$%2$IM$$ 
$ 
3,133%)3AE3-3 
3 
OU48PP-1PJP 
P
 PV48Q Q -1Q JQ h *+F ,F. 5:NS5:='='26='GK='='/2='?D='~ 89!26;@ :6 V[FK=A>>$(>>?C>>>>6:>>FK>>B :;38r H <HT  <"8 A 	 
EI/3Q,Q8KQ 
Q 
EI =-=27= 
= 
EI&*P#P/JP 
P /0EI&*5#5/J5 15p +. +.\ ?@IN#&SW)-D D6PD&D27D ADL '(   +vfZ^'+v$v0Cv , )vr  2 D D.b &'i< (i<V 
LQ$(8!8-28 
8 
KP$(F!F-@F 
F >?/4%$(A!A-HA @AHJSX 		 	 ,<=# ># V > ^$3 %3j  5&p h&'OVei ^ (^r(   