L i_tddlZddlZddlmcmZddlmZddl m Z dddddddddZ dZ ddddddddd Z y) N) _RichResult)xp_copy)argsxatolxrtolfatolfrtolmaxitercallbackc"t|||||||| } | \}}}}}}}} tj|||f|} | \}} } }}}| \}}| \}}j|tjj }d\}}j |}|d|jzn|}|d|jzn|}| |jn|}|jj|j|z}|?tj|jtj|jz n|}t||||ddd|||||||}gd}d}fd }fd }fd }fd }tj|| ||||||||||| S)aZFind 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)rN?)x1f1x2f2x3f3trrr r nitnfevstatus) rr)xxmin)funfminrrrrxlrflr)xrr)frrcl|j|j|j|jz zz}|SN)rrr)workrs b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py pre_func_evalz$_chandrupatla..pre_func_evals+ GGdff$'' 12 2cj|jdj|jdc|_|_j |j |j k(}|}|j||j |c|j|<|j|<|j||j |c|j|<|j|<||c|_|_y)NT)copy)asarrayrrrrsignrr)rfr,jnjxps r-post_func_evalz%_chandrupatla..post_func_evalsJJtwwTJ:JJtwwTJ:  GGAJ"''$''* *R!%TWWQZ DGGAJ#'772;   TWWR[ar/c2j|jj|jk}j||j|j |_j||j|j|_j|jj}j|j|j|jzk}tj|j|<d||<j|jj|jk(|z}j!j"|j j$}||tj&c|j |<|j|<|j|<d||<j)|jj)|j z}j+|jj+|jz}||z|z}||tj,c|j |<|j|<|j|<d||<j|j |jz |_j|j |j0z|j2z|_|j.|j4k}tj|j|<d||<|S)NrT)absrrwhererrrr! zeros_likeboolr r eim _ECONVERGEDrr3r2nanr _ESIGNERRisfiniteisnan _EVALUEERRdxrrtol)r,istopNaN x_nonfinitef_nanr7s r-check_terminationz(_chandrupatla..check_terminationsB FF477ObffTWWo -HHQ1 HHQ1 }}TWWBGG}4 FF499 djj!8 8 AQWWTWW !1 1dU :jjtyyj758#s}}2 ! diilDKKNQ DGG,r{{477/CCD !BHHTWW$55 5 TE )58#s~~2 ! diilDKKNQ&&477*+66$))$tzz1DJJ> GGdhh  AQ r/c>|j|jz |j|jz z }tjdd5|j |j z |j|j z z }ddd|j|jz |j|jz z }d jd|z z k| j|kz}|j ||j ||j|||f\}}}} j|d} |||z z |z||z z ||z||z z |z||z z z | |<d|jz|jz } j| | d| z |_ y#1swYxYw)Nignore)divideinvalidr)rrrnperrstaterrrsqrt full_likerFrEclipr) r,xi1phi1alphar5f1jf2jf3jalphajrtlr7s r-post_termination_checkz-_chandrupatla..post_termination_checkswww TWWtww%67 [[( ; =GGdgg%$''DGG*;.customize_resultsTCIs4y#d)CBB ID !HHQB'D HHQB'D HHQB'D HHQB'D  r/r7)_chandrupatla_ivr> _initializerU _EINPROGRESSint32finfosmallest_normalepsminimumr:mathlog2maxr_loop) funcabrrrr r r r rdtempxsfsrerrrrrrrrrlr,res_work_pairsr.r8rLr_rfr7s @r- _chandrupatlar{ sh 4ue %( 344 ;;t w :: 1uq % 1uq % 1uq % 1uq: ;D MM$**bii 0BFF4!84Dvvbhhtn%t);CDD'l k !Wq[HI IHX$6788 ueUE7H DDr/dc(!t||||||| | } | \}}}}}}} } |||f} tj|| |} | \}} }}}}!| \}}}|\}}}!jd|d}!j |tj !j }d\}}|!j|jn|}|!j|jn|}|!j|jn|}|.tj!j|jn|}!j|||f!j|||f}} !j| d}!j| |d\}}}!j||d\}}}t|}t!did|d|d |d |d |d |d |d|d|d|d|d|d|d|d|d|}gd}!fd}!fd}!fd}d}!fd} tj"|| || |||||||| |!S)aFind 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?rr)rr)axisrrrrrrphirrr r rrrq0r) r)rr)r rr"r#r$)xmr)r(rr&)fmr)r)rc |j|jz }|j|jz }||j|jz z}||j |jz z}|||zz }d||j|jz z|jz|jzz} j ||jz d j |zk}||} j |||j|z |j|k} |j||  j||| |j|| zz|| <|jd|jz |zz} || |<||_| S)Nrr) rrrrrrr:rxtolr3r) r,x21x32ABCq1rGxir5rr7s r-r.z-_chandrupatla_minimize..pre_func_evalsegggg 477TWW$ % 477TWW$ % QK Atww()DGG3dgg= > FF2< 3#4 4 U FF2a54771:% &$))A, 6 1 Aq 2TYYq\!_ DD1 GGq488|s* *!r/cj||jz j|j|jz 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 | <yr+)r3rrrrrr)rr4r,rGrx1ix2ix3ifif1if2if3ir5nixnix1nix2nix3nifnif1nif2nif3nir7s r-r8z._chandrupatla_minimize..post_func_evalsn GGAK BGGDGGdgg,=$> >aD$''!*dggaj$''!*ECcaD$''!*dggaj$''!*DCc HA1AA B),QQA1)E&AAAAR !"twwr{DGGBK MT4 !"twwr{DGGBK LT4 $Jq63q6Qa B-1!Wd1gs1vs1v-M*Qa$q'47-0#s* DGGAJ -0#s* DGGAJ 04dD- TWWR[$''"+04dD- TWWR[$''"+r/cZj|jt}|j|jkD|j|j kDz}j j c|j|<|j|<dtjc||<|j|<j|j|jz|jz|jz|jz|j z}||z}j j c|j|<|j|<dtjc||<|j|<j|j|jz j|j|jz k}|j|}|j||j|<||j|<|j|}|j ||j|<||j |<j|j|jz|j z|_j|j|jz d|j"zk}j|j|j$z|j&z}||jd|jzz |j zd|zkz}||z}dtj(c||<|j|<|S)NrTr)r<rr=rrrr@rr>rArrBrrDr:rrrr r r?)r,rHrGfiniterwftolr7s r-rLz1_chandrupatla_minimize..check_terminationsr}}TWWD}1ggDGGdgg$5 6!# DGGAJ"& QQTWWTWW_TWW4TWW.post_termination_checks r/c|d|d|d|df\}}}}|d|dk\}j||||d<j||||d<j||||d<j||||d<|Srarbrcs r-rfz0_chandrupatla_minimize..customize_resultsTCIs4y#d)CBB IT "HHQB'D HHQB'D HHQB'D HHQB'D  r/rg)rhr>rir2rUrjrkrlrmrprTrnstackargsorttake_along_axisrrrs)"rtrrrrrrr r r r rdrxrwryrerrrrrrrrrGrr,rzr.r8rLr_rfr7s" @r-_chandrupatla_minimizersj 4ue %( scipy._lib._utilrscipy._lib._array_apirr{rhrrr/r-rsO 66()')DAtdgTE<68t!%Ts$(Sr/