o
    4BiZ                     @   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 rAtn|}|du rItn|}|du rUt	|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   \/var/www/html/Trade-python/venv/lib/python3.10/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+   j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_liker:   r9   clipr   )r+   xi1phi1alphar2   f1jf2jf3jalphajr   tlr   r   r,   post_termination_check   s   $*z-_chandrupatla.<locals>.post_termination_checkc                 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/   r6   resshaper%   r(   r'   r)   rA   r   r   r,   customize_result      $z'_chandrupatla.<locals>.customize_result)_chandrupatla_ivr;   _initializer/   rE   _EINPROGRESSintr   r   finfotinyminimumr5   r   _loop)funcabr   r	   r
   r   r   r   r   rT   tempxsfsrU   r   r   r   r   r   r   r   r   r+   res_work_pairsr-   r4   rC   rO   rV   r   r   r,   _chandrupatla   s8   
r
"	rg   c           
      C   s   t | stdt|s|f}t|d ur|nd|d ur|nd|d ur&|nd|d ur-|ndg}t|jtjrMt|dk sMtt	|sM|j
dkrQtdt|}	||	ks]|dk ratd|d urmt |smt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/   iterableasarray
issubdtyper   numberanyisnanrU   r[   )
r`   r   r	   r
   r   r   r   r   tolsmaxiter_intr   r   r,   rX      s(   

rX   d   c          !      C   s  t | ||||||	|
}|\} }}}}}}	}
|||f}t| ||}|\} }}}}}|\}}}|\}}}|d}tj|tjtd}d\}}|du rOt|j	n|}|du r[t|j	n|}|du rgt|j	n|}|du rvt
t|jn|}t|||ft|||f}}tj|dd}tj||dd\}}}tj||dd\}}}| }td"i d|d|d	|d
|d|d|d|d|d|d|d|d|d|d|d|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. ])
    gw?r   )r      Nr   )axisr   r   r   r   r   r   phir	   r
   r   r   r   r   r   q0r   )r   )r   r   )r    r   r"   r#   r$   )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   r5   rw   xtolr/   r0   rv   )r+   x21x32ABCq1rA   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+   rA   r   x1ix2ix3ifif1if2if3ir2   nixnix1nix2nix3nifnif1nif2nif3nir   r   r,   r4     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/   r7   r   r8   r   r   r   r=   r   r;   r>   r   r?   r   r@   r5   r
   r	   rz   r   r   r<   )r+   rB   rA   finiterc   ftolr   r   r,   rC     s,   *
 



"
z1_chandrupatla_minimize.<locals>.check_terminationc                 S   s   d S r*   r   )r+   r   r   r,   rO     s   z6_chandrupatla_minimize.<locals>.post_termination_checkc                 S   rP   rQ   rR   rS   r   r   r,   rV     rW   z0_chandrupatla_minimize.<locals>.customize_resultr   )rX   r;   rY   typer/   rE   rZ   r[   r\   r]   rD   epsvstackargsorttake_along_axisr.   r   r_   )!r`   r   r   r   r   r	   r
   r   r   r   r   rT   rd   rc   re   rU   r   r   r   r   rv   r   r   r   rA   rw   r+   rf   r-   r4   rC   rO   rV   r   r   r,   _chandrupatla_minimize   sd   
u



"2%.	r   )numpyr/   	_zeros_pyr   r   r   (scipy._lib._elementwise_iterative_method_lib_elementwise_iterative_methodr;   scipy._lib._utilr   rg   rX   r   r   r   r   r,   <module>   s     Y