a
    “Àh¶Z  ã                   @   sz   d dl ZddlmZmZmZ d dlm  mZ	 d dl
mZ deedd eddœdd„Zd	d
„ Zddddddddœdd„ZdS )é    Né   )Ú_xtolÚ_rtolÚ_iter)Ú_RichResult© )ÚargsÚxatolÚxrtolÚfatolÚfrtolÚmaxiterÚcallbackc                C   s@  t | |||||||	ƒ}
|
\} }}}}}}}	t | ||f|¡}|\} }}}}}|\}}|\}}tj|tjtd}d\}}|du r‚tn|}|du r’tn|}|du rªt 	|¡j
n|}|t t |¡t |¡¡ }t||||ddd|||||||d}g d¢}dd„ }d	d
„ }dd„ }dd„ }dd„ }t ||	||| ||||||||¡S )a  Find the root of an elementwise function using Chandrupatla's algorithm.

    For each element of the output of `func`, `chandrupatla` seeks the scalar
    root that makes the element 0. This function allows for `a`, `b`, and the
    output of `func` to be of any broadcastable shapes.

    Parameters
    ----------
    func : callable
        The function whose root is desired. The signature must be::

            func(x: ndarray, *args) -> ndarray

         where each element of ``x`` is a finite real and ``args`` is a tuple,
         which may contain an arbitrary number of components of any type(s).
         ``func`` must be an elementwise function: each element ``func(x)[i]``
         must equal ``func(x[i])`` for all indices ``i``. `_chandrupatla`
         seeks an array ``x`` such that ``func(x)`` is an array of zeros.
    a, b : array_like
        The lower and upper bounds of the root of the function. Must be
        broadcastable with one another.
    args : tuple, optional
        Additional positional arguments to be passed to `func`.
    xatol, xrtol, fatol, frtol : float, optional
        Absolute and relative tolerances on the root and function value.
        See Notes for details.
    maxiter : int, optional
        The maximum number of iterations of the algorithm to perform.
    callback : callable, optional
        An optional user-supplied function to be called before the first
        iteration and after each iteration.
        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
        similar to that returned by `_chandrupatla` (but containing the current
        iterate's values of all variables). If `callback` raises a
        ``StopIteration``, the algorithm will terminate immediately and
        `_chandrupatla` will return a result.

    Returns
    -------
    res : _RichResult
        An instance of `scipy._lib._util._RichResult` with the following
        attributes. The descriptions are written as though the values will be
        scalars; however, if `func` returns an array, the outputs will be
        arrays of the same shape.

        x : float
            The root of the function, if the algorithm terminated successfully.
        nfev : int
            The number of times the function was called to find the root.
        nit : int
            The number of iterations of Chandrupatla's algorithm performed.
        status : int
            An integer representing the exit status of the algorithm.
            ``0`` : The algorithm converged to the specified tolerances.
            ``-1`` : The algorithm encountered an invalid bracket.
            ``-2`` : The maximum number of iterations was reached.
            ``-3`` : A non-finite value was encountered.
            ``-4`` : Iteration was terminated by `callback`.
            ``1`` : The algorithm is proceeding normally (in `callback` only).
        success : bool
            ``True`` when the algorithm terminated successfully (status ``0``).
        fun : float
            The value of `func` evaluated at `x`.
        xl, xr : float
            The lower and upper ends of the bracket.
        fl, fr : float
            The function value at the lower and upper ends of the bracket.

    Notes
    -----
    Implemented based on Chandrupatla's original paper [1]_.

    If ``xl`` and ``xr`` are the left and right ends of the bracket,
    ``xmin = xl if abs(func(xl)) <= abs(func(xr)) else xr``,
    and ``fmin0 = min(func(a), func(b))``, then the algorithm is considered to
    have converged when ``abs(xr - xl) < xatol + abs(xmin) * xrtol`` or
    ``fun(xmin) <= fatol + abs(fmin0) * frtol``. This is equivalent to the
    termination condition described in [1]_ with ``xrtol = 4e-10``,
    ``xatol = 1e-5``, and ``fatol = frtol = 0``. The default values are
    ``xatol = 2e-12``, ``xrtol = 4 * np.finfo(float).eps``, ``frtol = 0``,
    and ``fatol`` is the smallest normal number of the ``dtype`` returned
    by ``func``.

    References
    ----------

    .. [1] Chandrupatla, Tirupathi R.
        "A new hybrid quadratic/bisection algorithm for finding the zero of a
        nonlinear function without using derivatives".
        Advances in Engineering Software, 28(3), 145-149.
        https://doi.org/10.1016/s0965-9978(96)00051-8

    See Also
    --------
    brentq, brenth, ridder, bisect, newton

    Examples
    --------
    >>> from scipy import optimize
    >>> def f(x, c):
    ...     return x**3 - 2*x - c
    >>> c = 5
    >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,))
    >>> res.x
    2.0945514818937463

    >>> c = [3, 4, 5]
    >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,))
    >>> res.x
    array([1.8932892 , 2.        , 2.09455148])

    ©Údtype)r   é   Nç      à?)Úx1Úf1Úx2Úf2Úx3Úf3Útr	   r
   r   r   ÚnitÚnfevÚstatus)	©r   r   )ÚxÚxmin)ÚfunÚfmin©r   r   ©r   r   ©Úxlr   ©Úflr   )Úxrr   )Úfrr   c                 S   s   | j | j| j| j    }|S ©N)r   r   r   )Úworkr   r   r   úX/var/www/html/assistant/venv/lib/python3.9/site-packages/scipy/optimize/_chandrupatla.pyÚpre_func_evalŽ   s    z$_chandrupatla.<locals>.pre_func_evalc                 S   sŒ   |j  ¡ |j ¡  |_|_t |¡t |j¡k}| }|j| |j|  |j|< |j|< |j| |j|  |j |< |j|< | | |_|_d S r*   )	r   Úcopyr   r   r   ÚnpÚsignr   r   )r   Úfr+   ÚjZnjr   r   r,   Úpost_func_eval“   s    ""z%_chandrupatla.<locals>.post_func_evalc                 S   sr  t  | j¡t  | j¡k }t  || j| jf¡| _t  || j| jf¡| _t j	| jt
d}t| j| j ƒ| _t| jƒ| j | j | _| j| jk }|t  | j¡| j| j kO }tj| j|< d||< t  | j¡t  | j¡k| @ }t jt jtj  | j|< | j|< | j|< d||< t  | j¡t  | j¡@ t  | j¡@ t  | j¡@ |B  }t jt jtj  | j|< | j|< | j|< d||< |S )Nr   T)r/   Úabsr   r   Úchooser   r   r   r!   Ú
zeros_likeÚboolÚdxr
   r	   Útolr   r   ÚeimÚ_ECONVERGEDr   r0   ÚnanÚ	_ESIGNERRÚisfiniteÚ
_EVALUEERR)r+   ÚiÚstopr   r   r,   Úcheck_termination   s.    (
ÿ
ÿÿ(z(_chandrupatla.<locals>.check_terminationc                 S   s  | j | j | j| j  }| j| j | j| j  }| j| j  | j| j   }dt d| ¡ |k |t |¡k @ }| j| | j| | j| || f\}}}}t |d¡}	|||  | ||  || ||  | ||   |	|< d| j	 | j
 }
t |	|
d|
 ¡| _d S )Nr   r   )r   r   r   r   r   r   r/   ÚsqrtÚ	full_liker9   r8   Zclipr   )r+   Zxi1Zphi1Úalphar2   Zf1jZf2jZf3jZalphajr   Útlr   r   r,   Úpost_termination_check¿   s    $*ÿz-_chandrupatla.<locals>.post_termination_checkc                 S   sˆ   | d | d | d | d f\}}}}| d | d k }t  |||f¡| d< t  |||f¡| d< t  |||f¡| d< t  |||f¡| d< |S ©Nr%   r(   r'   r)   ©r/   r5   ©ÚresÚshaper%   r(   r'   r)   r@   r   r   r,   Úcustomize_resultÐ   s    $z'_chandrupatla.<locals>.customize_result)Ú_chandrupatla_ivr:   Ú_initializer/   rD   Ú_EINPROGRESSÚintr   r   ÚfinfoÚtinyÚminimumr4   r   Ú_loop)ÚfuncÚaÚbr   r	   r
   r   r   r   r   rK   ÚtempÚxsÚfsrL   r   r   r   r   r   r   r   r   r+   Úres_work_pairsr-   r3   rB   rG   rM   r   r   r,   Ú_chandrupatla   s8    r
ÿþ
"	þr]   c           
      C   sî   t | ƒstdƒ‚t |¡s |f}t |d ur0|nd|d ur>|nd|d urL|nd|d urZ|ndg¡}t |jtj¡ršt |dk ¡sšt t 	|¡¡sš|j
dkr¢tdƒ‚t|ƒ}	||	ksº|dk rÂtdƒ‚|d urÚt |ƒsÚtdƒ‚| |||||||fS )Nz`func` must be callable.r   r   )é   z(Tolerances must be non-negative scalars.z)`maxiter` must be a non-negative integer.z`callback` must be callable.)ÚcallableÚ
ValueErrorr/   ÚiterableZasarrayZ
issubdtyper   ÚnumberÚanyÚisnanrL   rQ   )
rV   r   r	   r
   r   r   r   r   ZtolsZmaxiter_intr   r   r,   rN   Þ   s*    
ýÿÿrN   éd   c          !      C   sÎ  t | ||||||	|
ƒ}|\} }}}}}}	}
|||f}t | ||¡}|\} }}}}}|\}}}|\}}}| d¡}tj|tjtd}d\}}|du ržt |¡j	n|}|du r¶t |¡j	n|}|du rÎt |¡j	n|}|du rìt 
t |¡j¡n|}t |||f¡t |||f¡ }}tj|dd}tj||dd\}}}tj||dd\}}}| ¡ }t||||||||||||||||d}g d¢}d	d
„ }dd„ }dd„ }dd„ }dd„ } t ||
||	| ||||||| |¡S )a¦  Find the minimizer of an elementwise function.

    For each element of the output of `func`, `_chandrupatla_minimize` seeks
    the scalar minimizer that minimizes the element. This function allows for
    `x1`, `x2`, `x3`, and the elements of `args` to be arrays of any
    broadcastable shapes.

    Parameters
    ----------
    func : callable
        The function whose minimizer is desired. The signature must be::

            func(x: ndarray, *args) -> ndarray

         where each element of ``x`` is a finite real and ``args`` is a tuple,
         which may contain an arbitrary number of arrays that are broadcastable
         with `x`. ``func`` must be an elementwise function: each element
         ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``.
         `_chandrupatla` seeks an array ``x`` such that ``func(x)`` is an array
         of minima.
    x1, x2, x3 : array_like
        The abscissae of a standard scalar minimization bracket. A bracket is
        valid if ``x1 < x2 < x3`` and ``func(x1) > func(x2) <= func(x3)``.
        Must be broadcastable with one another and `args`.
    args : tuple, optional
        Additional positional arguments to be passed to `func`.  Must be arrays
        broadcastable with `x1`, `x2`, and `x3`. If the callable to be
        differentiated requires arguments that are not broadcastable with `x`,
        wrap that callable with `func` such that `func` accepts only `x` and
        broadcastable arrays.
    xatol, xrtol, fatol, frtol : float, optional
        Absolute and relative tolerances on the minimizer and function value.
        See Notes for details.
    maxiter : int, optional
        The maximum number of iterations of the algorithm to perform.
    callback : callable, optional
        An optional user-supplied function to be called before the first
        iteration and after each iteration.
        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
        similar to that returned by `_chandrupatla_minimize` (but containing
        the current iterate's values of all variables). If `callback` raises a
        ``StopIteration``, the algorithm will terminate immediately and
        `_chandrupatla_minimize` will return a result.

    Returns
    -------
    res : _RichResult
        An instance of `scipy._lib._util._RichResult` with the following
        attributes. (The descriptions are written as though the values will be
        scalars; however, if `func` returns an array, the outputs will be
        arrays of the same shape.)

        success : bool
            ``True`` when the algorithm terminated successfully (status ``0``).
        status : int
            An integer representing the exit status of the algorithm.
            ``0`` : The algorithm converged to the specified tolerances.
            ``-1`` : The algorithm encountered an invalid bracket.
            ``-2`` : The maximum number of iterations was reached.
            ``-3`` : A non-finite value was encountered.
            ``-4`` : Iteration was terminated by `callback`.
            ``1`` : The algorithm is proceeding normally (in `callback` only).
        x : float
            The minimizer of the function, if the algorithm terminated
            successfully.
        fun : float
            The value of `func` evaluated at `x`.
        nfev : int
            The number of points at which `func` was evaluated.
        nit : int
            The number of iterations of the algorithm that were performed.
        xl, xm, xr : float
            The final three-point bracket.
        fl, fm, fr : float
            The function value at the bracket points.

    Notes
    -----
    Implemented based on Chandrupatla's original paper [1]_.

    If ``x1 < x2 < x3`` are the points of the bracket and ``f1 > f2 <= f3``
    are the values of ``func`` at those points, then the algorithm is
    considered to have converged when ``x3 - x1 <= abs(x2)*xrtol + xatol``
    or ``(f1 - 2*f2 + f3)/2 <= abs(f2)*frtol + fatol``. Note that first of
    these differs from the termination conditions described in [1]_. The
    default values of `xrtol` is the square root of the precision of the
    appropriate dtype, and ``xatol=fatol = frtol`` is the smallest normal
    number of the appropriate dtype.

    References
    ----------
    .. [1] Chandrupatla, Tirupathi R. (1998).
        "An efficient quadratic fit-sectioning algorithm for minimization
        without derivatives".
        Computer Methods in Applied Mechanics and Engineering, 152 (1-2),
        211-217. https://doi.org/10.1016/S0045-7825(97)00190-4

    See Also
    --------
    golden, brent, bounded

    Examples
    --------
    >>> from scipy.optimize._chandrupatla import _chandrupatla_minimize
    >>> def f(x, args=1):
    ...     return (x - args)**2
    >>> res = _chandrupatla_minimize(f, -5, 0, 5)
    >>> res.x
    1.0
    >>> c = [1, 1.5, 2]
    >>> res = _chandrupatla_minimize(f, -5, 0, 5, args=(c,))
    >>> res.x
    array([1. , 1.5, 2. ])
    g¨ô—›wãù?r   )r   é   Nr   )Zaxis)r   r   r   r   r   r   Úphir	   r
   r   r   r   r   r   Úq0r   )r   )r   r   )r    r   r"   r#   r$   )Zxmr   )r(   r   r&   )Úfmr   )r)   r   c                 S   sþ   | j | j }| j| j  }|| j| j  }|| j| j  }|||  }d|| j| j  | j  | j  }t|| j ƒdt|ƒ k }|| }t|| | j |  ƒ| j| k}	| j | |	 t	 
|| |	 ¡| j| |	   ||	< | j d| j |  }
||
|< || _|
S )Nr   r   )r   r   r   r   r   r   r4   rh   Úxtolr/   r0   rg   )r+   Zx21Zx32ÚAÚBÚCÚq1r@   Úxir2   r   r   r   r,   r-   ‘  s      2z-_chandrupatla_minimize.<locals>.pre_func_evalc                 S   s  t  | |j ¡t  |j|j ¡k}| | |j| |j| |j| f\}}}}|| |j| |j| |j| f\}}	}
}||
k}|| ||  ||< ||< | }|| |
| || || f\||< |	|< ||< |
|< | }| | |j| |j| |j| f\}}}}|| |j| |j| |j| f\}}}}||k}|| ||  ||< ||< | }|| || || || f\||< ||< ||< ||< |||  |j|< |j|< |j|< |	|
|  |j|< |j|< |j|< |||  |j|< |j|< |j|< |||  |j|< |j|< |j|< d S r*   )r/   r0   r   r   r   r   r   r   )r   r1   r+   r@   ro   Zx1iZx2iZx3iÚfiZf1iZf2iZf3ir2   ÚniZxniZx1niZx2niZx3niZfniZf1niZf2niZf3nir   r   r,   r3   ¶  s$    "**4**4"""z._chandrupatla_minimize.<locals>.post_func_evalc                 S   s²  t j| jtd}| j| jk| j| jkB }t jt j | j|< | j|< dt	j
 ||< | j|< t  | j| j | j | j | j | j ¡}||B  }t jt j | j|< | j|< dt	j ||< | j|< t| j| j ƒt| j| j ƒk }| j| }| j| | j|< || j|< | j| }| j| | j|< || j|< t| jƒ| j | j | _t| j| j ƒd| j k}t| jƒ| j | j }|| jd| j  | j d| kO }|| M }dt	j ||< | j|< |S )Nr   Tr   )r/   r6   r   r7   r   r   r   r<   r   r:   r=   r   r>   r   r?   r4   r
   r	   rj   r   r   r;   )r+   rA   r@   ZfiniterY   Zftolr   r   r,   rB   Ð  s,    *
 



"
z1_chandrupatla_minimize.<locals>.check_terminationc                 S   s   d S r*   r   )r+   r   r   r,   rG   þ  s    z6_chandrupatla_minimize.<locals>.post_termination_checkc                 S   sˆ   | d | d | d | d f\}}}}| d | d k }t  |||f¡| d< t  |||f¡| d< t  |||f¡| d< t  |||f¡| d< |S rH   rI   rJ   r   r   r,   rM     s    $z0_chandrupatla_minimize.<locals>.customize_result)rN   r:   rO   Útyper/   rD   rP   rQ   rR   rS   rC   ÚepsZvstackZargsortZtake_along_axisr.   r   rU   )!rV   r   r   r   r   r	   r
   r   r   r   r   rK   rZ   rY   r[   rL   r   r   r   r   rg   r   r   r   r@   rh   r+   r\   r-   r3   rB   rG   rM   r   r   r,   Ú_chandrupatla_minimizeú   sF    u
ÿ



"
þ%.	þrt   )Únumpyr/   Z	_zeros_pyr   r   r   Z(scipy._lib._elementwise_iterative_methodZ_libZ_elementwise_iterative_methodr:   Zscipy._lib._utilr   r]   rN   rt   r   r   r   r,   Ú<module>   s   ÿ Yþ