
    ^Mh6                         d dl Z d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlmZ g dZddZddZdd
Zd Zd ZddZddZdS )    N)_asarray_validated)array_namespacexp_sizexp_broadcast_promotexp_copyxp_float_to_complex
is_complex)array_api_extra)	logsumexpsoftmaxlog_softmaxFc                    t          | |          }t          | |dd|          \  } }t          j        | d|          } |t          j        |d|          n|}|!t	          t          | j                            n|}t          |           dk    rFt          j	        dd          5  t          | ||||	          \  }}ddd           n# 1 swxY w Y   nct          j        | j                  }d||<   |                    t	          |          |j         | j        
          }|                    |          }|                    |j        d          r|rN|                    |          }	t'          t)          |                    |          |                    }
|	|
dz  z   }nM|                    |          }	t'          t)          |                    |          |                    }
|	|
dz  z   }|s|                    ||          n|}||s|                    ||          n|}|j        dk    r|d         n|}||j        dk    r|d         n|}|r||fn|S )an  Compute the log of the sum of exponentials of input elements.

    Parameters
    ----------
    a : array_like
        Input array.
    axis : None or int or tuple of ints, optional
        Axis or axes over which the sum is taken. By default `axis` is None,
        and all elements are summed.

        .. versionadded:: 0.11.0
    b : array-like, optional
        Scaling factor for exp(`a`) must be of the same shape as `a` or
        broadcastable to `a`. These values may be negative in order to
        implement subtraction.

        .. versionadded:: 0.12.0
    keepdims : bool, optional
        If this is set to True, the axes which are reduced are left in the
        result as dimensions with size one. With this option, the result
        will broadcast correctly against the original array.

        .. versionadded:: 0.15.0
    return_sign : bool, optional
        If this is set to True, the result will be a pair containing sign
        information; if False, results that are negative will be returned
        as NaN. Default is False (no sign information).

        .. versionadded:: 0.16.0

    Returns
    -------
    res : ndarray
        The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically
        more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``
        is returned. If ``return_sign`` is True, ``res`` contains the log of
        the absolute value of the argument.
    sgn : ndarray
        If ``return_sign`` is True, this will be an array of floating-point
        numbers matching res containing +1, 0, -1 (for real-valued inputs)
        or a complex phase (for complex inputs). This gives the sign of the
        argument of the logarithm in ``res``.
        If ``return_sign`` is False, only one result is returned.

    See Also
    --------
    numpy.logaddexp, numpy.logaddexp2

    Notes
    -----
    NumPy has a logaddexp function which is very similar to `logsumexp`, but
    only handles two arguments. `logaddexp.reduce` is similar to this
    function, but may be less stable.

    The logarithm is a multivalued function: for each :math:`x` there is an
    infinite number of :math:`z` such that :math:`exp(z) = x`. The convention
    is to return the :math:`z` whose imaginary part lies in :math:`(-pi, pi]`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.special import logsumexp
    >>> a = np.arange(10)
    >>> logsumexp(a)
    9.4586297444267107
    >>> np.log(np.sum(np.exp(a)))
    9.4586297444267107

    With weights

    >>> a = np.arange(10)
    >>> b = np.arange(10, 0, -1)
    >>> logsumexp(a, b=b)
    9.9170178533034665
    >>> np.log(np.sum(b*np.exp(a)))
    9.9170178533034647

    Returning a sign flag

    >>> logsumexp([1,2],b=[1,-1],return_sign=True)
    (1.5413248546129181, -1.0)

    Notice that `logsumexp` does not directly support masked arrays. To use it
    on a masked array, convert the mask into zero weights:

    >>> a = np.ma.array([np.log(2), 2, np.log(3)],
    ...                  mask=[False, True, False])
    >>> b = (~a.mask).astype(int)
    >>> logsumexp(a.data, b=b), np.log(5)
    1.6094379124341005, 1.6094379124341005

    T)ensure_writeableforce_floatingxp   )ndimr   Nr   ignore)divideinvalid)axisreturn_signr   dtypecomplex floating              ?)r    )r   r   xpx
atleast_ndtupleranger   r   nperrstate
_logsumexpasarrayshapefullinfr   signisdtyperealr   _wrap_radiansimagsqueeze)ar   bkeepdimsr   r   outsgnr&   r+   r-   s              X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/special/_logsumexp.pyr   r      s   z 
A		B1tDUWXXXDAqqqR(((A,-MqqR((((qA#'<5qvTDqzzQ[(;;; 	S 	S!!QT{rRRRHC	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 
17##dggeEllRVG17g;;ggcll	zz#)/00 ! 	!773<<D&}RWWS\\2'F'FGGDb.CC773<<D&}RWWS\\2'F'FGGDb.C -5
="**St*
$
$
$#C),"**St*
$
$
$PSCX]]#b''Co#(a--#b''cC$-C::#-s   (CCCc                     |t          |           n|}|  t          j        z   dt          j        z  z  t          j        z
   }|                    |           |j        k     }| |         ||<   |S )N   )r   mathpiabs)xr   r2   no_wraps       r4   r,   r,      sb    !z			rBR$'\a$'k*TW4
5CffQii"%GW:CLJ    c                 z   |t          |           n|}|                    | j        d          r|                    |           }|                    ||d          }||k    }|                    |                    t          |                     | j                  }d|| <   |                    ||d          }||k    }t          |           } d| | <   |
                    | || j        d          }n|                    | |d          }| |k    }|                    |          |                    |          fS )Nr   Tr   r1   r=   r   )r   r   r1   )r   r*   r   r+   maxreshapearanger   r&   r   sumr%   )r/   r   r   real_ar@   maskimax_is           r4   #_elements_and_indices_with_max_realrH      s*     "z			rB	zz!'-.. ffV$f66}
 JJryy,,ag664%qtd33EzAJJ4%ffQT4f@@ffQTDf11Cx::c??BJJt,,,,r<   c                     | |                     | dk    |                    d| j                  |                    |                     z  S )Nr   r   r   )wherer%   r   r9   )r:   r   s     r4   _signrK      s=    rxxQ

1AG
 < <bffQiiHHHHr<   c                    ||j          | |dk    <   t          | ||          \  }}|j          | |<   |                    || j                  }||                    ||d| j                  n |                    ||z  |d| j                  }|                    |                    |          ||                    d|j                            }	|||                    | |	z
            z  n|                    | |	z
            }
|                    |
|d|
j                  }|                    |dk    |||z            }t          |dz   |          t          ||          z  }|
                    |j        d          r5|                    |d	k     | d
z
  |          }|                    |          }nH||                    |                    |          |                    d|j                  z            z  }|                    |          |                    |          z   |z   }|r&t          ||          r|                    |          }n)|
                    |j        d          r|j        ||dk     <   ||fS )Nr   )r   r   T)r   r1   r   r   r   )r   zreal floatingr=   r6   r   )r(   rH   astyper   rC   rJ   isfiniter%   exprK   r*   r9   r-   log1plogr	   r+   nan)r/   r0   r   r   r   a_maxi_maxi_max_dtmshiftrO   sr3   r2   s                 r4   r$   r$      sh   
 	}VG!q&	 7qtKKKLE5 wAeHyy((H GHitd!'	B	B	BffQ\t17fKK 
 HHR[[''

1EK
0P0PQQE $%=!bffQY

bffQY6G6GC
sCI>>A
aAaC  A A"


aB
/C	zz!'?++ QHHQVaR!VQ''FF1II BFF2775>>BJJt5;J,O,OOPPP ((1++q		
!E
)C c2 	''#,,C	CI	/	/ vC!G8Or<   c                     t          | d          } t          j        | |d          }t          j        | |z
            }|t          j        ||d          z  S )a
  Compute the softmax function.

    The softmax function transforms each element of a collection by
    computing the exponential of each element divided by the sum of the
    exponentials of all the elements. That is, if `x` is a one-dimensional
    numpy array::

        softmax(x) = np.exp(x)/sum(np.exp(x))

    Parameters
    ----------
    x : array_like
        Input array.
    axis : int or tuple of ints, optional
        Axis to compute values along. Default is None and softmax will be
        computed over the entire array `x`.

    Returns
    -------
    s : ndarray
        An array the same shape as `x`. The result will sum to 1 along the
        specified axis.

    Notes
    -----
    The formula for the softmax function :math:`\sigma(x)` for a vector
    :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is

    .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}

    The `softmax` function is the gradient of `logsumexp`.

    The implementation uses shifting to avoid overflow. See [1]_ for more
    details.

    .. versionadded:: 1.2.0

    References
    ----------
    .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the
       log-sum-exp and softmax functions", IMA Journal of Numerical Analysis,
       Vol.41(4), :doi:`10.1093/imanum/draa038`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.special import softmax
    >>> np.set_printoptions(precision=5)

    >>> x = np.array([[1, 0.5, 0.2, 3],
    ...               [1,  -1,   7, 3],
    ...               [2,  12,  13, 3]])
    ...

    Compute the softmax transformation over the entire array.

    >>> m = softmax(x)
    >>> m
    array([[  4.48309e-06,   2.71913e-06,   2.01438e-06,   3.31258e-05],
           [  4.48309e-06,   6.06720e-07,   1.80861e-03,   3.31258e-05],
           [  1.21863e-05,   2.68421e-01,   7.29644e-01,   3.31258e-05]])

    >>> m.sum()
    1.0

    Compute the softmax transformation along the first axis (i.e., the
    columns).

    >>> m = softmax(x, axis=0)

    >>> m
    array([[  2.11942e-01,   1.01300e-05,   2.75394e-06,   3.33333e-01],
           [  2.11942e-01,   2.26030e-06,   2.47262e-03,   3.33333e-01],
           [  5.76117e-01,   9.99988e-01,   9.97525e-01,   3.33333e-01]])

    >>> m.sum(axis=0)
    array([ 1.,  1.,  1.,  1.])

    Compute the softmax transformation along the second axis (i.e., the rows).

    >>> m = softmax(x, axis=1)
    >>> m
    array([[  1.05877e-01,   6.42177e-02,   4.75736e-02,   7.82332e-01],
           [  2.42746e-03,   3.28521e-04,   9.79307e-01,   1.79366e-02],
           [  1.22094e-05,   2.68929e-01,   7.31025e-01,   3.31885e-05]])

    >>> m.sum(axis=1)
    array([ 1.,  1.,  1.])

    Fcheck_finiteTr?   )r   r"   amaxrO   rC   )r:   r   x_maxexp_x_shifteds       r4   r   r      s\    v 	15111AGAD4000EF1u9%%M26-dTJJJJJr<   c                    t          | d          } t          j        | |d          }|j        dk    rd|t          j        |           <   nt          j        |          sd}| |z
  }t          j        |          }t          j        d          5  t          j        ||d          }t          j        |          }ddd           n# 1 swxY w Y   ||z
  }|S )	a  Compute the logarithm of the softmax function.

    In principle::

        log_softmax(x) = log(softmax(x))

    but using a more accurate implementation.

    Parameters
    ----------
    x : array_like
        Input array.
    axis : int or tuple of ints, optional
        Axis to compute values along. Default is None and softmax will be
        computed over the entire array `x`.

    Returns
    -------
    s : ndarray or scalar
        An array with the same shape as `x`. Exponential of the result will
        sum to 1 along the specified axis. If `x` is a scalar, a scalar is
        returned.

    Notes
    -----
    `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that
    make `softmax` saturate (see examples below).

    .. versionadded:: 1.5.0

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.special import log_softmax
    >>> from scipy.special import softmax
    >>> np.set_printoptions(precision=5)

    >>> x = np.array([1000.0, 1.0])

    >>> y = log_softmax(x)
    >>> y
    array([   0., -999.])

    >>> with np.errstate(divide='ignore'):
    ...   y = np.log(softmax(x))
    ...
    >>> y
    array([  0., -inf])

    FrZ   Tr?   r   r   )r   N)	r   r"   r\   r   rN   rO   r#   rC   rQ   )r:   r   r]   tmpexp_tmprX   r2   s          r4   r   r   [  s   h 	15111AGAD4000EzA~~%&r{5!!!""[ 
e)CfSkkG 
H	%	%	%  F7555fQii               )CJs   ,C		CC)NNFF)N)r=   N)r7   numpyr"   scipy._lib._utilr   scipy._lib._array_apir   r   r   r   r   r	   
scipy._libr
   r   __all__r   r,   rH   rK   r$   r   r   r   r<   r4   <module>rg      s@        / / / / / /                . - - - - -
1
1
1|. |. |. |.~   - - - -DI I I7 7 7t^K ^K ^K ^KBF F F F F Fr<   