
    ^Mh?`                     ~    d dl Z d dlZd dlmc mZ d dlmZ d dl	m
Z
mZmZ ddddd ddddZd Zddddddddd	ZdS )
    N)_RichResult)xp_signxp_copyxp_take_along_axis )argsxatolxrtolfatolfrtolmaxitercallbackc                4   t          | |||||||	          }
|
\  } }}}}}}}	t          j        | ||f|          }|\  } }}}}}|\  }}|\  }}                    |                    t          j                  j                  }d\  }}                    |          }|
d|j        z  n|}|
d|j	        z  n|}||j        n|}|
                                        |                              |                    z  }|3t          j        |j                  t          j        |j                  z
  n|}t          ||||ddd|||||||          }g d}d }fd	}fd
}fd}fd}t          j        ||	||| ||||||||          S )aZ  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.
        The default is the maximum possible number of bisections within
        the (normal) floating point numbers of the relevant dtype.
    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 = 4*tiny``, ``xrtol = 4*eps``, ``frtol = 0``, and ``fatol = tiny``,
    where ``eps`` and ``tiny`` are the precision and smallest normal number
    of the result ``dtype`` of function inputs and outputs.

    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                 D    | j         | j        | j        | j         z
  z  z   }|S N)r   r   r   )workr    s     \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_chandrupatla.pypre_func_evalz$_chandrupatla.<locals>.pre_func_eval   s#    Gdf$' 122    c                                         |j        d                               |j        d          c|_        |_                            |                              |j                  k    }| }|j        |         |j        |         c|j        |<   |j        |<   |j        |         |j        |         c|j        |<   |j        |<   | |c|_        |_        d S )NT)copy)asarrayr   r   r   r   signr   r   )r    fr.   jnjxps        r/   post_func_evalz%_chandrupatla.<locals>.post_func_eval   s     JJtwTJ::JJtwTJ:: 	GGAJJ"''$'***R!%TWQZ
DGAJ#'72; TWR[ar1   c                                         | j                                       | j                  k     }                    || j        | j                  | _                            || j        | j                  | _                            | j        j	                  }                     | j                  | j
        | j        z   k    }t          j        | j        |<   d||<   t          | j                  t          | j                  k    | z  }                    j        | j        j                  }||t          j        c| j        |<   | j        |<   | j        |<   d||<                       | j                                      | j                  z   }                    | j                                      | j                  z  }||z  | z  }||t          j        c| j        |<   | j        |<   | j        |<   d||<                        | j        | j        z
            | _                             | j                  | j        z  | j        z   | _        | j        | j        k     }t          j        | j        |<   d||<   |S )Nr   T)absr   r   wherer   r   r!   r#   
zeros_likeboolr   r   eim_ECONVERGEDr   r   r4   nanr   	_ESIGNERRisfiniteisnan
_EVALUEERRdxr
   r	   tol)r.   istopNaNx_nonfinitef_nanr9   s         r/   check_terminationz(_chandrupatla.<locals>.check_termination   s   
 FF47OObffTWoo-HHQ11	HHQ11	}}TWBG}44 FF49dj!88AQ TW!1!11dU:jjtyj7758#s}2	!dilDKNQ DG,,r{{47/C/CCD!!BHHTW$5$555 TE)58#s~2	!dilDKNQ &&47*++66$)$$tz1DJ>GdhAQr1   c                    | j         | j        z
  | j        | j        z
  z  }t          j        dd          5  | j        | j        z
  | j        | j        z
  z  }d d d            n# 1 swxY w Y   | j        | j         z
  | j        | j         z
  z  }d                    d|z
            z
  |k     |                    |          k     z  }| j        |         | j        |         | j        |         ||         f\  }}}}	                    |
                    d                    }	|||z
  z  |z  ||z
  z  ||z  ||z
  z  |z  ||z
  z  z
  |	|<   d| j        z  | j        z  }
                    |	|
d|
z
            | _        d S )Nignore)divideinvalid   r   )r   r   r   nperrstater   r   r   sqrt	full_liker4   rH   rG   clipr   )r.   xi1phi1alphar7   f1jf2jf3jalphajr   tlr9   s              r/   post_termination_checkz-_chandrupatla.<locals>.post_termination_check   s   w TWtw%67[(;;; 	= 	=Gdg%$'DG*;<D	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	= 	=47"tw'89"''!c'"""d*tbggcll/BC $
DGAJ
E!H LS#vLL

300sSy!C'3953,#),s2cCi@A!
 48^dg%BB''s    A##A'*A'c                 B   | d         | d         | d         | d         f\  }}}}| d         | d         k     }                     |||          | d<                        |||          | d<                        |||          | d<                        |||          | d<   |S Nr'   r*   r)   r+   r=   resshaper'   r*   r)   r+   rI   r9   s          r/   customize_resultz'_chandrupatla.<locals>.customize_result   s    TCIs4y#d)CBBID	!HHQB''D	HHQB''D	HHQB''D	HHQB''D	r1   r9   )_chandrupatla_ivr@   _initializerW   r4   _EINPROGRESSint32finfosmallest_normalepsminimumr<   mathlog2maxr   _loop) funcabr   r	   r
   r   r   r   r   rf   tempxsfsrg   r   r   r   r   r   r   r   r   rn   r.   res_work_pairsr0   r:   rN   ra   rh   r9   s                                   @r/   _chandrupatlar}      sR   h 4ue %(< <C@C=D$ueUGX ?4!Q..D+/(D"b$ubFBFB\\"bjj)9:: "  * *FICHHUOOE',}Ae###%E =AeiKKeE%*]E!!EBJJrvvbzz266"::666E/ y##di0E&F&FFF'. "rdts"%uET&: : :D@ @ @N  
	  	  	  	  	 ) ) ) ) )V( ( ( ( ($     9T8UGT4"N4E+-=~   r1   c                 `   t          |           st          d          t          j        |          s|f}t          j        ||nd||nd||nd||ndg          }t          j        |j        t          j                  rIt          j        |dk               s1t          j        t          j	        |                    s|j
        dk    rt          d          |*t          |          }	||	k    s|dk     rt          d          |t          |          st          d          | |||||||fS )Nz`func` must be callable.rS   r   )r   z(Tolerances must be non-negative scalars.z)`maxiter` must be a non-negative integer.z`callback` must be callable.)callable
ValueErrorrT   iterabler4   
issubdtyper   numberanyrE   rg   int)
rv   r   r	   r
   r   r   r   r   tolsmaxiter_ints
             r/   rj   rj      sU    D>> 53444;t w : 1uuq % 1uuq % 1uuq % 1uuq: ; ;D M$*bi00 EBF4!84D4D Evbhtnn%%E)-t););CDDD'llk!!Wq[[HIIIHX$6$67888ueUE7HDDr1   d   c                b  ! t          | ||||||	|
          }|\  } }}}}}}	}
|||f}t          j        | ||          }|\  } }}}}}!|\  }}}|\  }}}!                    d|          d         }!                    |!                    t          j                  !j                  }d\  }}|!                    |          j        n|}|!                    |          j        n|}|!                    |          j        n|}|,t          j
        !                    |          j                  n|}!                    |||f          !                    |||f          }}!                    |d          }t          ||d          \  }}}t          ||d          \  }}}t          |          }t!          di d|d	|d
|d|d|d|d|d|d|d|d|d|d|d|d|d|}g d}!fd}d }!fd}d }!fd} t          j        ||
||	| ||||||| |!          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   )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                    | j         | j        z
  }| j        | j         z
  }|| j        | j        z
  z  }|| j        | j        z
  z  }|||z   z  }d|| j        | j        z
  z  | j         z   | j        z   z  }                    || j        z
            d                    |          z  k     }||         }                    ||         | j         |         z
            | j        |         k    }	| j         |         |	         t          ||         |	                   | j        |         |	         z  z   ||	<   | j         d| j
        z
  |z  z   }
||
|<   || _        |
S )Nr   r   )r   r   r   r   r   r   r<   r   xtolr   r   )r.   x21x32ABCq1rI   xir7   r    r9   s              r/   r0   z-_chandrupatla_minimize.<locals>.pre_func_eval  sF    gg 47TW$%47TW$%QKAtw()DG3dg=>
 FF2<  3#44U
 FF2a5471:%&&$)A,6
1Aq	 2 2TYq\!_ DD1 Gq48|s**! r1   c                 :   t          | |j        z
            t          |j        |j        z
            k    }| |         |j        |         |j        |         |j        |         f\  }}}}||         |j        |         |j        |         |j        |         f\  }}	}
}||
k    }||         ||         c||<   ||<   | }||         |
|         ||         ||         f\  ||<   |	|<   ||<   |
|<   | }| |         |j        |         |j        |         |j        |         f\  }}}}||         |j        |         |j        |         |j        |         f\  }}}}||k    }||         ||         c||<   ||<   | }||         ||         ||         ||         f\  ||<   ||<   ||<   ||<   |||c|j        |<   |j        |<   |j        |<   |	|
|c|j        |<   |j        |<   |j        |<   |||c|j        |<   |j        |<   |j        |<   |||c|j        |<   |j        |<   |j        |<   d S r-   )r   r   r   r   r   r   r   )r    r6   r.   rI   r   x1ix2ix3ifif1if2if3ir7   nixnix1nix2nix3nifnif1nif2nif3nis                         r/   r:   z._chandrupatla_minimize.<locals>.post_func_eval  s9   
 AK  GDGdg,=$>$>>aD$'!*dgaj$'!*ECcaD$'!*dgaj$'!*DCcHA1AAB),QQA1)E&AAAAR !"twr{DGBK MT4 !"twr{DGBK LT4$Jq63q6QaB-1!Wd1gs1vs1v-M*Qa$q'47-0#s*
DGAJ
-0#s*
DGAJ
04dD-TWR[$'"+04dD-TWR[$'"+++r1   c                                         | j        t                    }| j        | j        k    | j        | j        k    z  }j        j        c| j        |<   | j        |<   dt          j	        c||<   | j
        |<                       | j        | j        z   | j        z   | j        z   | j        z   | j        z             }||z   }j        j        c| j        |<   | j        |<   dt          j        c||<   | j
        |<                       | j        | j        z
                                | j        | j        z
            k     }| j        |         }| j        |         | j        |<   || j        |<   | j        |         }| j        |         | j        |<   || j        |<                       | j                  | j        z  | j        z   | _                            | j        | j        z
            d| j        z  k    }                    | j                  | j        z  | j        z   }|| j        d| j        z  z
  | j        z   d|z  k    z  }|| z  }dt          j        c||<   | j
        |<   |S )Nr   Tr   )r>   r   r?   r   r   r   rB   r   r@   rC   r   rD   r   rF   r<   r
   r	   r   r   r   rA   )r.   rJ   rI   finitery   ftolr9   s         r/   rN   z1_chandrupatla_minimize.<locals>.check_termination  s#   }}TWD}11 gDGdg$56!#
DGAJ"&QQ TWTW_TW4TW<TWDTWLMMtm!#
DGAJ"&QQ FF47TW$%%tw/@(A(AAwqzWQZ

wqzWQZ

 FF47OOdj04:=	 FF47TW$%%TY6 vvdg+dj8 	
dgDG#dg-!D&88	dU
"&QQr1   c                     d S r-   r   )r.   s    r/   ra   z6_chandrupatla_minimize.<locals>.post_termination_check  s    r1   c                 B   | d         | d         | d         | d         f\  }}}}| d         | d         k    }                     |||          | d<                        |||          | d<                        |||          | d<                        |||          | d<   |S rc   rd   re   s          r/   rh   z0_chandrupatla_minimize.<locals>.customize_result  s    TCIs4y#d)CBBIT"HHQB''D	HHQB''D	HHQB''D	HHQB''D	r1   ri   )rj   r@   rk   r4   rW   rl   rm   rn   ro   rr   rV   rp   stackargsortr   r   r   ru   )"rv   r   r   r   r   r	   r
   r   r   r   r   rf   rz   ry   r{   rg   r   r   r   r   r   r   r   r   rI   r   r.   r|   r0   r:   rN   ra   rh   r9   s"                                    @r/   _chandrupatla_minimizer     sQ   j 4ue %(< <C@C=D$ueUGX b"B?4T**D+/(D"b$ubJBBJBB
**%U*
3
3B
7C\\"bjj)9:: "  * *FIC/4}BHHUOO++%E/4}BHHUOO++%E/4}BHHUOO++%E.3mDIbhhuoo)***E XXr2rl##RXXr2rl%;%;B


2A
A#B222JBB#B222JBB	B L L L"" L L Lrr Lbb LRR LSS L"UL*/%L7<uLDIEL3L%)TL28&L=?RLFJdLD@ @ @N# # # # #JA A A4, , , , ,\       9T8UGT4"N4E+-=~   r1   )rr   numpyrT   (scipy._lib._elementwise_iterative_method_lib_elementwise_iterative_methodr@   scipy._lib._utilr   scipy._lib._array_apir   r   r   r}   rj   r   r   r1   r/   <module>r      s         6 6 6 6 6 6 6 6 6 ( ( ( ( ( ( F F F F F F F F F F ')DAtdg g g g gTE E E< 68t!%Ts$(T T T T T T Tr1   