
    ^MhLz                         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ZdZd Z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)array_namespacexp_ravelxp_default_dtype   c           	      h   t          |           st          d          t          j        |          s|f}t	          |          }|                    |          d         }|                    |j        d          r|                    |j        d          rt          d          |                    |j        d          s$|                    |t          |                    }d}	|	|j	        }d	}	||j
         n|}||j
        n|}|d
n|}|                    ||                    |          |                    |          |                    |          |                    |                    \  }}}}}|                    |j        d          r|                    |j        d          rt          d          |                    |j        d          r|                    |j        d          rt          d          |                    |j        d          r|                    |j        d          rt          d          |                    |j        d          r|                    |j        d          rt          d          |                    |dk              st          d          |	rO||                    ||z
  dz  |                    d                    z   }|                    ||j        d          }|                    |          }d}
|                    |j        d          r2|j        t!                      k    s|                    |j        d          rt          |
          t#          |d                   }||k    r|dk     rt          |
          | ||||||||f	S )N`func` must be callable. numericcomplex floating`xl0` must be numeric and real.real floatingdtypeFT       @`xr0` must be numeric and real. `xmin` must be numeric and real. `xmax` must be numeric and real."`factor` must be numeric and real.   0All elements of `factor` must be greater than 1.   g      ?copy)`maxiter` must be a non-negative integer.r   )callable
ValueErrornpiterabler   asarrayisdtyper   r   naninfbroadcast_arraysallminimumastypeshapetupleint)funcxl0xr0xminxmaxfactorargsmaxiterxpxr0_not_suppliedmessagemaxiter_ints               W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_bracket.py_bracket_root_ivr9   	   s   D>> 53444;t w			B
**S//"
CJJsy),, <::ci!344<:;;;::ci11 :jj$4R$8$8j99
 
{flBF77D\266tD>RRvF#%#6#6RZZ__bjj..

40@0@"**VBTBT$V $V CdD& JJsy),, <::ci!344<:;;;JJtz9-- =::dj"455=;<<<JJtz9-- =::dj"455=;<<<JJv|Y// ?::fl$677?=>>>66&1* MKLLL  4BJJs
Q

3@@@iiSYUi33jj!!G9GJJw}i00 "GMUWW4L4Lzz'-);<< 5M!!!gbk""Kk!!Wq[[!!!c4vtWb@@    r   i  )r/   r0   r1   r2   r3   c                ^  $ d}t          | |||||||          }	|	\	  } }}}}}}}$||f}
t          j        | |
|          }	|	\  } }
}}}}$|
\  }}t          $                    $                    ||          |d          $          }t          $                    $                    ||          |d          $          }||k    ||k     z  ||k    z   }$                    |
          }$                    |          }$                    ||f          }|j        d         dz  }$                    ||d         |d|         f          }$                    ||d         |d|         f          }|}$                    ||f          }t          $                    ||          $          }$                    ||d          }$                    ||f          }$                    d|z            }$fd|D             }|dz   }$	                    |          }| }$
                    |          }||         ||         z
  ||<   ||         ||         z
  ||<   $                    |t          j        $j        	          }t          j        ||<   d
\  }}t          d#i d|d|d|d|d|d|d|d|d|d|d|d|d|d$j        d$j        d$j        d$j        d|}g d}$fd}d } $fd }!d! }"$fd"}#t          j        ||||| |||| |!|"|#|$          S )$a  Bracket the root of a monotonic scalar function of one variable

    This function works elementwise when `xl0`, `xr0`, `xmin`, `xmax`, `factor`, and
    the elements of `args` are broadcastable arrays.

    Parameters
    ----------
    func : callable
        The function for which the root is to be bracketed.
        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``.
    xl0, xr0: float array_like
        Starting guess of bracket, which need not contain a root. If `xr0` is
        not provided, ``xr0 = xl0 + 1``. Must be broadcastable with one another.
    xmin, xmax : float array_like, optional
        Minimum and maximum allowable endpoints of the bracket, inclusive. Must
        be broadcastable with `xl0` and `xr0`.
    factor : float array_like, default: 2
        The factor used to grow the bracket. See notes for details.
    args : tuple, optional
        Additional positional arguments to be passed to `func`.  Must be arrays
        broadcastable with `xl0`, `xr0`, `xmin`, and `xmax`. If the callable to be
        bracketed requires arguments that are not broadcastable with these
        arrays, wrap that callable with `func` such that `func` accepts
        only `x` and broadcastable arrays.
    maxiter : int, optional
        The maximum number of iterations of the algorithm to perform.

    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.

        xl, xr : float
            The lower and upper ends of the bracket, if the algorithm
            terminated successfully.
        fl, fr : float
            The function value at the lower and upper ends of the bracket.
        nfev : int
            The number of function evaluations required to find the bracket.
            This is distinct from the number of times `func` is *called*
            because the function may evaluated at multiple points in a single
            call.
        nit : int
            The number of iterations of the algorithm that were performed.
        status : int
            An integer representing the exit status of the algorithm.

            - ``0`` : The algorithm produced a valid bracket.
            - ``-1`` : The bracket expanded to the allowable limits without finding a bracket.
            - ``-2`` : The maximum number of iterations was reached.
            - ``-3`` : A non-finite value was encountered.
            - ``-4`` : Iteration was terminated by `callback`.
            - ``-5``: The initial bracket does not satisfy `xmin <= xl0 < xr0 < xmax`.
            - ``1`` : The algorithm is proceeding normally (in `callback` only).
            - ``2`` : A bracket was found in the opposite search direction (in `callback` only).

        success : bool
            ``True`` when the algorithm terminated successfully (status ``0``).

    Notes
    -----
    This function generalizes an algorithm found in pieces throughout
    `scipy.stats`. The strategy is to iteratively grow the bracket ``(l, r)``
     until ``func(l) < 0 < func(r)``. The bracket grows to the left as follows.

    - If `xmin` is not provided, the distance between `xl0` and `l` is iteratively
      increased by `factor`.
    - If `xmin` is provided, the distance between `xmin` and `l` is iteratively
      decreased by `factor`. Note that this also *increases* the bracket size.

    Growth of the bracket to the right is analogous.

    Growth of the bracket in one direction stops when the endpoint is no longer
    finite, the function value at the endpoint is no longer finite, or the
    endpoint reaches its limiting value (`xmin` or `xmax`). Iteration terminates
    when the bracket stops growing in both directions, the bracket surrounds
    the root, or a root is found (accidentally).

    If two brackets are found - that is, a bracket is found on both sides in
    the same iteration, the smaller of the two is returned.
    If roots of the function are found, both `l` and `r` are set to the
    leftmost root.

    NFr   r4   r   r   c                 >    g | ]}                     ||f          S r   )concat).0argr4   s     r8   
<listcomp>z!_bracket_root.<locals>.<listcomp>   s)    222cBIIsCj!!222r:   )r   r   )r   r   xx0flimitr1   activedx_lastf_lastnitnfevstatusr2   xlxrflfrn)rL   rL   rM   rM   rN   rN   rJ   rJ   rK   rK   rO   rO   rP   rP   )rB   rB   )rD   rD   )rH   rH   )rI   rI   c                 n                        | j                  }                    | j                  }| j        |xx         | j        |         z  cc<   | j        |         | j        |         z   ||<   | }| j        |xx         | j        |         z  cc<   | j        |         | j        |         z
  ||<   |S N)
zeros_likerB   isinfrE   rG   r1   rC   )workrB   inir4   s       r8   pre_func_evalz$_bracket_root.<locals>.pre_func_eval   s    MM$&!! HHTZ  q			T[^#			wqzDF1I%! Rr


dk"o%



2+"r:   c                 R    |j         |_        |j        |_        | |_         ||_        d S rZ   )rB   rH   rD   rI   rB   rD   r]   s      r8   post_func_evalz%_bracket_root.<locals>.post_func_eval  s(     ffr:   c                 L   | j         t          j        k    }                    | j                  }                    | j                  }|| k    |dk    z  |dk    z  | z  }t          j        | j         |<   d||<   | j        |         | j        z   d| j        z  z  }	                    | j        |          }|| j        j
        d         k     }||         ||         }}||| j        |         k             }                    |          }d||<   || z  }t          | j         |<   d||<   | j        | j        k    | z  }t          | j         |<   d||<                       | j                                      | j                  z   | z  }t          j        | j         |<   d||<   |S )Nr   Tr   )rL   eim
_EINPUTERRsignrD   rI   _ECONVERGEDrF   rQ   searchsortedr)   r[   _ESTOPONESIDErB   rE   _ELIMITSisfinite
_EVALUEERR)	r]   stopsfsf_lastr^   	also_stopjmaskr4   s	           r8   check_terminationz(_bracket_root.<locals>.check_termination  s   s~- WWTV__''$+&&"nA."':teCAQ" [^df,46:	 OODK33
 4;$Q'' w	$9i4;q>)*MM$!I&AQ Vtz!dU*!AQ kk$&!!BKK$7$778D5@AQr:   c                     d S rZ   r   r]   s    r8   post_termination_checkz-_bracket_root.<locals>.post_termination_checkO      r:   c                 `   | d         j         d         dz  }| d         d |         }| d         d |         }| d         |d          }| d         |d          }| d         d |         }| d         d |         }| d         |d          }	| d         |d          }
                    |d          }                    |d          }                    |d          }                    |
d          }| d	         d |         }| d	         |d          }||z
  }||z
  }||k    |dk    z  |dk    |dk    z  z  }||k    |dk    z  |dk    |dk    z  z  }||         ||<   ||         ||<   ||         ||<   |	|         ||<   || d
<   || d<   || d<   || d<                       | d         d |         | d         |d                    | d<   | d         d |         | d         |d          z   | d<                       |dk    ||          | d	<   | d	         dk    | d<   | d= | d= | d= | d= |d d         S )NrB   r   r   rH   rD   rI   Tr   rL   rM   rN   rO   rP   rJ   rK   successr   )r)   r!   maximumwhere)resr)   rQ   xalxarxblxbrfalfarfblfbrrM   rO   rN   rP   sasbdadbi1i2r4   s                        r8   customize_resultz'_bracket_root.<locals>.customize_resultR  s   HN1" #hrrl(mBQB(mABB#hqrrl#hrrl(mBQB(mABB#hqrrl ZZ$Z''ZZ$Z''ZZ$Z''ZZ$Z'' ]2A2]1223Y3YRxB!G$"'bAg)>?RxB!G$"'bAg)>?R2R2R2R2 D	D	D	D	ZZE
2A2E
122??E
&k"1"oFABB7F q"b11Hh-1,IHHMMSbSzr:   r   )r9   re   _initializer   r(   broadcast_tor>   r)   aranger\   r[   	full_like_EINPROGRESSint32rf   r   r#   _loop)%r,   r-   r.   r/   r0   r1   r2   r3   callbacktempxsfsr)   r   invalid_bracketrB   rD   rQ   rH   rI   rC   rE   rF   r^   r_   rG   rL   rJ   rK   r]   res_work_pairsr`   rc   rt   rw   r   r4   s%                                       @r8   _bracket_rootr   K   sX   J HD#sD$gNND<@9D#sD$gr
sB?4T**D+/(D"b$ubHCBIIboodE::EINNSUVVVDBIIboodE::EINNSUVVVDs3sd{CDO 			"A
		"Aii/ BCCO	
aA
 YY!""q!u~&&FYY!""q!u~&&F	B IItTl##Eboofe44<<<FYYvu5Y11FYY'((FYYqs^^F2222T222D DLE 	A
B
aAQ4"Q%<AaD"I"AbE\\!S-RX\>>F!nF?IC H H H Hrr HQQ Hee HFF H$fH()H28&HAGH3H%)TH28&H?CtH &&H &(VVH 13H <>66H FGQHDB B BN
    $  = = = = =~  J J J J JX 9T8UGT4"N4E+-=~  r:   c	           
         t          |           st          d          t          j        |          s|f}t	          |          }	|	                    |          d         }|	                    |j        d          r|	                    |j        d          rt          d          |	                    |j        d          s$|	                    |t          |	                    }||	j	         n|}||	j	        n|}d}
|	|	j
        }d	}
d}|	|	j
        }d	}|d
n|}|	                    |	                    |          ||	                    |          |	                    |          |	                    |          |	                    |                    \  }}}}}}|	                    |j        d          r|	                    |j        d          rt          d          |	                    |j        d          r|	                    |j        d          rt          d          |	                    |j        d          r|	                    |j        d          rt          d          |	                    |j        d          r|	                    |j        d          rt          d          |	                    |j        d          r|	                    |j        d          rt          d          |	                    |dk              st          d          |
rO||	                    ||z
  dz  |	                    d                    z
  }|	                    ||j        d          }|rO||	                    ||z
  dz  |	                    d                    z   }|	                    ||j        d          }|	                    |          }d}|	                    |j        d          r2|j        t!                      k    s|	                    |j        d          rt          |          t#          |d                   }||k    r|dk     rt          |          | |||||||||	f
S )Nr
   r   r   r   z`xm0` must be numeric and real.r   r   FTr   r   r   r   r   r   r   r      g      ?r   r   r   )r   r   r   r    r   r!   r"   r   r   r$   r#   r%   r&   r'   r(   r)   r*   r+   )r,   xm0r-   r.   r/   r0   r1   r2   r3   r4   xl0_not_suppliedr5   r6   r7   s                 r8   _bracket_minimum_ivr     sK   D>> 53444;t w			B
**S//"
CJJsy),, <::ci!344<:;;;::ci11 :jj$4R$8$8j99lBF77D\266tD
 
{f
{fNSSF(*(;(;


3bjjoorzz$/?/?


4"**V,,) )%Cc4v
 JJsy),, <::ci!344<:;;;JJsy),, <::ci!344<:;;;JJtz9-- =::dj"455=;<<<JJtz9-- =::dj"455=;<<<JJv|Y// ?::fl$677?=>>>66&1* MKLLL
  4BJJd
B

3@@@iiSYUi33 4BJJs
B

3@@@iiSYUi33jj!!G9GJJw}i00 "GMUWW4L4Lzz'-);<< 5M!!!gbk""Kk!!Wq[[!!!c3dFD'2EEr:   )r-   r.   r/   r0   r1   r2   r3   c                  " d}	t          | ||||||||	  	        }
|
\
  } }}}}}}}}"|||f}t          j        | ||          }
|
\  } }}}}}"|\  }}}|\  }}}"                    "                    ||          |d          }t          |"          }"                    "                    ||          |d          }t          |"          }||k    ||k     z  ||k     z  ||k    z   }"                    "                    ||          |d          }t          |          }||k     }||         ||         c||<   ||<   ||         ||         c||<   ||<   "                    |||          }"                    |          }| }"                    |          }||         ||         z
  ||<   ||         ||         z
  ||<   d||         z  ||<   "	                    |t          j
        "j                  }t          j        ||<   d\  }}t          |||||||||||||||	          }g d
}"fd}d }"fd}d } d }!t          j        ||	||| |||||| |!|"          S )a[  Bracket the minimum of a unimodal scalar function of one variable

    This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`,
    and the elements of `args` are broadcastable arrays.

    Parameters
    ----------
    func : callable
        The function for which the minimum is to be bracketed.
        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`.
    xm0: float array_like
        Starting guess for middle point of bracket.
    xl0, xr0: float array_like, optional
        Starting guesses for left and right endpoints of the bracket. Must be
        broadcastable with one another and with `xm0`.
    xmin, xmax : float array_like, optional
        Minimum and maximum allowable endpoints of the bracket, inclusive. Must
        be broadcastable with `xl0`, `xm0`, and `xr0`.
    factor : float array_like, optional
        Controls expansion of bracket endpoint in downhill direction. Works
        differently in the cases where a limit is set in the downhill direction
        with `xmax` or `xmin`. See Notes.
    args : tuple, optional
        Additional positional arguments to be passed to `func`.  Must be arrays
        broadcastable with `xl0`, `xm0`, `xr0`, `xmin`, and `xmax`. If the
        callable to be bracketed requires arguments that are not broadcastable
        with these arrays, wrap that callable with `func` such that `func`
        accepts only ``x`` and broadcastable arrays.
    maxiter : int, optional
        The maximum number of iterations of the algorithm to perform. The number
        of function evaluations is three greater than the number of iterations.

    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.

        xl, xm, xr : float
            The left, middle, and right points of the bracket, if the algorithm
            terminated successfully.
        fl, fm, fr : float
            The function value at the left, middle, and right points of the bracket.
        nfev : int
            The number of function evaluations required to find the bracket.
        nit : int
            The number of iterations of the algorithm that were performed.
        status : int
            An integer representing the exit status of the algorithm.

            - ``0`` : The algorithm produced a valid bracket.
            - ``-1`` : The bracket expanded to the allowable limits. Assuming
                       unimodality, this implies the endpoint at the limit is a
                       minimizer.
            - ``-2`` : The maximum number of iterations was reached.
            - ``-3`` : A non-finite value was encountered.
            - ``-4`` : ``None`` shall pass.
            - ``-5`` : The initial bracket does not satisfy
                       `xmin <= xl0 < xm0 < xr0 <= xmax`.

        success : bool
            ``True`` when the algorithm terminated successfully (status ``0``).

    Notes
    -----
    Similar to `scipy.optimize.bracket`, this function seeks to find real
    points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``,
    where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`,
    this function can operate in a vectorized manner on array input, so long as
    the input arrays are broadcastable with each other. Also unlike
    `scipy.optimize.bracket`, users may specify minimum and maximum endpoints
    for the desired bracket.

    Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``,
    the algorithm checks if these points already give a valid bracket. If not,
    a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new
    opposite endpoint, and either `xl` or `xr` becomes the new middle point,
    depending on which direction is downhill. The algorithm repeats from here.

    The new endpoint `w` is chosen differently depending on whether or not a
    boundary `xmin` or `xmax` has been set in the downhill direction. Without
    loss of generality, suppose the downhill direction is to the right, so that
    ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w`
    is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by
    the user (defaults to 2.0) so that step sizes increase in geometric proportion.
    If there is a boundary, `xmax` in this case, then `w` is chosen to be
    ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at
    `xmax`. This cautious approach ensures that a minimum near but distinct from
    the boundary isn't missed while also detecting whether or not the `xmax` is
    a minimizer when `xmax` is reached after a finite number of steps.
    NFr   r<   Tr   r   )r      )rM   xmrN   r.   rO   fmrP   steprE   limitedr1   rJ   rK   rL   r2   )	rR   rS   )r   r   rT   rU   rV   rW   )r   r   rX   c                    | xj         | j        z  c_                             | j                  }| j        | j                  | j         | j                  z   || j         <   | j        | j                 | j         | j                 z
  || j        <                       || j                 | j        | j                 k    | j        | j                 || j                           || j        <   |S rZ   )r   r1   
empty_likerN   r.   r   rE   r|   )r]   rB   r4   s     r8   r`   z'_bracket_minimum.<locals>.pre_func_eval  s    		T[ 		MM$'""8T\M2TY}5MM4<-*T\2TYt|5LL$,
 ((dlOtwt|44Jt|$dlO
 
$,
 r:   c                     |j         |j        | c|_        |_         |_        |j        |j        |c|_        |_        |_        d S rZ   )r   rN   rM   r   rP   rO   rb   s      r8   rc   z(_bracket_minimum.<locals>.post_func_eval  s:    $(GTWa!$'$(GTWa!$'''r:   c                    | j         t          j        k    }| j        | j        k    | j        | j        k    z  | j        | j        k    | j        | j        k    z  z  | z  }t          j        | j         |<   d||<   | j        | j        k    | z  }t          | j         |<   d||<   
                    | j                  
                    | j                  z   | z  }t          j        | j         |<   d||<   |S )NT)rL   re   rf   rO   r   rP   rh   rN   rE   rk   rl   rm   )r]   rn   r^   r4   s      r8   rt   z+_bracket_minimum.<locals>.check_termination  s    s~- WDGdg$56w TW%789E AQ W
"te+!AQ kk$'""R[[%9%99:dUBAQr:   c                     d S rZ   r   rv   s    r8   rw   z0_bracket_minimum.<locals>.post_termination_check  rx   r:   c                     | d         | d         k    }| d         |         | d         |         c| d         |<   | d         |<   | d         |         | d         |         c| d         |<   | d         |<   |S )NrM   rN   rP   rO   r   )r}   r)   comps      r8   r   z*_bracket_minimum.<locals>.customize_result  sq    4y3t9$+.t9T?CIdO(D	$T4+.t9T?CIdO(D	$T4r:   )r   re   r   r(   r   r   r|   r\   r   r   r   r   rf   r   r   )#r,   r   r-   r.   r/   r0   r1   r2   r3   r   r   r   r   r)   r   fl0fm0fr0r   r   rE   	unlimitedr   r   rL   rJ   rK   r]   r   r`   rc   rt   rw   r   r4   s#                                     @r8   _bracket_minimumr     s   L HtS#sD$gVVDAE>D#sCtVT7B
sCB?4T**D+/(D"b$ubMCcMCc99R__T5115u9EEDDR   D99R__T5115u9EEDDR   Ds3sSyASD[QRO YYrvu55u4YHHFfF 9Dt9c$iCIs4yt9c$iCIs4yHHT4&&EIjG==D9~I6DO7^c'l2DM &/)F7O\\#s/rx\@@F!nF?IC###3333 wvSV d< < <D$ $ $N     8 8 8    0     9T8UdD%"N&(>%~r	; ; ;r:   rZ   )numpyr   (scipy._lib._elementwise_iterative_method_lib_elementwise_iterative_methodre   scipy._lib._utilr   scipy._lib._array_apir   r   r   rk   rj   r9   r   r   r   r   r:   r8   <module>r      s        6 6 6 6 6 6 6 6 6 ( ( ( ( ( ( M M M M M M M M M M?A ?A ?ADVt$t4V V V V Vr
OF OF OFd (,Dt r4S; S; S; S; S; S; S;r:   