
    tfZ                     t    d dl ZddlmZmZmZ d dlmc mZ	 d dl
mZ deedd edddZd Zdddddd	ddd
Zy)    N   )_xtol_rtol_iter)_RichResult )argsxatolxrtolfatolfrtolmaxitercallbackc                x   t        | |||||||	      }
|
\  } }}}}}}}	t        j                  | ||f|      }|\  } }}}}}|\  }}|\  }}t        j                  |t        j
                  t              }d\  }}|t        n|}|t        n|}|t        j                  |      j                  n|}|t        j                  t        j                  |      t        j                  |            z  }t        ||||ddd|||||||      }g d}d }d }d	 }d
 }d }t        j                  ||	||| ||||||||      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                 l    | j                   | j                  | j                  | j                   z
  z  z   }|S N)r   r   r   )workr    s     f/var/www/html/software/conda/envs/higlass/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.pypre_func_evalz$_chandrupatla.<locals>.pre_func_eval   s+    GGdff$'' 122    c                    |j                   j                         |j                  j                         c|_        |_        t        j                  |      t        j                  |j                        k(  }| }|j                  |   |j                  |   c|j                  |<   |j                  |<   |j                  |   |j                  |   c|j                   |<   |j                  |<   | |c|_        |_        y r-   )	r   copyr   r   r   npsignr   r   )r    fr.   jnjs        r/   post_func_evalz%_chandrupatla.<locals>.post_func_eval   s      77<<>477<<>GGAJ"''$''**R!%TWWQZ
DGGAJ#'772; TWWR[ar1   c                 6   t        j                  | j                        t        j                  | j                        k  }t        j                  || j
                  | j                  f      | _        t        j                  || j                  | j                  f      | _        t        j                  | j                  t              }t        | j
                  | j                  z
        | _        t        | j                        | j                  z  | j                  z   | _        | j                  | j                  k  }|t        j                  | j                        | j                  | j                   z   k  z  }t"        j$                  | j&                  |<   d||<   t        j(                  | j                        t        j(                  | j                        k(  | z  }t         j*                  t         j*                  t"        j,                  c| j                  |<   | j                  |<   | j&                  |<   d||<   t        j.                  | j                        t        j.                  | j
                        z  t        j.                  | j                        z  t        j.                  | j                        z  |z   }t         j*                  t         j*                  t"        j0                  c| j                  |<   | j                  |<   | j&                  |<   d||<   |S )Nr   T)r4   absr   r   chooser   r   r!   r#   
zeros_likebooldxr   r
   tolr   r   eim_ECONVERGEDr   r5   nan	_ESIGNERRisfinite
_EVALUEERR)r.   istops      r/   check_terminationz(_chandrupatla.<locals>.check_termination   s   
 FF477ObffTWWo-IIa$''477!34	IIa$''477!34	}}TWWD1 dgg'(tyy>DJJ.;GGdhh
 	
RVVDII$**tzz"999AQWWTWW!11dU:57VVRVVS]]2		!diilDKKNQ{{477#bkk$''&::TWW%&(*DGG(<=@DE F57VVRVVS^^2		!diilDKKNQr1   c                    | j                   | j                  z
  | j                  | j                  z
  z  }| j                  | j                  z
  | j
                  | j                  z
  z  }| j                  | j                   z
  | j                  | j                   z
  z  }dt        j                  d|z
        z
  |k  |t        j                  |      k  z  }| j                  |   | j                  |   | j
                  |   ||   f\  }}}}t        j                  |d      }	|||z
  z  |z  ||z
  z  ||z  ||z
  z  |z  ||z
  z  z
  |	|<   d| j                  z  | j                  z  }
t        j                  |	|
d|
z
        | _        y )Nr   r   )r   r   r   r   r   r   r4   sqrt	full_liker@   r?   clipr   )r.   xi1phi1alphar7   f1jf2jf3jalphajr   tls              r/   post_termination_checkz-_chandrupatla.<locals>.post_termination_check   sS   ww TWWtww%67$''!dgg&78477"tww'89"''!c'""d*tbggcl/BC $
DGGAJ
E!H LS#vLL$sSy!C'3953,#),s2cCi@A!
 488^dgg%BB'r1   c                 "   | d   | d   | d   | d   f\  }}}}| d   | d   k  }t        j                  |||f      | d<   t        j                  |||f      | d<   t        j                  |||f      | d<   t        j                  |||f      | d<   |S Nr'   r*   r)   r+   r4   r<   resshaper'   r*   r)   r+   rG   s          r/   customize_resultz'_chandrupatla.<locals>.customize_result       TCIs4y#d)CBBID	!IIa"b*D	IIa"b*D	IIa"b*D	IIa"b*D	r1   )_chandrupatla_ivrA   _initializer4   rL   _EINPROGRESSintr   r   finfotinyminimumr;   r   _loop)funcabr	   r
   r   r   r   r   r   r[   tempxsfsr\   r   r   r   r   r   r   r   r   r.   res_work_pairsr0   r9   rI   rV   r]   s                                 r/   _chandrupatlarn      sd   d 4ue %(<C@C=D$ueUGX ??4!Q.D'+$D"b$uFBFB\\"c..c:FIC]EE]EE$)MBHHUO  uEBJJrvvbz266":66E"rdts"%uET&:D@N
  D(" 99T8UGT4"N4E+-=~O Or1   c                 D   t        |       st        d      t        j                  |      s|f}t        j                  ||nd||nd||nd||ndg      }t        j
                  |j                  t        j                        rOt        j                  |dk        s7t        j                  t        j                  |            s|j                  dk7  rt        d      t        |      }	||	k7  s|dk  rt        d      |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
ValueErrorr4   iterableasarray
issubdtyper   numberanyisnanr\   rb   )
rg   r	   r
   r   r   r   r   r   tolsmaxiter_ints
             r/   r_   r_      s	    D>344;;tw:: 1uq % 1uq % 1uq % 1uq: ;D MM$**bii0BFF4!84Dvvbhhtn%t);CDDg,K+1DEEHX$6788ueUE7HDDr1   d   c                T   t        | ||||||	|
      }|\  } }}}}}}	}
|||f}t        j                  | ||      }|\  } }}}}}|\  }}}|\  }}}|j                  d      }t	        j
                  |t        j                  t              }d\  }}|t	        j                  |      j                  n|}|t	        j                  |      j                  n|}|t	        j                  |      j                  n|}|2t	        j                  t	        j                  |      j                        n|}t	        j                  |||f      t	        j                  |||f      }}t	        j                  |d      }t	        j                  ||d      \  }}}t	        j                  ||d      \  }}}|j                         }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 } 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   )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  }t        || j                  z
        dt        |      z  k  }||   }t        ||   | j                   |   z
        | j                  |   k  }	| j                   |   |	   t        j                  ||   |	         | j                  |   |	   z  z   ||	<   | j                   d| j                  z
  |z  z   }
||
|<   || _        |
S )Nr   r   )r   r   r   r   r   r   r;   r   xtolr4   r5   r   )r.   x21x32ABCq1rG   xir7   r    s              r/   r0   z-_chandrupatla_minimize.<locals>.pre_func_eval  sW    gggg 477TWW$%477TWW$%QKAtww()DGG3dgg=>
 TWWc#h.U
 1
"#tyy|3
1Aq	 2TYYq\!_ DD1 GGq488|s**! r1   c                    t        j                  | |j                  z
        t        j                  |j                  |j                  z
        k(  }| |   |j                  |   |j                  |   |j                  |   f\  }}}}||   |j
                  |   |j                  |   |j                  |   f\  }}	}
}||
kD  }||   ||   c||<   ||<   | }||   |
|   ||   ||   f\  ||<   |	|<   ||<   |
|<   | }| |   |j                  |   |j                  |   |j                  |   f\  }}}}||   |j
                  |   |j                  |   |j                  |   f\  }}}}||kD  }||   ||   c||<   ||<   | }||   ||   ||   ||   f\  ||<   ||<   ||<   ||<   |||c|j                  |<   |j                  |<   |j                  |<   |	|
|c|j
                  |<   |j                  |<   |j                  |<   |||c|j                  |<   |j                  |<   |j                  |<   |||c|j
                  |<   |j                  |<   |j                  |<   y r-   )r4   r5   r   r   r   r   r   r   )r    r6   r.   rG   r   x1ix2ix3ifif1if2if3ir7   nixnix1nix2nix3nifnif1nif2nif3nis                         r/   r9   z._chandrupatla_minimize.<locals>.post_func_eval  sm   
 GGAK BGGDGGdgg,=$>>aD$''!*dggaj$''!*ECcaD$''!*dggaj$''!*DCcHA1AAB),QQA1)E&AAAAR !"twwr{DGGBK MT4 !"twwr{DGGBK LT4$Jq63q6QaB-1!Wd1gs1vs1v-M*Qa$q'47-0#s*
DGGAJ
-0#s*
DGGAJ
04dD-TWWR[$''"+04dD-TWWR[$''"+r1   c                 L   t        j                  | j                  t              }| j                  | j
                  kD  | j                  | j                  kD  z  }t         j                  t         j                  c| j                  |<   | j                  |<   dt        j                  c||<   | j                  |<   t        j                  | j                  | j                  z   | j                  z   | j
                  z   | j                  z   | j                  z         }||z   }t         j                  t         j                  c| j                  |<   | j                  |<   dt        j                  c||<   | j                  |<   t        | j                  | j                  z
        t        | j                  | j                  z
        k  }| j                  |   }| j                  |   | j                  |<   || j                  |<   | j
                  |   }| j                  |   | j
                  |<   || j                  |<   t        | j                        | j                   z  | j"                  z   | _        t        | j                  | j                  z
        d| j$                  z  k  }t        | 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   )r4   r=   r   r>   r   r   r   rC   r   rA   rD   r   rE   r   rF   r;   r   r
   r   r   r   rB   )r.   rH   rG   finiterj   ftols         r/   rI   z1_chandrupatla_minimize.<locals>.check_termination  s[   }}TWWD1 ggDGGdgg$56!#
DGGAJ"&QQ TWWTWW_TWW4TWW<TWWDTWWLMtm!#
DGGAJ"&QQ $''!"S477):%;;wwqzWWQZ

wwqzWWQZ

 L4::-

:	 $''!"a$))m3 477|djj(4::5 	
dggDGG#dgg-!D&88	dU
"&QQr1   c                      y r-   r   )r.   s    r/   rV   z6_chandrupatla_minimize.<locals>.post_termination_check  s    r1   c                 "   | d   | d   | d   | d   f\  }}}}| d   | d   k  }t        j                  |||f      | d<   t        j                  |||f      | d<   t        j                  |||f      | d<   t        j                  |||f      | d<   |S rX   rY   rZ   s          r/   r]   z0_chandrupatla_minimize.<locals>.customize_result  r^   r1   r   )r_   rA   r`   typer4   rL   ra   rb   rc   rd   rK   epsvstackargsorttake_along_axisr3   r   rf   )!rg   r   r   r   r	   r
   r   r   r   r   r   r[   rk   rj   rl   r\   r   r   r   r   r   r   r   r   rG   r   r.   rm   r0   r9   rI   rV   r]   s!                                    r/   _chandrupatla_minimizer      s}   j 4ue %(<C@C=D$ueUGX b"B??4T*D'+$D"b$uJBBJBB
**%
&C\\"c..c:FIC$)MBHHUO  uE$)MBHHUO  uE$)MBHHUO  uE,1MBGGBHHUO''(uE YYB|$biiR&=B


2AA##B2JBB##B2JBB	B L" L L Lr Lb LR LS L"L*/L7<LDILL%)L28L=?LFJLD@N#JA4,\ 99T8UGT4"N4E+-=~O Or1   )numpyr4   	_zeros_pyr   r   r   (scipy._lib._elementwise_iterative_method_lib_elementwise_iterative_methodrA   scipy._lib._utilr   rn   r_   r   r   r1   r/   <module>r      sO     * * 6 6 (&(UAutUOpE8 68t!%Ts$(ROr1   