
    VpfY9                   p	   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 d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d dl m!Z" d dl#m$Z$m%Z% d dl&m'Z( d dl&m)Z* ddZ+ddZ,ddZ-ddZ!ddd"Z.edd#            Z/edd%            Z/edd&            Z/d' Z/d( Z0dd)Z1dd*Z2dd+Z3dd,Z4dd-Z5dd.Z6dd/Z7ej8        dd0            Z9e9:                    d1            dd2Z;ej<        Z<ej8        dd3            Z=d4 Z>e=?                    e>           ej8        dd5            Z@d6 ZAe@?                    eA           ej8        d7             ZBd8 ZCeB?                    eC           dd9ZDdd;ZEdd>ZFdd?ZGg d@ZHej8        dddB            ZIdddCZJeI?                     eeeJ                     ddDZK e
jL        dEe
jM                  ZN e
jL        dFe
jO                  ZP e
jL        dGe
jM                  ZQ e
jL        dHe
jO                  ZRddIZSddJZTddKZUddLZV eej8        dMN          dddR            ZWdS ZXeW?                    eX           dT ZYdU ZZddWZ[ e
j\         e
j]        dXe
j^        z                      Z_dY Z`ddZZadd[Zbdd\Zcdd]Zdd^ Zed_d`dddZf eedbdcge          d_d`ddf            ZgddlZh eedXm          ddn            Zi eedom          ddp            ZjddrZkddsZl eedtm          ddx            Zm	 dddzZndd{ZoddZpddZqddZrddZsd Ztd Zud ZvddZwddZxej8        edd                        Zyeyj?        ed                         ZzddZ{ddZ|ddZ} eej8        dN          ej~        edd                                    Zej?        ed                         ZddZddZddZddZddZddZej8        dd            Zd Zd Ze:                    d d            d Zd Zeej~        d                         Zeej~        d                         Zed             Zej8        eej~        dd                                    Ze:                    d d d            ddddZ'ddddZ)dS )    )annotations)partialN)castoverloadAny)jit)jvp)vmap)lax)core)custom_derivatives)deprecations)dtypes)_const)promote_args_inexactpromote_dtypes_inexact)special)betaln)Array	ArrayLike)softmax)log_softmaxxr   returnr   c                N    t          d|           \  } t          j        |           S )aL  Natural log of the absolute value of the gamma function.

  JAX implementation of :obj:`scipy.special.gammaln`.

  .. math::

     \mathrm{gammaln}(x) = \log(|\Gamma(x)|)

  Where :math:`\Gamma` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    x: arraylike, real valued.

  Returns:
    array containing the values of the log-gamma function

  See Also:
    - :func:`jax.scipy.special.gammaln`: the natural log of the gamma function
    - :func:`jax.scipy.special.gammasgn`: the sign of the gamma function

  Notes:
    ``gammaln`` does not support complex-valued inputs.
  gammaln)r   r   lgammar   s    V/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/scipy/special.pyr   r   *   s#    0 Iq))"!	A    c                    t          d|           \  } t          j        |           }t          j        | dk    | |k    z  |dz  dk    z  dd          S )am  Sign of the gamma function.

  JAX implementation of :obj:`scipy.special.gammasgn`.

  .. math::

    \mathrm{gammasgn}(x) = \begin{cases}
      +1 & \Gamma(x) > 0 \\
      -1 & \Gamma(x) < 0
    \end{cases}

  Where :math:`\Gamma` is the :func:`~jax.scipy.special.gamma` function.
  Because :math:`\Gamma(x)` is never zero, no condition is required for this case.

  Args:
    x: arraylike, real valued.

  Returns:
    array containing the sign of the gamma function

  See Also:
    - :func:`jax.scipy.special.gamma`: the gamma function
    - :func:`jax.scipy.special.gammaln`: the natural log of the gamma function
  gammasgnr            ?      )r   r   floorjnpwhere)r   floor_xs     r   r"   r"   F   sQ    2 J**"!IaLL'	AEa7l+w{a/?@#t	L	LLr    c                    t          d|           \  } t          |           t          j        t          j        |                     z  S )a  The gamma function.

  JAX implementation of :obj:`scipy.special.gamma`.

  The gamma function is defined for :math:`\Re(z)>0` as

  .. math::

     \mathrm{gamma}(z) = \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}\mathrm{d}t

  and is extended by analytic continuation to arbitrary complex values `z`.
  For positive integers `n`, the gamma function is related to the
  :func:`~jax.scipy.special.factorial` function via the following identity:

  .. math::

     \Gamma(n) = (n - 1)!

  Args:
    x: arraylike, real valued.

  Returns:
    array containing the values of the gamma function

  See Also:
    - :func:`jax.scipy.special.factorial`: the factorial function.
    - :func:`jax.scipy.special.gammaln`: the natural log of the gamma function
    - :func:`jax.scipy.special.gammasgn`: the sign of the gamma function

  Notes:
    Unlike the scipy version, JAX's ``gamma`` does not support complex-valued inputs.
  gamma)r   r"   r   expr   r   s    r   r+   r+   d   s9    B GQ''"!	!swsz!}}--	--r    abc                J    t          d| |          \  } }t          | |          S )a  Natural log of the absolute value of the beta function

  JAX implementation of :obj:`scipy.special.betaln`.

  .. math::

     \mathrm{betaln}(a, b) = \log B(a, b)

  where :math:`B` is the :func:`~jax.scipy.special.beta` function.

  Args:
    a: arraylike, real-valued.  Parameter *a* of the beta distribution.
    b: arraylike, real-valued.  Parameter *b* of the beta distribution.

  Returns:
    array containing the values of the log-beta function

  See Also:
    :func:`jax.scipy.special.beta`
  r   )r   _betaln_implr-   r.   s     r   r   r      s)    * 
h1	-	-$!Q	a		r    Fnexactboolc           
         |rt          d          t          d|           \  } t          j        | dk     dt	          j        t	          j        | dz                                 S )a  Factorial function

  JAX implementation of :obj:`scipy.special.factorial`

  .. math::

     \mathrm{factorial}(n) = n! = \prod_{k=1}^n k

  Args:
    n: arraylike, values for which factorial will be computed elementwise
    exact: bool, only ``exact=False`` is supported.

  Returns:
    array containing values of the factorial.

  Notes:
    This computes the float-valued factorial via the :func:`~jax.scipy.special.gamma`
    function. JAX does not support exact factorials, because it is not particularly
    useful: above ``n=20``, the exact result cannot be represented by 64-bit integers,
    which are the largest integers available to JAX.

  See Also:
    :func:`jax.scipy.special.gamma`
  zfactorial with exact=True	factorialr      )NotImplementedErrorr   r'   r(   r   r,   r   )r2   r3   s     r   r6   r6      s\    2  ;
9
:
::K++"!	1q5!SWSZA%6%677	8	88r    c                    d S N r1   s     r   betar<      s    /2sr    yc                   d S r:   r;   )r-   r=   s     r   r<   r<          25#r    c                    d S r:   r;   )r   r=   s     r   r<   r<      r?   r    c                    d|v rDd}t          j        d|d           d|v rt          d          |                    d          |d<   d|v rDd	}t          j        d|d           d
|v rt          d          |                    d          |d
<   |                                dd
hz
  x}rt          dt          |                     t          | i |S )a!  The beta function

  JAX implementation of :obj:`scipy.special.beta`.

  .. math::

     \mathrm{beta}(a, b) = B(a, b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a + b)}

  where :math:`\Gamma` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    a: arraylike, real-valued. Parameter *a* of the beta distribution.
    b: arraylike, real-valued. Parameter *b* of the beta distribution.

  Returns:
    array containing the values of the beta function.

  See Also:
    - :func:`jax.scipy.special.gamma`
    - :func:`jax.scipy.special.betaln`
  r   zKThe `x` parameter of jax.scipy.special.beta is deprecated, use `a` instead.zjax-scipy-beta-argsr#   )
stacklevelr-   z0beta() got both parameter 'a' and parameter 'x'.r=   zKThe `y` parameter of jax.scipy.special.beta is deprecated, use `b` instead.r.   z0beta() got both parameter 'b' and parameter 'y'.z(beta() got unexpected keyword arguments )r   warn	TypeErrorpopkeyslist_beta)argskwdsmsgextras       r   r<   r<      s    . 	D[[
WC+SQ????
d{{HIIIDID[[
WC+SQ????
d{{HIIIDIiikkS#J&&U N
LtE{{LL
M
MM				r    c                    t          d| |          \  } }t          |           t          |          z  t          | |z             z  }|t          j        t	          | |                    z  S )Nr<   )r   r"   r   r,   r   )r-   r.   signs      r   rH   rH      sY    	fa	+	+$!Q	!x{{	"Xa!e__	4$	q!%%	%%r    c                Z    t          d| ||          \  } }}t          j        | ||          S )ay  The regularized incomplete beta function.

  JAX implementation of :obj:`scipy.special.betainc`.

  .. math::

     \mathrm{betainc}(a, b, x) = B(a, b)\int_0^x t^{a-1}(1-t^{b-1})\mathrm{d}t

  where :math:`B(a, b)` is the :func:`~jax.scipy.special.beta` function.

  Args:
    a: arraylike, real-valued. Parameter *a* of the beta distribution.
    b: arraylike, real-valued. Parameter *b* of the beta distribution.
    x: arraylike, real-valued. Upper limit of the integration.

  Returns:
    array containing values of the betainc function

  See Also:
    - :func:`jax.scipy.special.beta`
    - :func:`jax.scipy.special.betaln`
  betainc)r   r   rP   r-   r.   r   s      r   rP   rP      s1    . !Aq!44'!Q	Q1		r    c                N    t          d|           \  } t          j        |           S )a  The digamma function

  JAX implementation of :obj:`scipy.special.digamma`.

  .. math::

     \mathrm{digamma}(z) = \psi(z) = \frac{\mathrm{d}}{\mathrm{d}z}\log \Gamma(z)

  where :math:`\Gamma(z)` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing values of the digamma function.

  Notes:
    The JAX version of `digamma` accepts real-valued inputs.

  See also:
    - :func:`jax.scipy.special.gamma`
    - :func:`jax.scipy.special.polygamma`
  digamma)r   r   rS   r   s    r   rS   rS     s#    0 Iq))"!	Qr    c                T    t          d| |          \  } }t          j        | |          S )a\  The regularized lower incomplete gamma function.

  JAX implementation of :obj:`scipy.special.gammainc`.

  .. math::

     \mathrm{gammainc}(x; a) = \frac{1}{\Gamma(a)}\int_0^x t^{a-1}e^{-t}\mathrm{d}t

  where :math:`\Gamma(a)` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    a: arraylike, real-valued. Positive shape parameter of the gamma distribution.
    x: arraylike, real-valued. Non-negative upper limit of integration

  Returns:
    array containing values of the gammainc function.

  See Also:
    - :func:`jax.scipy.special.gamma`
    - :func:`jax.scipy.special.gammaincc`
  gammainc)r   r   igammar-   r   s     r   rU   rU   -  s+    , 
j!Q	/	/$!Q	Aq		r    c                T    t          d| |          \  } }t          j        | |          S )ac  The regularized upper incomplete gamma function.

  JAX implementation of :obj:`scipy.special.gammaincc`.

  .. math::

     \mathrm{gammaincc}(x; a) = \frac{1}{\Gamma(a)}\int_x^\infty t^{a-1}e^{-t}\mathrm{d}t

  where :math:`\Gamma(a)` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    a: arraylike, real-valued. Positive shape parameter of the gamma distribution.
    x: arraylike, real-valued. Non-negative lower limit of integration

  Returns:
    array containing values of the gammaincc function.

  See Also:
    - :func:`jax.scipy.special.gamma`
    - :func:`jax.scipy.special.gammainc`
  	gammaincc)r   r   igammacrW   s     r   rY   rY   G  s+    , 
k1a	0	0$!Q	Q		r    c                N    t          d|           \  } t          j        |           S )a  The error function

  JAX implementation of :obj:`scipy.special.erf`.

  .. math::

     \mathrm{erf}(x) = \frac{2}{\sqrt\pi} \int_{0}^x e^{-t^2} \mathrm{d}t

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing values of the error function.

  Notes:
     The JAX version only supports real-valued inputs.

  See also:
    - :func:`jax.scipy.special.erfc`
    - :func:`jax.scipy.special.erfinv`
  erf)r   r   r\   r   s    r   r\   r\   a  s#    , E1%%"!	r    c                N    t          d|           \  } t          j        |           S )a7  The complement of the error function

  JAX implementation of :obj:`scipy.special.erfc`.

  .. math::

     \mathrm{erfc}(x) = \frac{2}{\sqrt\pi} \int_{x}^\infty e^{-t^2} \mathrm{d}t

  This is the complement of the error function :func:`~jax.scipy.special.erf`,
  ``erfc(x) = 1 - erf(x)``.

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing values of the complement of the error function.

  Notes:
     The JAX version only supports real-valued inputs.

  See also:
    - :func:`jax.scipy.special.erf`
    - :func:`jax.scipy.special.erfinv`
  erfc)r   r   r^   r   s    r   r^   r^   {  s#    2 FA&&"!	!r    c                N    t          d|           \  } t          j        |           S )a  The inverse of the error function

  JAX implementation of :obj:`scipy.special.erfinv`.

  Returns the inverse of :func:`~jax.scipy.special.erf`.

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing values of the inverse error function.

  Notes:
     The JAX version only supports real-valued inputs.

  See also:
    - :func:`jax.scipy.special.erf`
    - :func:`jax.scipy.special.erfc`
  erfinv)r   r   erf_invr   s    r   r`   r`     s#    ( Ha(("!	Qr    c                    t          d|           \  } t          j        t          j        | t          j        t          | d          |                               S )zThe logit function

  JAX implementation of :obj:`scipy.special.logit`.

  .. math::

     \mathrm{logit}(p) = \log\frac{p}{1 - p}

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing values of the logit function.
  logitr7   )r   r   logdivsub
_lax_constr   s    r   rc   rc     sG      GQ''"!	CGJq!$4$4a8899	:	::r    c                    t          j        | t          j        |t          j        t	          |d          |                              S Nr7   )r   re   mulrf   rg   )gansr   s      r   <lambda>rm     s4    cgaCGJq!4D4Da,H,H!I!IJJ r    c                N    t          d|           \  } t          j        |           S )a   The logistic sigmoid (expit) function

  JAX implementation of :obj:`scipy.special.expit`.

  .. math::

     \mathrm{expit}(x) = \frac{1}{1 + e^{-x}}

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing values of the expit function.
  expit)r   r   logisticr   s    r   ro   ro     s#     GQ''"!	ar    c           	         t          d| |          \  } }| dk    }t          j        |t          j        | t          j        |                    t          j        |                     S )a  Compute x*log(y), returning 0 for x=0.

  JAX implementation of :obj:`scipy.special.xlogy`.

  This is defined to return zero when :math:`(x, y) = (0, 0)`, with a custom
  derivative rule so that automatic differentiation is well-defined at this point.

  Args:
    x: arraylike, real-valued.
    y: arraylike, real-valued.

  Returns:
    array containing xlogy values.

  See also:
    :func:`jax.scipy.special.xlog1py`
  xlogy        )r   r'   r(   r   rj   rd   
zeros_liker   r=   x_oks      r   rr   rr     sT    ( 
gq!	,	,$!Q	
b$	4CGAJJ//1B1B	C	CCr    c                    | \  }}|\  }}t          ||          }||t          j        |          z  ||z  |z  z                       |j                  fS r:   )rr   r   rd   astypedtypeprimalstangentsr   r=   x_doty_dotresults          r   
_xlogy_jvpr     sV    &1a.5%A;;&	%#'!**$uqy1}4<<V\JJ	JJr    c           	         t          d| |          \  } }| dk    }t          j        |t          j        | t          j        |                    t          j        |                     S )a  Compute x*log(1 + y), returning 0 for x=0.

  JAX implementation of :obj:`scipy.special.xlog1py`.

  This is defined to return 0 when :math:`(x, y) = (0, -1)`, with a custom
  derivative rule so that automatic differentiation is well-defined at this point.

  Args:
    x: arraylike, real-valued.
    y: arraylike, real-valued.

  Returns:
    array containing xlog1py values.

  See also:
    :func:`jax.scipy.special.xlogy`
  xlog1pyrs   )r   r'   r(   r   rj   log1prt   ru   s      r   r   r     sT    ( 
iA	.	.$!Q	
b$	4CIaLL113>!3D3D	E	EEr    c                    | \  }}|\  }}t          ||          }||t          j        |          z  ||z  d|z   z  z                       |j                  fS ri   )r   r   r   rx   ry   rz   s          r   _xlog1py_jvpr     s[    &1a.5%1a==&	%#)A,,&a!e)<<DDV\RR	RRr    c                "    t          | |           S )z/Compute x log(x) with well-defined derivatives.)rr   r   s    r   _xlogxr     s     
q!r    c                d    | \  }|\  }t          |          |t          j        |          dz   z  fS ri   )r   r   rd   r{   r|   r   r}   s       r   
_xlogx_jvpr      s2    "!&%
))Ucgajj1n-
--r    c           	        t          d|           \  } t          j        t          j        | t	          | d                    t          j        | t          j                   t          j        t          |                               S )a  The entropy function

  JAX implementation of :obj:`scipy.special.entr`.

  .. math::

     \mathrm{entr}(x) = \begin{cases}
       -x\log(x) & x > 0 \\
       0 & x = 0\\
       -\infty & x > 0
     \end{cases}

  Args:
    x: arraylike, real-valued.

  Returns:
    array containing entropy values.

  See also:
    - :func:`jax.scipy.special.kl_div`
    - :func:`jax.scipy.special.rel_entr`
  entrr   )
r   r   selectltrg   	full_likenpinfnegr   r   s    r   r   r   '  sg    . FA&&"!	CF1jA..//M!bfW--GF1II&&
( 
( (r    dc                   t          j        t          |d          }t          d| |          \  } }t	          j        t	          j        t	          j        t          | d          |          t	          j        |t          | d                              t	          j        t          | t          j
                                      }t	          j        t          j        ||j                  t          | d                    }t          j        t!          t          j        | d          t          j        |t%          t'          | j                                      z
            d          }||z   S )	a-  The natural log of the multivariate gamma function.

  JAX implementation of :func:`scipy.special.multigammaln`.

  .. math::

     \mathrm{multigammaln}(a, d) = \log\Gamma_d(a)

  where

  .. math::

     \Gamma_d(a) = \pi^{d(d-1)/4}\prod_{i=1}^d\Gamma(a-(i-1)/2)

  and :math:`\Gamma(x)` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    a: arraylike, real-valued.
    d: int, the dimension of the integration space.

  Returns:
    array containing values of the log-multigamma function.

  See also:
    - :func:`jax.scipy.special.gamma`
  zd argument of multigammalnmultigammalng      ?r7   ry   r#   axis)r   concrete_or_errorintr   r   rj   rg   rf   rd   r   pire   r'   arangery   sumr   expand_dimstuplerangendim)r-   r   d_constantr.   ress         r   r   r   D  s1   6 S!%ABB!
~q!
4
4%!RWSWSWZ4%8%8"== WRAq)9)9::< <WZ2511224 4( 
gcj"(+++Z1-=-=>>!333eAFmm0D0DEEEF G G	 	 	# 
xr    pqc                V    t          d| |          \  } }t          | |          | z
  |z   S )a  The Kullback-Leibler divergence.

  JAX implementation of :obj:`scipy.special.kl_div`.

  .. math::

     \mathrm{kl\_div}(p, q) = \begin{cases}
       p\log(p/q)-p+q & p>0,q>0\\
       q & p=0,q\ge 0\\
       \infty & \mathrm{otherwise}
    \end{cases}

  Args:
    p: arraylike, real-valued.
    q: arraylike, real-valued.

  Returns:
    array of KL-divergence values

  See also:
    - :func:`jax.scipy.special.entr`
    - :func:`jax.scipy.special.rel_entr`
  kl_div)r   rel_entr)r   r   s     r   r   r   l  s1    6 
h1	-	-$!Q	!Q!	a	r    c           	     Z   t          d| |          \  } }t          | d          }t          j        t          j        | |          t          j        ||                    }t          j        t          j        | |          t          j        ||                    }t          j        || d          }t          j        ||d          }t          j	        t          |          t          ||                    }t          j        ||t          j        ||t          j                            }|S )a  The relative entropy function.

  JAX implementation of :obj:`scipy.special.rel_entr`.

  .. math::

     \mathrm{rel\_entr}(p, q) = \begin{cases}
       p\log(p/q) & p>0,q>0\\
       0 & p=0,q\ge 0\\
       \infty & \mathrm{otherwise}
    \end{cases}

  Args:
    p: arraylike, real-valued.
    q: arraylike, real-valued.

  Returns:
    array of relative entropy values.

  See also:
    - :func:`jax.scipy.special.entr`
    - :func:`jax.scipy.special.kl_div`
  r   rs   r7   )r   rg   r   bitwise_andgteqger'   r(   rf   r   rr   r   )	r   r   zeroboth_gt_zero_maskone_zero_masksafe_psafe_qlog_valr   s	            r   r   r     s    6 
j!Q	/	/$!Q	As		$ocfQoosvaGG/#&D//36!T??CC-9&1--&9&1--&GF6NNE&&$9$9::'9#)M4"I"I & 
-r    )   i0i v  i i gS`3l    KE gPqwg+cQ{Bg1oXU0gީ~#'Cg2HUgopyL.DgiTg"WDg.,ArrayLike | Nonec                v    |t          d          t          d| |          \  } }t          j        | |          S )aT  The Hurwitz zeta function.

  JAX implementation of :func:`scipy.special.zeta`. JAX does not implement
  the Riemann zeta function (i.e. ``q = None``).

  .. math::

     \zeta(x, q) = \sum_{n=0}^\infty \frac{1}{(n + q)^x}

  Args:
    x: arraylike, real-valued
    q: arraylike, real-valued

  Returns:
    array of zeta function values
  N[Riemann zeta function not implemented; pass q != None to compute the Hurwitz Zeta function.zeta)r8   r   r   r   )r   r   s     r   r   r     sF    $ Y
ce e e	fa	+	+$!Q	!Qr    c                6   |t          d          t          d| |          \  }}t          j        |          j        }t          j        |d          t          j        |d          }}t          j        |          t
          j        k    r |d          n
 |d          x}}|t          t                    k    sJ t          j        t          j        ||j                  t          t          |j                                      }	t          j        ||	z   | z  d          }
t          j        ||z    |d          |z
  z  | |d          z
            }||z   | z  }t          j        t          j        d|z  |j                  t          t          |j                                      }||z   ||z   z  }t          j        |d          d	d d df         }t          j        |t          j        |          j        
          }t          j        t          j        t          d |j        d                  |          t          t          |j                                      }||z  }| |d          |                    d          z   z  }|
|z   |z   S )Nr   r   r         r   r7   r#   .)max      ?)r8   r   r   ry   typer'   r   float32len_BERNOULLI_COEFSr   r   r   r   r   r   re   cumprodclipfinfor   arrayshape)r   r   sr-   ry   s_a_NMkSIT0ms_over_aT1coefsTs                     r   _zeta_series_expansionr     sG   Y
ce e e 
fa	+	+$!Q
)A,,
%?1b!!3?1b#9#9b"illck11%%(((uuRyy@!a	
c"##	#	#	#	#	obi1115qv3G3GHH!	grAv2#or""!	gq1u%%((Q,'UU1XX66!	A1"}"	obiAQW555uU16]]7K7KLL!1fa (
{8R  ccc*"
x	%((,---"
."2=BHRL="AOOOuQV}}--/ /%	Ez"EE#JJ#$!	
Qr    c                    t          j        t          j        |           t           j                  sJ t          d| |          \  }}t          j        ||          S )a  The polygamma function.

  JAX implementation of :func:`scipy.special.polygamma`.

  .. math::

     \mathrm{polygamma}(n, x) = \psi^{(n)}(x) = \frac{\mathrm{d}^n}{\mathrm{d}x^n}\log \Gamma(x)

  where :math:`\Gamma` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    n: arraylike, integer-valued. The order of the derivative.
    x: arraylike, real-valued. The value at which to evaluate the function.

  Returns:
    array

  See also:
    - :func:`jax.scipy.special.gamma`
    - :func:`jax.scipy.special.digamma`
  	polygamma)r'   
issubdtyper   ry   integerr   r   )r2   r   n_arrx_arrs       r   r   r     sM    , 
	!ck	2	2222%k1a88,%	ue	$	$$r    iir      c                    t          j        |           } t          j        |           }|t           j        t           j        fvr"t          d                    |                    t          |           S )ac  Normal distribution function.

  JAX implementation of :obj:`scipy.special.ndtr`.

  Returns the area under the Gaussian probability density function, integrated
  from minus infinity to x:

  .. math::
    \begin{align}
    \mathrm{ndtr}(x) =&
      \ \frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{x} e^{-\frac{1}{2}t^2} dt \\
    =&\ \frac{1}{2} (1 + \mathrm{erf}(\frac{x}{\sqrt{2}})) \\
    =&\ \frac{1}{2} \mathrm{erfc}(\frac{x}{\sqrt{2}})
    \end{align}

  Args:
    x: An array of type `float32`, `float64`.

  Returns:
    An array with `dtype=x.dtype`.

  Raises:
    TypeError: if `x` is not floating-type.
  ?x.dtype={} is not supported, see docstring for supported types.)	r'   asarrayr   ry   r   float64rD   format_ndtrr   ry   s     r   ndtrr   l  s_    2 
k!nn!
)A,,%
3;,,,
I	   
q/r    c                   t          j        |           j        } |d          t          j        d|          z  }| |z  }t          j        |          }t          j        t          j        ||           |d          t          j        |          z   t          j        t          j	        | |d                     |d          t          j
        |          z
  t          j
        |                              } |d          |z  S )zImplements ndtr core logic.r          @r   r$   rs   )r   ry   r   r   sqrtabsr   r   r\   r   r^   )r   ry   half_sqrt_2wzr=   s         r   r   r     s    
)A,,
%c

RWRu5555++o!	gajj!	j;''eBii#'!**,j5599!5!5&+eBii#(1++&=&)hqkk3 34 4!
 
sar    c                    t          j        |           }|t          j        t          j        fvr"t          d                    |                    t          |           S )a  The inverse of the CDF of the Normal distribution function.

  JAX implementation of :obj:`scipy.special.ndtri`.

  Returns `x` such that the area under the PDF from :math:`-\infty` to `x` is equal
  to `p`.

  A piece-wise rational approximation is done for the function.
  This is based on the implementation in netlib.

  Args:
    p: an array of type `float32`, `float64`.

  Returns:
    an array with `dtype=p.dtype`.

  Raises:
    TypeError: if `p` is not floating-type.
  r   )r   ry   r'   r   r   rD   r   _ndtri)r   ry   s     r   ndtrir     sS    ( )A,,%
3;,,,
I	   
r    c           
     2   t          t          g d                    }t          t          g d                    }t          t          g d                    }t          t          g d                    }t          t          g d                    }t          t          g d                    }t          j        |           j        t          j        |           }fdt          j        |  t          j	        d                     k     d	          | z
  |           }t          j        | d
          k    t          j
        | d                    |          }	|	 d          z
  }
t          j        |
          }|
|
|z   ||           ||          z  z  z   }| t          j        dt          j        z                       z  }t          j         d          t          j        |	          z            }|t          j        |          |z  z
  }  d	          |z  |            d	          |z  |          z  |z  }  d	          |z  |            d	          |z  |          z  |z  }||z
  }||z
  }t          j        |	 t          j        d                    k    |t          j        | d          k    ||                    }t          j        |  d	t          j        d          z
            k    ||           }t          j
        | t          j                            }t          j        |  d
          k    | t          j        |  d	          k    ||                    }|S )zImplements ndtri core logic.)g-^OMgX@gVLg;+@g~)	r$   gt ҕE?g@gԁ5U@g_6V.lgSi@gٷaTgcu/@gͿ)	gێ<8@gyՒm?@gBהL@gN
F@g>F^-@glz9~@gwDgAcglL)	r$   g;Z/@go)F@gF"D@gE؇.@g <	@g23¿gmENg}yN)	gtՓ	@gx'1@g+@gT?gQ&^E?gM5iPV?g3?g4"L)L>gX0:>)	r$   g(V@g8ҪMp@g b*G?g<_?gǶ'|?g)e+5?gC>g=kv)=>c                    t          j        |          }|j        st          j        |           S |d          | |dd                   | z  z   S )z2Compute n_th order polynomial via Horner's method.r   r7   N)r   r   sizer'   rt   )varcoeffs_create_polynomialry   s     r   r   z"_ndtri.<locals>._create_polynomial  sX    Xfe$$F; !^C   !9))#vabbz::S@@@r    g       r$   rs   r   r   g       @)rG   reversedr   ry   r   r'   r   r(   r   expm1fullsquarer   r   rd   r,   r   )r   p0q0p1q1p2q2r   maybe_complement_psanitized_mcpr   wwx_for_big_pr   
first_termsecond_term_small_psecond_term_otherwisex_for_small_px_otherwiser   infinityx_fix_boundariesr   ry   s                         @@r   r   r     s    H 1 1 1 2 2 3 3"
 H 1 1 1 2 2 3 3" H 2 2 2 3 3 4 4" H 2 2 2 3 3 4 4" H 1 1 1 2 2 3 3" H 1 1 1 2 2 3 3" )A,,
%
)A,,%A A A A A A yUUBHSMM>%:%:!:EE"IIM1MM )EE"II%	hueeCjj!! - eeCjj !
z!}}"AF00R88 2 22r : :; < <+%%RU
++,,,,+
 
huuSzzCGM22233!371::>!*rQ++rQ++,./0  rQ++rQ++,./0  22-22+	ibfSkk 2 22	!uuSzz/=+FFH H! 
iEE"rvc{{*+++Q33!XeUU26]]++(Y55::oy#)AsOXq"I"IK K	r    )r7   )nondiff_argnums   series_orderr   c                   t          |t                    st          d          |dk     rt          d          |dk    rt          d          t	          j        |           }t          j        |          }|t          j        k    rt          }t          }nD|t          j        k    rt          }t          }n%t          dt          j        |           d          t	          j        t          j        ||          t#          |            t	          j        t          j        ||          t          j        t#          t          j        ||                              t)          t          j        ||          |                              S )a  Log Normal distribution function.

  JAX implementation of :obj:`scipy.special.log_ndtr`.

  For details of the Normal distribution function see `ndtr`.

  This function calculates :math:`\log(\mathrm{ndtr}(x))` by either calling
  :math:`\log(\mathrm{ndtr}(x))` or using an asymptotic series. Specifically:

  - For `x > upper_segment`, use the approximation `-ndtr(-x)` based on
    :math:`\log(1-x) \approx -x, x \ll 1`.
  - For `lower_segment < x <= upper_segment`, use the existing `ndtr` technique
    and take a log.
  - For `x <= lower_segment`, we use the series approximation of `erf` to compute
    the log CDF directly.

  The `lower_segment` is set based on the precision of the input:

  .. math::
    \begin{align}
    \mathit{lower\_segment} =&
      \ \begin{cases}
        -20 &  x.\mathrm{dtype}=\mathit{float64} \\
        -10 &  x.\mathrm{dtype}=\mathit{float32} \\
        \end{cases} \\
    \mathit{upper\_segment} =&
      \ \begin{cases}
        8&  x.\mathrm{dtype}=\mathit{float64} \\
        5&  x.\mathrm{dtype}=\mathit{float32} \\
        \end{cases}
    \end{align}


  When `x < lower_segment`, the `ndtr` asymptotic series approximation is:

  .. math::
    \begin{align}
     \mathrm{ndtr}(x) =&\  \mathit{scale} * (1 + \mathit{sum}) + R_N \\
     \mathit{scale}   =&\  \frac{e^{-0.5 x^2}}{-x \sqrt{2 \pi}} \\
     \mathit{sum}     =&\  \sum_{n=1}^N {-1}^n (2n-1)!! / (x^2)^n \\
     R_N     =&\  O(e^{-0.5 x^2} (2N+1)!! / |x|^{2N+3})
    \end{align}

  where :math:`(2n-1)!! = (2n-1) (2n-3) (2n-5) ...  (3) (1)` is a
  `double-factorial
  <https://en.wikipedia.org/wiki/Double_factorial>`_ operator.


  Args:
    x: an array of type `float32`, `float64`.
    series_order: Positive Python integer. Maximum depth to
      evaluate the asymptotic expansion. This is the `N` above.

  Returns:
    an array with `dtype=x.dtype`.

  Raises:
    TypeError: if `x.dtype` is not handled.
    TypeError: if `series_order` is a not Python `integer.`
    ValueError:  if `series_order` is not in `[0, 30]`.
  z&series_order must be a Python integer.r   z"series_order must be non-negative.   zseries_order must be <= 30.x.dtype=z is not supported.)
isinstancer   rD   
ValueErrorr'   r   r   ry   r   _LOGNDTR_FLOAT64_LOWER_LOGNDTR_FLOAT64_UPPERr   _LOGNDTR_FLOAT32_LOWER_LOGNDTR_FLOAT32_UPPERr   r(   r   r   rd   r   _log_ndtr_lowermin)r   r  r   ry   lower_segmentupper_segments         r   log_ndtrr  %  sX   ~ 
L#	&	& >
<
=
==A
9
:
::B
2
3
33
+a..%
)E

%
ck 6M 6MM*M*MM
BrxBBB
C
CC  
	fUM""eV}}n	ium,,wuSWUM%B%BCCDD&swum'D'D'35 56 6
7 
7 7r    c           
         ||c\  }\  }t          ||           }t          j        |t          j        t          j        t          |          |                              }||fS )N)r  )r  r   rj   r,   rf   _norm_logpdf)r  r{   r|   r   trl   t_outs          r   _log_ndtr_jvpr!    sZ    *$1...#
'!SWSW\!__c::;;
<
<%	er    c                L   t          j        |           j        }t          j        |           } |d           |z  t          j        |            z
   |dt          j        dt
          j        z            z            z
  }|t          j        t          | |                    z   S )zGAsymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.r   r   )r   ry   r   r   rd   r   r   _log_ndtr_asymptotic_series)r   r  ry   x_2	log_scales        r   r  r    s    
)A,,
%
1#uSzzkC#'1"++-cBF2:<N<N6N0O0OO)	SW8LIIJJ	JJr    c                   t          j        |           j        }|dk    rt          j        d|          S t          j        |           }t          j        |           }t          j        |           }|}t          d|dz             D ]B}t          j        t          d|z  dz
            |          |z  }|dz  r||z  }n||z  }||z  }C |d          |z   |z
  S )z2Calculates the asymptotic series used in log_ndtr.r   r7   r#   r$   )
r   ry   r   r   r   r   r'   rt   r   _double_factorial)	r   r  ry   r$  even_sumodd_sumx_2nr2   r=   s	            r   r#  r#    s    
)A,,
%Q8Au
1#^A(N1'	$L1$%%  a
"1q519--u55<A1u lgg!mhCKDD	rX		''r    
np.ndarrayc                R    t          j        t          j        | dd                    S )z;The double factorial function for small Python integer `n`.r7   )r   prodr   )r2   s    r   r'  r'    s     	1a$$	%	%%r    r#   c                    t          | d          }t          | t                    }t          j        t          j        |t          j        |                     |          S )N      )rg   _norm_logpdf_constantr   rf   rj   r   )r   neg_halflog_normalizers      r   r  r    sG    4  (a!677.	3:a==11>	B	BBr    c                N    t          d|           \  } t          j        |           S )a  Exponentially scaled modified bessel function of zeroth order.

  JAX implementation of :obj:`scipy.special.i0e`.

  .. math::

     \mathrm{i0e}(x) = e^{-|x|} I_0(x)

  where :math:`I_0(x)` is the modified Bessel function :func:`~jax.scipy.special.i0`.

  Args:
    x: array, real-valued

  Returns:
    array of bessel function values.

  See also:
    - :func:`jax.scipy.special.i0`
    - :func:`jax.scipy.special.i1`
    - :func:`jax.scipy.special.i1e`
  i0e)r   r   
bessel_i0er   s    r   r5  r5    %    , E1%%"!			r    c                    t          d|           \  } t          j        t          j        t          j        |                     t          j        |                     S )a  Modified bessel function of zeroth order.

  JAX implementation of :obj:`scipy.special.i0`.

  .. math::

     \mathrm{i0}(x) = I_0(x) = \sum_{k=0}^\infty \frac{(x^2/4)^k}{(k!)^2}

  Args:
    x: array, real-valued

  Returns:
    array of bessel function values.

  See also:
    - :func:`jax.scipy.special.i0e`
    - :func:`jax.scipy.special.i1`
    - :func:`jax.scipy.special.i1e`
  i0)r   r   rj   r,   r   r6  r   s    r   r9  r9    C    ( D!$$"!	$$cnQ&7&7	8	88r    c                N    t          d|           \  } t          j        |           S )a  Exponentially scaled modified bessel function of first order.

  JAX implementation of :obj:`scipy.special.i1e`.

  .. math::

     \mathrm{i1e}(x) = e^{-|x|} I_1(x)

  where :math:`I_1(x)` is the modified Bessel function :func:`~jax.scipy.special.i1`.

  Args:
    x: array, real-valued

  Returns:
    array of bessel function values

  See also:
    - :func:`jax.scipy.special.i0`
    - :func:`jax.scipy.special.i0e`
    - :func:`jax.scipy.special.i1`
  i1e)r   r   
bessel_i1er   s    r   r<  r<    r7  r    c                    t          d|           \  } t          j        t          j        t          j        |                     t          j        |                     S )a  Modified bessel function of first order.

  JAX implementation of :obj:`scipy.special.i1`.

  .. math::

     \mathrm{i1}(x) = I_1(x) = \frac{1}{2}x\sum_{k=0}^\infty\frac{(x^2/4)^k}{k!(k+1)!}

  Args:
    x: array, real-valued

  Returns:
    array of bessel function values

  See also:
    - :func:`jax.scipy.special.i0`
    - :func:`jax.scipy.special.i0e`
    - :func:`jax.scipy.special.i1e`
  i1)r   r   rj   r,   r   r=  r   s    r   r?  r?  	  r:  r    c                    | \  }}}}d|dz   z  |z  |z  |z
  }d }d }t          j        t          j        |d          dk    ||||f          }|}|}||||f|fS )Nr   r$   c                    | \  }}|d|z  z   S )Nr   r;   )ubsfs      r   true_fn_update_bsz3_bessel_jn_scan_body_fun.<locals>.true_fn_update_bs$  s    EBa<r    c                    | \  }}|S r:   r;   )rB  rC  _s      r   false_fn_update_bsz4_bessel_jn_scan_body_fun.<locals>.false_fn_update_bs(  s    EBIr    r#   r   )operand)r   condr'   mod)	carryr   f0f1rC  r   rD  rE  rH  s	            r   _bessel_jn_scan_body_funrO     s    -"b"a	QWoQ#!     x1"$5"RG5 5 5" 
""
b"a!	r    2   )n_iterr   vrQ  c          	     b   t          | d          }t          | d          }t          | d          }t          | d          }t          j        t          |||| ft          j        t          j        |           |dz             d          \  \  }}}}}|d         }|d |dz            }|||z
  z  }|S )Nrs   gؗҜ<r7   T)rD  initxsreverser   )rg   r   scanrO  iotary   )	r   rR  rQ  rM  rN  rD  rC  rG  j_valss	            r   
_bessel_jnrZ  4  s    !S"!U"C!!S"( BA	#)A,,q	)	)49 9 9-1aQ Qi!$1Q3$<&R!V&	-r    )static_argnamesc                  t          j        |           } t          |           \  } t          j        |           }t          j        |t                    rt          d          t          j
        t          j        |d          }t          j
        t          |d          }t          t          ||          }t!          | j                  D ]}t%          |          }t          j         ||           dd          S )a  Bessel function of the first kind of integer order and real argument.

  Reference:
  Shanjie Zhang and Jian-Ming Jin. Computation of special functions.
  Wiley-Interscience, 1996.

  Args:
    z: The sampling point(s) at which the Bessel function of the first kind are
      computed.
    v: The order (int) of the Bessel function.
    n_iter: The number of iterations required for updating the function
      values. As a rule of thumb, `n_iter` is the smallest nonnegative integer
      that satisfies the condition
      `int(0.5 * log10(6.28 + n_iter) - n_iter *  log10(1.36 + abs(z) / n_iter)) > 20`.
      Details in `BJNDD` (https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.f)

  Returns:
    An array of shape `(v+1, *z.shape)` containing the values of the Bessel
    function of orders 0, 1, ..., v. The return type matches the type of `z`.

  Raises:
    TypeError if `v` is not integer.
    ValueError if elements of array `z` are not float.
  zcomplex input not supported.zArgument v of bessel_jn.zArgument n_iter of bessel_jn.)rR  rQ  r   r   )r'   r   r   r   ry   r   r   complexr  r   r   operatorindexr   r   rZ  r   r   r
   moveaxis)r   rR  rQ  z_dtypebessel_jn_funrG  s         r   	bessel_jnrc  E  s    4 
k!nn!a  "!IaLL'w(( 5
3
4
44
X^Q0JKK!!#v/NOO&*&999-== ( (a''MM	mmA&&A	.	..r    l_maxis_normalizedry   r   tuple[Array, Array]c                   t          j        t          j        | dz   |          t          j        | dz   |          d          \  }}|rd||z  }||z  }d|z  }|dz
  |dz
  z  }t          j        d|z  dz
  ||z
  z            }	t          j        |dz   ||z
  z  |dz
  ||z
  z  z            }
nd|z  dz
  ||z
  z  }	||z   dz
  ||z
  z  }
t          j        | dz   d          }t          j        | dz   d	          }t          j        | dz   | dz   f|          }|j        |                             |	|                   }|j        |                             |
|                   }t           j        d
| dz   d
| dz   d
| dz   f         \  }}}||z   |z
  dk    	                    |          }t          j
        d||          }t          j
        d||          }||fS )a  Generates a mask for recurrence relation on the remaining entries.

  The remaining entries are with respect to the diagonal and offdiagonal
  entries.

  Args:
    l_max: see `gen_normalized_legendre`.
    is_normalized: True if the recurrence mask is used by normalized associated
      Legendre functions.

  Returns:
    Arrays representing the mask used by the recurrence relations.
  r7   r   ijindexingr   r$   g      @      @r#   Nr   zjk,ijk->ijk)r'   meshgridr   r   triu_indiceszerosatsetogridrx   einsum)rd  re  ry   m_matl_matc0c1c2c3d0d1d0_mask_indicesd1_mask_indicesd_zerosd0_maskd1_maskijr   mask
d0_mask_3d
d1_mask_3ds                         r   _gen_recurrence_maskr  n  s   $ Juqy&&&Juqy&&&  ,%  	1	B	B	uB
#+%#+	&B	38c>b2g.	/	/B	BHb)rCxBG.DE	F	FBB
+
	.B
%-#
%%-	0B$UQY22/$UQY22/Iuqy%!),E:::'J'++B,?@@'J'++B,?@@' Ijuqyj*519*juqyj89'!Q
a%!)q.	 	 	'	'$z-$77*z-$77*
j	!!r    )static_argnumsc           	     	   | j         \  }}}t          j        | d          ddd|ddf         }t          j        |d          d|dz   ddddf         }t          j        |d          d|ddddf         }|rt          d          |dk    ryt          j        d|dz
  |j                  }	| dd|dz
  ddf         }
d	|	dz   |	z  z  }t          j        d
||
          }|j        dd|ddf                             |          }|dk    rt          j        d|dz
  |j                  }	| dd|dz
  ddf         }d|	dz   |	dz   z  |	z  |	dz
  z  z  }t          j        d
||          }|j        dd|ddf                             |          }t          j	        t          j        ||j                  t          j        ||j                  d          \  }}t          j
        ||f|j                  }t          j        |d|          }t          j
        |f|j                  }d|dz
  z  }|j        |                             ||                   }|j        dddf                             |          }||z   }||dz
  z  |dz
  z  }|j        |                             ||                   }|j        dddf                             |          }t          j        d||          t          j        d||          z   }d|dz   z  }|j        |                             ||                   }||z  |dz   z  }|j        |                             ||                   }t          j        d||          t          j        d||          z   }|||z
  dz   z  dz  }|j        |                             ||                   } t          j        d| |          d|z  z
  }!|dk    rt          j        || j                  }	t          j        d
|	dz   |	z  | dddddf                   }"|dk    r|"| dddddf         z
  }"t          j        ddt          j        d||z  z
            z  |"          }#|!j        dddddf                             |#          }!|!j        ddddf                             d          }!|!S )a  Generates derivatives of associated Legendre functions of the first kind.

  Args:
    p: The 3D array containing the values of associated Legendre functions; the
      dimensions are in the sequence of order (m), degree (l), and evaluation
      points.
    x: A vector of type `float32` or `float64` containing the sampled points.
    is_normalized: True if the associated Legendre functions are normalized.
  Returns:
    The 3D array representing the derivatives of associated Legendre functions
    of the first kind.
  )r   r   )r7   r   r  N)r   r#   r  r  r#   ))r#   r   r  r  z9Negative orders for normalization is not implemented yet.r7   r   r%   i,ij->ijr$   r   r  rh  ri  r0  r   ij,ijk->ijkr   zj,ij->ij)r   r'   padr8   r   ry   rr  ro  rp  rl  rn  rm  r   )$r   r   re  num_mnum_lnum_xp_m_lm1	p_mp2_lm1	p_mm2_lm1l_vecp_p1coeffupdate_p_p1p_p2update_p_p2rs  rt  coeff_zerosupper_0_indiceszero_veca0	a0_maskedb0ru  	c0_maskedp_mm1_lry  	d0_maskede0	e0_maskedp_mp1_lrM  	f0_maskedp_derivativeg0p_derivative_m0s$                                       r   _gen_derivativesr    s%   " % GA/00FUFAAA>' gg788519aaa9JK) gg788%AAAF)  ?
CE E E qyyjEAIQW555eq!EAI+qqq !duqyE)*eJz5$77k,q!E'111}-11+>>iqyyjEAIQW555eq!EAI+qqq !deaiEAI.6%!)DEeJz5$77k,q!E'111}-11+>>iJuAG$$$JuAG$$$  ,%
 	5%.888+$UAu55/Yxqw///(us{"n_-11"_2EFF)l1aaa4 $$X..)u}"	R#X"s(#"n_-11"_2EFF)l1aaa4 $$X..) Zy'::Zy)<<=' us{"n_-11"_2EFF)	Bw"s("n_-11"_2EFF) Zy)<<Zy'::;' 
UU]S !C'"n_-11"_2EFF)M9g>>wN, QYYJuAG,,,E	Je 3Qq!!!QQQwZ	@	@Bqyy1aaa7bjS38AAI3F3F-FKKO?1aaa7+//@@L?1a7+//22L	r    r  c           	        t          j        | dz   | dz   j        d         fj                  }t          j        d| dz   j                  }t          j        | j                  }|rkdt          j        t           j                  z  }t          j        dt          j        dd|z  z             z            }t          j        d|z  dz             }n$d}t          j        dd|z  z
            }d|z  dz   }|j        d	         	                    |          }t          j        t          j
        t          j        dz  z
            | j        d         f          d
          }	|t          j        d||	          z  }
t          j        | dz             }|j        |d         dd         |d         dd         f         	                    |
          }t          j        dt          j        d|          |t          j        |                              }|d         d|          |d         d|          dz   f}|j        |         	                    |          }t          | |j                  \  fd}|                    t          j        |                    }| dk    rt!          j        d| dz   ||          }|S )u
  Computes associated Legendre functions (ALFs) of the first kind.

  The ALFs of the first kind are used in spherical harmonics. The spherical
  harmonic of degree `l` and order `m` can be written as
  `Y_l^m(θ, φ) = N_l^m * P_l^m(cos(θ)) * exp(i m φ)`, where `N_l^m` is the
  normalization factor and θ and φ are the colatitude and longitude,
  respectively. `N_l^m` is chosen in the way that the spherical harmonics form
  a set of orthonormal basis functions of L^2(S^2). For the computational
  efficiency of spherical harmonics transform, the normalization factor is
  used in the computation of the ALFs. In addition, normalizing `P_l^m`
  avoids overflow/underflow and achieves better numerical stability. Three
  recurrence relations are used in the computation.

  Args:
    l_max: The maximum degree of the associated Legendre function. Both the
      degrees and orders are `[0, 1, 2, ..., l_max]`.
    x: A vector of type `float32`, `float64` containing the sampled points in
      spherical coordinates, at which the ALFs are computed; `x` is essentially
      `cos(θ)`. For the numerical integration used by the spherical harmonics
      transforms, `x` contains the quadrature points in the interval of
      `[-1, 1]`. There are several approaches to provide the quadrature points:
      Gauss-Legendre method (`scipy.special.roots_legendre`), Gauss-Chebyshev
      method (`scipy.special.roots_chebyu`), and Driscoll & Healy
      method (Driscoll, James R., and Dennis M. Healy. "Computing Fourier
      transforms and convolutions on the 2-sphere." Advances in applied
      mathematics 15, no. 2 (1994): 202-250.). The Gauss-Legendre quadrature
      points are nearly equal-spaced along θ and provide exact discrete
      orthogonality, (P^m)^T W P_m = I, where `T` represents the transpose
      operation, `W` is a diagonal matrix containing the quadrature weights,
      and `I` is the identity matrix. The Gauss-Chebyshev points are equally
      spaced, which only provide approximate discrete orthogonality. The
      Driscoll & Healy quadrature points are equally spaced and provide the
      exact discrete orthogonality. The number of sampling points is required to
      be twice as the number of frequency points (modes) in the Driscoll & Healy
      approach, which enables FFT and achieves a fast spherical harmonics
      transform.
    is_normalized: True if the associated Legendre functions are normalized.
      With normalization, `N_l^m` is applied such that the spherical harmonics
      form a set of orthonormal basis functions of L^2(S^2).

  Returns:
    The 3D array of shape `(l_max + 1, l_max + 1, len(x))` containing the values
    of the ALFs at `x`; the dimensions in the sequence of order, degree, and
    evaluation points.
  r7   r   r   r   r   r$   r   rk  r  r   r  Nz	ij,ij->ijzi,j->ij)re  ry   c                   |          }|          }t          j        d|t          j        dt          j        |dd                              t          j        d|t          j        |dd                    z
  }||z   }|S )Nr  z
ijk,k->ijkr7   )shiftr   r#   )r'   rr  roll)r  p_valcoeff_0coeff_1hr  r  r   s        r   body_funz*_gen_associated_legendre.<locals>.body_funT  s    mGmG	MJ$chuAA&F&F&FK K
L 
L 
M7CHU!!,L,L,L	M	M	
NA
 AIELr    r#   )lowerupperr  init_val)r'   rn  r   ry   r   r   r   r   ro  rp  broadcast_torr  diag_indicesr  rx   result_typer   	fori_loop)rd  r   re  r   a_idxb_idxinitial_valuef_af_br=   p_diagr  	p_offdiagoffdiag_indicesr  r  r  s    `             @@r   _gen_associated_legendrer    s   b 
iEAIqwqz2!'BBB!
*Q	
1
1
1%
*U!'
*
*
*% "SXcf%5%55M
+b38C#+$5666
7
7C
(3;$
%
%CCM
+cC%K'
(
(C
+
Cd6l}%%! 
k	sxa!e,,uagaj.ABB  ! 3:j#q999&!%!),,,dLOABBa!456::6BB! jIsA663+E2235 5) "!_VeV,l1ofuf.E.IJ/d?	**! 0=9 9 9*j	 	 	 	 	 	 	 hhsq!Z0011!
QYYAU1Wx!LLLA	
(r    r   c                   t          j        |          }|t          j        t          j        fvr"t          d                    |                    |j        dk    rt          d          t          j
        t          | d          } t          j
        t          |d          }| |k    rt          d          |}d}t          |||          }t          |||          }||fS )aH  The associated Legendre functions (ALFs) of the first kind.

  Args:
    m: The maximum order of the associated Legendre functions.
    n: The maximum degree of the associated Legendre function, often called
      `l` in describing ALFs. Both the degrees and orders are
      `[0, 1, 2, ..., l_max]`, where `l_max` denotes the maximum degree.
    z: A vector of type `float32` or `float64` containing the sampling
      points at which the ALFs are computed.

  Returns:
    A 2-tuple of 3D arrays of shape `(l_max + 1, l_max + 1, len(z))` containing
    the values and derivatives of the associated Legendre functions of the
    first kind. The return type matches the type of `z`.

  Raises:
    TypeError if elements of array `z` are not in (float32, float64).
    ValueError if array `z` is not 1D.
    NotImplementedError if `m!=n`.
  ?z.dtype={} is not supported, see docstring for supported types.r7   z must be a 1D array.Argument m of lpmn.Argument n of lpmn.,Computations for m!=n are not yet supported.F)r   ry   r'   r   r   rD   r   r   r  r   r   r   r8   r  r  )r   r2   r   ry   rd  re  p_valsp_derivativess           r   lpmnr  g  s    * )A,,%
3;,,,
I	   Vq[[
,
-
--
S!%:;;!
S!%:;;!!VV
L
M
MM
%-#E1m<<&"61m<<-
-	  r    c                   t          j        |          }|t          j        t          j        fvr"t          d                    |                    |j        dk    rt          d          t          j
        t          | d          } t          j
        t          |d          }| |k    rt          d          |}t          |||          S )u}  The associated Legendre functions (ALFs) of the first kind.

  Unlike `lpmn`, this function only computes the values of ALFs.
  The ALFs of the first kind can be used in spherical harmonics. The
  spherical harmonic of degree `l` and order `m` can be written as
  :math:`Y_l^m(\theta, \phi) = N_l^m * P_l^m(\cos \theta) * \exp(i m \phi)`,
  where :math:`N_l^m` is the normalization factor and θ and φ are the
  colatitude and longitude, respectively. :math:`N_l^m` is chosen in the
  way that the spherical harmonics form a set of orthonormal basis function
  of :math:`L^2(S^2)`. Normalizing :math:`P_l^m` avoids overflow/underflow
  and achieves better numerical stability.

  Args:
    m: The maximum order of the associated Legendre functions.
    n: The maximum degree of the associated Legendre function, often called
      `l` in describing ALFs. Both the degrees and orders are
      `[0, 1, 2, ..., l_max]`, where `l_max` denotes the maximum degree.
    z: A vector of type `float32` or `float64` containing the sampling
      points at which the ALFs are computed.
    is_normalized: True if the associated Legendre functions are normalized.
      With normalization, :math:`N_l^m` is applied such that the spherical
      harmonics form a set of orthonormal basis functions of :math:`L^2(S^2)`.

  Returns:
    A 3D array of shape `(l_max + 1, l_max + 1, len(z))` containing
    the values of the associated Legendre functions of the first kind. The
    return type matches the type of `z`.

  Raises:
    TypeError if elements of array `z` are not in (float32, float64).
    ValueError if array `z` is not 1D.
    NotImplementedError if `m!=n`.
  r  r7   r  r  r  r  )r   ry   r'   r   r   rD   r   r   r  r   r   r   r8   r  )r   r2   r   re  ry   rd  s         r   lpmn_valuesr    s    D )A,,%
3;,,,
I	   Vq[[
,
-
--
S!%:;;!
S!%:;;!!VV
L
M
MM
%	!%M	:	::r    )   thetaphin_maxc                   t          j        |          }t          ||d          }|j        t	          |           |t          j        t          |                    f                             d          }t	          |           |z  }t          j	        t          j        |          t          j
        |                    }	t          j	        |t          j        |	          z  |t          j        |	          z            }
t          j        | dk     dt	          |           z  t          j        |
          z  |
          }
|
S )z!Computes the spherical harmonics.Tr   )moder   r%   )r'   cosr  ro  r   r   r   getr   r]  sinrealimagr(   	conjugate)r   r2   r  r  r  cos_colatitudelegendrelegendre_valanglevandermonde	harmonicss              r   	_sph_harmr    s    73<<.%e^TBB(SVVQ
3q66(:(::;??V?LL,
a&&5.%CGENNCGENN;;+k,+)>)>>&+)>)>>@ @) iAAy)A)AA!# #) 
r    
int | Nonec                    t          j        |          rt          j        |g          }|t          j        |          }t          j        t          |d          }t          | ||||          S )a  Computes the spherical harmonics.

  The JAX version has one extra argument `n_max`, the maximum value in `n`.

  The spherical harmonic of degree `n` and order `m` can be written as
  :math:`Y_n^m(\theta, \phi) = N_n^m * P_n^m(\cos \phi) * \exp(i m \theta)`,
  where :math:`N_n^m = \sqrt{\frac{\left(2n+1\right) \left(n-m\right)!}
  {4 \pi \left(n+m\right)!}}` is the normalization factor and :math:`\phi` and
  :math:`\theta` are the colatitude and longitude, respectively. :math:`N_n^m` is
  chosen in the way that the spherical harmonics form a set of orthonormal basis
  functions of :math:`L^2(S^2)`.

  Args:
    m: The order of the harmonic; must have `|m| <= n`. Return values for
      `|m| > n` are undefined.
    n: The degree of the harmonic; must have `n >= 0`. The standard notation for
      degree in descriptions of spherical harmonics is `l (lower case L)`. We
      use `n` here to be consistent with `scipy.special.sph_harm`. Return
      values for `n < 0` are undefined.
    theta: The azimuthal (longitudinal) coordinate; must be in [0, 2*pi].
    phi: The polar (colatitudinal) coordinate; must be in [0, pi].
    n_max: The maximum degree `max(n)`. If the supplied `n_max` is not the true
      maximum value of `n`, the results are clipped to `n_max`. For example,
      `sph_harm(m=jnp.array([2]), n=jnp.array([10]), theta, phi, n_max=6)`
      actually returns
      `sph_harm(m=jnp.array([2]), n=jnp.array([6]), theta, phi, n_max=6)`
  Returns:
    A 1D array containing the spherical harmonics at (m, n, theta, phi).
  NzThe `n_max` argument of `jnp.scipy.special.sph_harm` must be statically specified to use `sph_harm` within JAX transformations.)	r'   isscalarr   r   r   r   r   r   r  )r   r2   r  r  r  s        r   sph_harmr    sq    F 	\# 
)SE

C
]F1IIE

 	5 NO O% 
1aU	+	++r    c                "   g d}g d}t          j        || j                  }t          j        || j                  }t          j        ||           t          j        ||           z  }| |z  t           j        z   t          j        |           z   S )N)gfgrG(Pk@g`χPg>x@gN	P(9煘)3M8A)r$   gX$@JgEv@g_'g鏱9Ag-C&r  r   )r'   r   ry   polyvaleuler_gammard   )r   ABA_arrB_arrrD  s         r   _expint1r    s      !  ! )AQW
%
%
%%
)AQW
%
%
%%	k%ck%333!	
Q	 371::	--r    r  list[float]r  c                2   t          j        | |j                  }t          j        ||j                  }t          |d          }||z  }t          j        ||          t          j        ||          z  }||z  |z   }t          j        |          |z  |z  S )Nr   r$   )r'   r   ry   rg   r  r,   )r  r  r   r  r  oner   rD  s           r   _eval_expint_kr  2  s    
)AQW
%
%
%%
)AQW
%
%
%%1c#	Ag!	k%ck%333!!eck!	a!	r    c                4    g d}g d}t          |||           S )N)g`V,1K?gN{Xg+qg gmZ@g0$N8ܿg=S?g`PYg,n߁?)r$   gA?gE]l?gIUW?gScjw?gY)R:r?gSS&?gٹ?r  r   r  r  s      r   _expint2r  =  s8    	 	 	!	 	 	! 
1a	 	  r    c                4    g d}g d}t          |||           S )N)g󲛯g/Sg!J?gwh]Lпga*\?g*reQgL?gr>)	r$   giy?gT]j?g\?gw.?gTp1L?gxV>?gТӾgv[>r  r  s      r   _expint3r  V  8    	 	 	!
 
 
! 
1a	 	  r    c                4    g d}g d}t          |||           S )N)
gܞH  gn&G?gDϿg(Kȗ?go /?g}$4
gJԼǾ>gGW󇘾g3uO>g^]h8>)
r$   g$>:TJjͿgD;J?g`0
gO. uf?gTzb+g٨%L>gR*
흾gBw6,M>gl\[">r  r  s      r   _expint4r  p  s8      !  ! 
1a	 	  r    c                4    g d}g d}t          |||           S )N)gvϿg5F9¿g	?%=?gg V?g4gP/CU.>g/f)	r$   g9\pg\!ѿgE{H"Ѹ?gOVfgiCkX?g.G/g[Y>gZ<fr  r  s      r   _expint5r    r  r    c                4    g d}g d}t          |||           S )N)g
?g[Og}?g$ D!g[X?g(t)r$   g9	gNe?g}8gНNfY?g⏩tr  r  s      r   _expint6r    s8      !  ! 
1a	 	  r    c                4    g d}g d}t          |||           S )N)	gi|Ng.;<8+	?gJΨL˿gҵ b!?gp3ig\&?gw}ϙپg	l Y>g2)
r$   gW[8gwM+?gC68ѿgJ? ?g+kg=x(?gMd~yھg|e[gã>g/r  r  s      r   _expint7r     s8    
 
 
!  ! 
1a	 	  r    c                    t             d           k        d          k    z  g fdt          dd          D             z   }t          j         |t          t
          t          t          t          t          t          g          S )Nr   r#   c           
     d    g | ],} d |z            k      d |dz   z            k    z  -S )r#   r7   r;   ).0r  _cr   s     r   
<listcomp>z_expi_pos.<locals>.<listcomp>  sW     0 0 09:RR16]]Q11aAEl 3 3340 0 0r    r7      )rg   r   r'   	piecewiser  r  r  r  r  r  r   )r   condsr  s   ` @r   	_expi_posr	    s    "Bq!HHqLQ""Q((]+
, 0 0 0 0 0>CAqkk0 0 0 % 
	x8XxJ
 
 r    c                $    t          |             S r:   )exp1r   s    r   	_expi_negr    s    
r((r    c                t    t          d|           \  }t          j        ||dk     gt          t          g          S )aH  Exponential integral function.

  JAX implementation of :obj:`scipy.special.expi`

  .. math::

     \mathrm{expi}(x) = \int_{-\infty}^x \frac{e^t}{t} \mathrm{d}t

  Args:
    x: arraylike, real-valued

  Returns:
    array of expi values

  See also:
    - :func:`jax.scipy.special.expn`
    - :func:`jax.scipy.special.exp1`
  expir   )r   r'   r  r  r	  )r   r   s     r   r  r    s4    *  **&%	uuqykIy+A	B	BBr    c                d    | \  }|\  }t          |          t          j        |          |z  |z  fS r:   )r  r'   r,   r   s       r   expi_jvpr    s4     
$1(5	a#'!**q.5(	((r    x_inc                   t           t          j        |          }t          j        |j                  j         |d           |d          t          j         t          j        |          z
  }t          j	         | d          | fd|          }t          j
        |  | d          k    z   |           }t          || | z
  t          j
        |  | d          k    |z
  z            t          j                  }fd}fd}t          j        |||          }| }	|  | d          z
  }
|d         |
z  |z  t          j        t          |	                    z  |d	         z
  S )
Nrs   r$   r7   c                    || z  z   S r:   r;   )r  psir  s     r   rm   z_expn1.<locals>.<lambda>  s    #a- r    )r   r   xkykpkrl   r  c           	     ~   | dxx         z  cc<   | dxx         | d         | d         z  z  cc<   | dxx         z  cc<   | dxx         t          j        | d         k    | d         | d         z            z  cc<   t          j        | d         k    t          | d         | d         z                      | d<   | S )Nr  r  r   r  rl   r  r'   r(   r   )r   r  r   s    r   bodyz_expn1.<locals>.body  s    dGGGsNGGGdGGGqv$GGGdGGGsNGGGeHHH	!D'T/1T7QtW+<dCCCHHHYqx4'QtWqx-?)@)@#FFAcFHr    c                V    | d          | d         d          k    | d         k    z  S )Nr   rs   r  r;   r   MACHEPr  s    r   rJ  z_expn1.<locals>.cond&  s-    cFRR#__$3&99r    r   rl   )rg   r'   r   r   ry   epsr  rd   r   r  r(   dictr   
while_loopr,   r   )r2   r  r   r  n1rT  r  rJ  r   r  rr  r  r  r   s              @@@@r   _expn1r#  	  s   "	k$!9QW!&	As$
1c

#	371::%#bbAhh#?#?#?#?EE#
ybbAhhc	1--"	b

Qw	!rr!Qxx-scBh'788	g
 
 
$     : : : : : : 
nT4&&!!""Q((l!	
31s	SWWQZZ00	01U8	;;r    c                   	
 t            |d          t          j        j                  j         |d          
 |d          	t            d          	|	| z   	| z   z   |t          j                  
|	  	        } 	
fd}fd}t          j        |||          }|d         t          j	        |           z  S )	Ng      Crs   r$   r7   )	r   pkm2qkm2pkm1qkm1rl   r  r"  r   c           	     z   | d         }| dxx          | d         d          z  cc<   | d         }| |d          z   |d          k    }t          j        ||          }t          j        || |d          z
   |d          z  z   | |d          z            }| d         |z  | d         |z  z   }| d         |z  | d         |z  z   }|k    }t          j        |||z  | d	                   x| d	<   }	t          j        |t          | d
         |	z
  |	z                      | d<   t          j        ||	| d
                   | d
<   | d         | d<   || d<   | d         | d<   || d<   t          |          k    }
dD ]7}dD ]2}|dz   |z   }t          j        |
| |         z  | |                   | |<   38| S )Nr   r   r7   r#   r'  r%  r(  r&  r"  rl   r  pq12kmr  )r   r   r   oddr  r  r  qknzr"  is_bigr   r  keyBIGr  r2   r  r   s                 r   r  z_expn2.<locals>.bodyC  s   	#AcFFFbb3mmFFF	#A
bbAhh,""Q((
"C	3Q		B	3QAq\RR1XX55q22a88|	D	DB	
6R!F)b.	(B	
6R!F)b.	(B	tB2rBw#///AcFQYr3%1122C88AcFyQ%))AeH&	AfIAfI&	AfIAfIWWs]F 9 9 9 9!$hl61S6C<388#9 Hr    c                V    | d          | d         d          k    | d         k    z  S )Nr   r   r   r  r;   r  s    r   rJ  z_expn2.<locals>.cond[  s-    cFRR#]]"qv77r    rl   )
rg   r'   r   ry   r  r  r   r   r   r,   )r2   r   rT  r  rJ  r   r2  r  r  r  r   s   `     @@@@@r   _expn2r4  /  s   "
1$%%#9SY#&	As$
1c

#	bAhh		
		
Qq1ubCGnn


 

 

$        08 8 8 8 8 8 
nT4&&!	
5CGQBKK	r    c                *   t           } ||d          }|| z   }|||z  z  }| }||z   ||d          |z  |z   ||d          |z  |z  z
  ||z  z   z  }|||| ||d          |z  z
  z  z   z  }|||z   z  }||z   t          j        |           z  |z  S )Nr$   r  r   r#   )rg   r'   r,   )r2   r   r  r  r  r  r  rl   s           r   _expn3r6  b  s    "
1c

#1u"
b2g"!
Q""Q((Q,"RR1XX\A%55A=>#
cARR1XX\)**+#
cAg#
)swr{{	"R	''r    )r   c           
        t          d| |          \  } }t          } ||d          } ||d          }|  || d          k     ||k     z  ||k    |  || d          k     z  ||k    |  || d          k    z  |  || d          k    ||k    z  |  || d          k    ||k    g}t          j        |  || d          k    | | z   |           }t          j        t          j        ||z  t          j        |           |z  t          t          |           t          t          |           t          t          |           g}t          j        |||          }|S )a  Generalized exponential integral function.

  JAX implementation of :obj:`scipy.special.expn`.

  .. math::

     \mathrm{expn}(x) = E_n(x) = x^{n-1}\int_x^\infty\frac{e^{-t}}{t^n}\mathrm{d}t

  Args:
    n: arraylike, real-valued
    x: arraylike, real-valued

  Returns:
    array of expn values

  See also:
    - :func:`jax.scipy.special.expi`
    - :func:`jax.scipy.special.exp1`
  expnr   r7   r#   i  )r   rg   r'   r(   nanr   r,   r   r6  r4  r#  r  )	r2   r   r  r   r  r  r!  valsrets	            r   r8  r8  o  sU   . 
fa	+	+$!Q"	Aq$
1a#Aq\a$h$Y1rr!Qxx< $Y11a=!""Q((]qDy!""Q++W% ybbAhhAq))"GG"HGQBKK!OFAFAFA
$ 	a%%#	*r    c                    ||c\  }\  }t          | |          t          j        t          j        |          t          t          j        | t          | d                    |                    fS ri   )r8  r   rj   r   rf   rg   )r2   r{   r|   r   r}   s        r   expn_jvpr=    sc     H.$1	aSWGENNDJq!$4$455q99  
 r    c                l    t          d|           \  } t          t          t          d|                     S )aW  Exponential integral function.

  JAX implementation of :obj:`scipy.special.exp1`

  .. math::

     \mathrm{exp1}(x) = E_1(x) = x^{n-1}\int_x^\infty\frac{e^{-t}}{t}\mathrm{d}t


  Args:
    x: arraylike, real-valued

  Returns:
    array of exp1 values

  See also:
    - :func:`jax.scipy.special.expi`
    - :func:`jax.scipy.special.expn`
  r  r7   )r   r   r   r8  r   s    r   r  r    s-    ( FA&&"!	eT!QZZ	 	  r    r   c                    t          j        g d| j                  }t          j        g d| j                  }|  t          j        ||           z  t          j        ||           z  S )N)g
b?g4ھcD}?gh\Qa!?gdn&?gj[!&@g'4z#@g#+wa
@r$   r   )grF?g! #ך?g?4B?g)m?gN@goR7c!@g#+wa@r$   )r'   r   ry   r  )r   r  r  s      r   _spence_polyr@    s    	i    7$ $ $! 
i    '# # #! ck!Q	#+a"3"3	33r    c                   | dk    }t          j        | |gd d g          } | dk    }| dk     }||z  }t          j        | ||gd d d g          }t          |          }t           j        d	z  d
z  t          j        |           t          j        d| z
            z  z
  |z
  }t          j        |||          }dt          j        |           d	z  z  |z
  }t          j        |||          S )Nr   c                    d| z  S Nr$   r;   r   s    r   rm   z_spence_calc.<locals>.<lambda>  s
    sQw r    c                    | S r:   r;   r   s    r   rm   z_spence_calc.<locals>.<lambda>  s    ! r    g      ?r   c                    d| z  dz
  S rC  r;   r   s    r   rm   z_spence_calc.<locals>.<lambda>  s    sQw} r    c                    |  S r:   r;   r   s    r   rm   z_spence_calc.<locals>.<lambda>  s     r    c                    | dz
  S rC  r;   r   s    r   rm   z_spence_calc.<locals>.<lambda>  s
    C r    r#   g      @r$   r0  )r'   r  r@  r   rd   r(   )r   x2_bool	x1_5_boolx_5_boolr   r=   
y_flag_one
y_flag_twos           r   _spence_calcrM    s   G'	mAy&&46 6! #g)W(i'	mA),,"l'')* *! 1oo!v{S 371::a0@0@#@@1D*	i*a((!cgajjAo%)*	7J	*	**r    c                    t          j        | | dk     | dk    | dk    gt           j        dt           j        dz  dz  t          g          S )Nrs   r$   r   r#   r  )r'   r  r9  r   rM  r   s    r   _spencerO    sI    	qCc184CFaK!O\B
D 
D Dr    c                    t          j        |           } t          j        |           }|t           j        t           j        fvrt          d| d          t          |           S )a?  Spence's function, also known as the dilogarithm for real values.

  JAX implementation of :obj:`scipy.special.spence`.

  It is defined to be:

  .. math::
    \mathrm{spence}(x) = \begin{equation}
    \int_1^x \frac{\log(t)}{1 - t}dt
    \end{equation}

  Unlike the SciPy implementation, this is only defined for positive
  real values of `z`. For negative values, `NaN` is returned.

  Args:
    z: An array of type `float32`, `float64`.

  Returns:
    An array with `dtype=z.dtype`.
    computed values of Spence's function.

  Raises:
    TypeError: if elements of array `z` are not in (float32, float64).

  Notes:
  There is a different convention which defines Spence's function by the
  integral:

  .. math::
    \begin{equation}
    -\int_0^z \frac{\log(1 - t)}{t}dt
    \end{equation}

  This is our spence(1 - z).
  r  z5 is not supported, see docstring for supported types.)r'   r   r   ry   r   r   rD   rO  r   s     r   spencerQ    sb    H 
k!nn!
)A,,%
3;,,,
MMMMO O O	r    c                   t          j        t          j        | d          } | dk     rt	          d          t          j        g d          }| dk     r|d| dz            S t          j        | dz             j        dd         	                    |          }t          j
        d| dz   d	|j        
          }dt
          j        d	z  z  t          j        |dz
   |z  dz  t
          j        d	z  z            z  }t          j
        d	d|j        
          }t          j        |dddf         |dddf          z  d          }|j        ddd	         	                    |d|z   z            S )a^  Generate the first N Bernoulli numbers.

  JAX implementation of :func:`scipy.special.bernoulli`.

  Args:
    n: integer, the number of Bernoulli terms to generate.

  Returns:
    Array containing the first ``n`` Bernoulli numbers.

  Notes:
    ``bernoulli`` generates numbers using the :math:`B_n^-` convention,
    such that :math:`B_1=-1/2`.
  zArgument n of bernoullir   z!n must be a non-negative integer.)r7   r0  gUUUUUU?r  Nr7   r  r#   r   r$   rP  r   )r   r   r^  r_  r  r'   r   rn  ro  rp  r   ry   r   r   r   )r2   b3bnr   r   r   r   s          r   	bernoullirU  "	  sV     X^Q0IJJ!UU
8
9
99
y  "UUfq1uf:
yQ2A2""2&&"	jAE1BH---!
SVq[CK!a%1q(836Q;(FGGG"	jBbh'''!
wqDzaaaaj[(q111"	qt!tq2v	'	''r    c                    t          d| |          \  } }t          j        |dk    t          j        d| j                  t          | |z             t          |           z            S )a  The Pochammer symbol.

  JAX implementation of :obj:`scipy.special.poch`.

  .. math::

     \mathrm{poch}(z, m) = (z)_m = \frac{\Gamma(z + m)}{\Gamma(z)}

  where :math:`\Gamma(z)` is the :func:`~jax.scipy.special.gamma` function.

  Args:
    z: arraylike, real-valued
    m: arraylike, real-valued

  Returns:
    array of Pochammer values.

  Notes:
    The JAX version supports only real-valued inputs.
  pochrs   r7   r   )r   r'   r(   r   ry   r+   r   r   s     r   rW  rW  @	  sW    , 
fa	+	+$!Q	17CIaqw777q1ua9P	Q	QQr    c                h    t          | |z             t          |           z
  t          | |          z  S )zT
  Defined in :
  https://functions.wolfram.com/GammaBetaErf/Pochhammer/20/01/01/
  rS   rW  rX  s     r   _poch_z_derivativer[  [	  s,     !a%..71::
%a	33r    c                H    t          | |z             t          | |          z  S )zT
  Defined in :
  https://functions.wolfram.com/GammaBetaErf/Pochhammer/20/01/02/
  rZ  rX  s     r   _poch_m_derivativer]  d	  s!     
Q$q!**	$$r    c                (    t          ||          | z  S r:   )r[  )z_dot
primal_outr   r   s       r   rm   rm   n	  s    #5a#;#;e#C r    c                (    t          ||          | z  S r:   )r]  )m_dotr`  r   r   s       r   rm   rm   o	  s    "4Q":":U"B r    c                     t          j        j                  j         fd}fd}dd z  z  f}t	          j        |||          d         S )z
  Compute the 1F1 hypergeometric function using the taylor expansion
  See Eq. 3.2 and associated method (a) from PEARSON, OLVER & PORTER 2014
  https://doi.org/10.48550/arXiv.1407.7786
  c                \    | \  }}}||z  }||z   |z   z  z  |dz   z  z  }|dz  }|||fS ri   r;   stateserier   termr-   r.   r   s       r   r  z_hyp1f1_serie.<locals>.body|	  sQ    NE1d	TMEQUq1u!QU++DFA!T>r    c                x    | \  }}}|dk     t          j        |          t          j        |          z  k    z  S N   r   r   rf  rg  r   rh  	precisions       r   rJ  z_hyp1f1_serie.<locals>.cond	  7    NE1dG6BCCr    r7   r   r'   r   ry   r  r   r   r-   r.   r   r  rJ  rT  rn  s   ```   @r   _hyp1f1_serierr  s	  s     i  $)      D D D D D
 
Aq1uqy$	dD	)	)!	,,r    c                8    t          j        j                  j         fd}fd}dd z
  d z
  z  z  f}t	          j        |||          d         }t                    t                     z  t	          j                  z   z
  z  z  |z  S )z
  Compute the 1F1 hypergeometric function using asymptotic expansion
  See Eq. 3.8 and simplification for real inputs from PEARSON, OLVER & PORTER 2014
  https://doi.org/10.48550/arXiv.1407.7786
  c                h    | \  }}}||z  }|z
  |z   dz
  |z   z  |dz   z  z  z  }|dz  }|||fS ri   r;   re  s       r   r  z _hyp1f1_asymptotic.<locals>.body	  sY    NE1d	TMEQUQY1q519%Q/!33DFA!T>r    c                x    | \  }}}|dk     t          j        |          t          j        |          z  k    z  S rj  rl  rm  s       r   rJ  z _hyp1f1_asymptotic.<locals>.cond	  ro  r    r7   r   )r'   r   ry   r  r   r   r+   r,   )r-   r.   r   r  rJ  rT  rg  rn  s   ```    @r   _hyp1f1_asymptoticrv  	  s     i  $)      D D D D D
 
AA!a% 1$	$$
.tT
*
*1
-%	qE!HH	swqzz	)A!a%L	85	@@r    c                     t          j        j                  j         fd}fd}dd z  z  f}t	          j        |||          d         S )zv
  Define it as a serie using :
  https://functions.wolfram.com/HypergeometricFunctions/Hypergeometric1F1/20/01/01/
  c                    | \  }}}||t          |z             t                    z
  z  z  }||z   |z   z  z  |dz   z  z  }|dz  }|||fS ri   rS   re  s       r   r  z"_hyp1f1_a_derivative.<locals>.body	  sl    NE1d	TWQU^^gajj011EQUq1u!QU++DFA!T>r    c                x    | \  }}}|dk     t          j        |          t          j        |          z  k    z  S rj  rl  rm  s       r   rJ  z"_hyp1f1_a_derivative.<locals>.cond	  ro  r    r   r7   rp  rq  s   ```   @r   _hyp1f1_a_derivativer{  	       i  $)      D D D D D
 
Aq1uqy$	dD	)	)!	,,r    c                     t          j        j                  j         fd}fd}dd z  z  f}t	          j        |||          d         S )zv
  Define it as a serie using :
  https://functions.wolfram.com/HypergeometricFunctions/Hypergeometric1F1/20/01/02/
  c                    | \  }}}||t                    t          |z             z
  z  z  }||z   |z   z  z  |dz   z  z  }|dz  }|||fS ri   ry  re  s       r   r  z"_hyp1f1_b_derivative.<locals>.body	  sl    NE1d	TWQZZ'!a%..011EQUq1u!QU++DFA!T>r    c                x    | \  }}}|dk     t          j        |          t          j        |          z  k    z  S rj  rl  rm  s       r   rJ  z"_hyp1f1_b_derivative.<locals>.cond	  ro  r    r   r7   rp  rq  s   ```   @r   _hyp1f1_b_derivativer  	  r|  r    c                <    | |z  t          | dz   |dz   |          z  S )zv
  Define it as a serie using :
  https://functions.wolfram.com/HypergeometricFunctions/Hypergeometric1F1/20/01/04/
  r7   )hyp1f1rQ   s      r   _hyp1f1_x_derivativer  	  s'     
QAq1ua((	((r    c           
        t          d| ||          \  } }}t          j        t          j        |          dk     t          t
          | ||          }| dk    dz  | |k    | dk    z  dz  z   |dk    | dk    z  dz  z   }t          j        ||t          j        d|j	                  t          j
        |          t          j        t          j        |j	                            S )a  The 1F1 hypergeometric function.

  JAX implementation of :obj:`scipy.special.hyp1f1`.

  .. math::

     \mathrm{hyp1f1}(a, b, x) = {}_1F_1(x;a, b) = \sum_{k=0}^\infty \frac{(a)_k}{(b)_kk!}x^k

  where :math:`(\cdot)_k` is the Pochammer symbol (refer to :func:`~jax.scipy.special.poch`).

  The JAX version only accepts positive and real inputs. Values of ``a``, ``b``,
  and ``x``, leading to high values of 1F1 may lead to erroneous results;
  consider enabling double precision in this case. The convention for
  ``a = b = 0`` is ``1``, unlike in scipy's implementation.

  Args:
    a: arraylike, real-valued
    b: arraylike, real-valued
    x: arraylike, real-valued

  Returns:
    array of 1F1 values.
  r  d   r   r7   r#   r  r   )r   r   rJ  r   rr  rv  select_nr'   r   ry   r,   r   )r-   r.   r   r   r_  s        r   r  r  	  s    < !1a33'!Q8CGAJJ$m5GAqQQ&6Q,16a1f-2
2qAv!q&6IQ5N
N%	ei111gajjiqw777	
9 
9 9r    c                *    t          |||          | z  S r:   )r{  )a_dotr`  r-   r.   r   s        r   rm   rm   
      %9!Q%B%BU%J r    c                *    t          |||          | z  S r:   )r  )b_dotr`  r-   r.   r   s        r   rm   rm   
  r  r    c                *    t          |||          | z  S r:   )r  )r}   r`  r-   r.   r   s        r   rm   rm   
  r  r    r   r   int | tuple[int, ...] | Nonec              $    t          | |          S )a  Softmax function.

  JAX implementation of :func:`scipy.special.softmax`.

  Computes the function which rescales elements to the range :math:`[0, 1]`
  such that the elements along :code:`axis` sum to :math:`1`.

  .. math ::
    \mathrm{softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}

  Args:
    x : input array
    axis: the axis or axes along which the softmax should be computed. The
      softmax output summed across these dimensions should sum to :math:`1`.

  Returns:
    An array of the same shape as ``x``.

  Note:
    If any input values are ``+inf``, the result will be all ``NaN``: this
    reflects the fact that ``inf / inf`` is not well-defined in the context of
    floating-point math.

  See also:
    :func:`log_softmax`
  r   )
nn_softmaxr   r   s     r   r   r   
  s    > 
AD	!	!	!!r    c              $    t          | |          S )a  Log-Softmax function.

  JAX implementation of :func:`scipy.special.log_softmax`

  Computes the logarithm of the :code:`softmax` function, which rescales
  elements to the range :math:`[-\infty, 0)`.

  .. math ::
    \mathrm{log\_softmax}(x)_i = \log \left( \frac{\exp(x_i)}{\sum_j \exp(x_j)}
    \right)

  Args:
    x : input array
    axis: the axis or axes along which the :code:`log_softmax` should be
      computed.

  Returns:
    An array of the same shape as ``x``

  Note:
    If any input values are ``+inf``, the result will be all ``NaN``: this
    reflects the fact that ``inf / inf`` is not well-defined in the context of
    floating-point math.

  See also:
    :func:`softmax`
  r   )nn_log_softmaxr  s     r   r   r   ?
  s    @ 
	%	%	%%r    )r   r   r   r   )r-   r   r.   r   r   r   )F)r2   r   r3   r4   r   r   )r-   r   r=   r   r   r   )r   r   r=   r   r   r   )r-   r   r.   r   r   r   r   r   )r-   r   r   r   r   r   )r-   r   r   r   r   r   )r   r   r   r   r   r   r:   )r   r   r   r   r   r   )r2   r   r   r   r   r   )r   r   r   r   )r  )r   r   r  r   r   r   )r2   r   r   r+  )r   r   rR  r   rQ  r   r   r   )rd  r   re  r4   ry   r   r   rf  )r   r   r   r   re  r4   r   r   )rd  r   r   r   re  r4   r   r   )r   r   r2   r   r   r   r   rf  )
r   r   r2   r   r   r   re  r4   r   r   )r   r   r2   r   r  r   r  r   r  r   r   r   )r   r   r2   r   r  r   r  r   r  r  r   r   )r   r   r   r   )r  r  r  r  r   r   r   r   )r2   r   r  r   r   r   )r2   r   r   r   r   r   )r   r   r   r   )r2   r   r   r   )r   r   r   r   r   r   )r   r   r   r  r   r   )
__future__r   	functoolsr   r^  typingr   r   r   numpyr   	jax.numpyr'   jaxr   r	   r
   r   jax._srcr   r   r   r   jax._src.lax.laxr   rg   jax._src.numpy.utilr   r   jax._src.opsr   ops_special!jax._src.third_party.scipy.betalnr   r0   jax._src.typingr   r   jax._src.nn.functionsr   r  r   r  r   r"   r+   r6   r<   rH   rP   rS   rU   rY   r\   r^   r`   
custom_jvprc   defjvpsro   	logsumexprr   r   defjvpr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r  r   r   r   r   r  r!  r  r#  r'  rd   r   r   r1  r  r5  r9  r<  r?  rO  rZ  rc  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r	  r  r  r  r#  r4  r6  	vectorizer8  r=  r  r@  rM  rO  rQ  rU  rW  r[  r]  rr  rv  r{  r  r  r  r;   r    r   <module>r     s(   # " " " " "        & & & & & & & & & &                                         ' ' ' ' ' ' ! ! ! ! ! !       1 1 1 1 1 1 L L L L L L L L / / / / / / D D D D D D , , , , , , , , 7 7 7 7 7 7 ? ? ? ? ? ?   8M M M M<". ". ". ".J   29 9 9 9 9< 
 2 2 2 
 2	 5 5 5 
 5	 5 5 5 
 5% % %N& & &   6   8   4   4   4   :   0 ; ; ; ;" JJL L L   & !	 D D D D.K K K
 Z    F F F F.S S S
 |     . . . j   ( ( ( (:% % % %P       >& & & &T   (     4    : GGC/00 1 1 1% % % %z "#rz22 !#rz22  "!RZ00 !!RZ00    D      8j j j jZ 			&===e7 e7 e7 e7 >=e7N  
 	   K K K( ( (&& & & &
 wrwq25y1122 C C C   49 9 9 90   49 9 9 9.  ( 57      " 	sHo...35 %/ %/ %/ %/ %/ /.%/P1" 1" 1" 1"h 	a!!![ [ [ "![| 	V$$$b b b %$bJ)! )! )! )!X3; 3; 3; 3;n 	T"""   #": "&	,, ,, ,, ,, ,,j. . . .2   ! ! ! !2! ! ! !4! ! ! !:! ! !4! ! !*! ! !8
 
 
 
    C C C  C. ) )  )#< #< #< #<L0  0  0  0 f
( 
( 
( 
( 			&===+ + +   >=+\    ! ! ! !24 4 4 40+ + + +,D D D D) ) ) )X( ( ( (< R R R R44 4 4% % % CCBB  - - -6A A A8 - -  -4 - -  -4 ) ) ) $9 $9 $9   $9N JJJJJJ   26" " " " " "J 6: &  &  &  &  &  &  &  &r    