L i ddlZddlZddlmZddlmcmZddl m Z ddl m Z m Z mZmZdgZddddddddd d Zd Zd Zd ZdZdZdZdZdZdZdZdZdddeddddZddZdZ y)N)special) _RichResult)array_namespacexp_copyxp_ravel xp_promotensumF)argslogmaxlevelminlevelatolrtolpreserve_shapecallbackc 0123d} t|||| ||| | \ }}}} }}} } 3tjddd53jt |t |zdz |j } 3j |3j |}} || dz | | <||dz| |<d| | |z<tj|| f|d| 3}ddd\}}}}}}3t 3j3j|||}t 3j3j|||}t||3\}}}2}}}d \}}r 3j nd }3j3j| d }|z d z}3j|j }rdt#j$|zn|dzt 3j'||| 03j(03j+|3j+|z3j+|d z<3j3j-0dddd d f}t 3j'|3j(| }t 3j'|tj.3j0 } t3|313j511t 3j'|3j | }!t 3j'|3j(| }"t 3j7|| }#t 3j'|3j| }$t 3j'|3j(| }%t 3j7|| }&t 3j7|| }'t9d id0d|d|d1dd|d|d|d3j|dd3j|ddd|d|d| d|!d|"d |#d!|$d"|%d#|&d$|'d%|d&|d'|d(3j|dd)t9ddd gd*}(gd+})13fd,}*3fd-}+03fd.},3fd/}-23fd0}.tjddd5tj:|(| ||||||*|+|,|-|.|)3| }/ddd|/S#1swYxYw#1swY/SxYw)1u5Evaluate a convergent integral numerically using tanh-sinh quadrature. In practice, tanh-sinh quadrature achieves quadratic convergence for many integrands: the number of accurate *digits* scales roughly linearly with the number of function evaluations [1]_. Either or both of the limits of integration may be infinite, and singularities at the endpoints are acceptable. Divergent integrals and integrands with non-finite derivatives or singularities within an interval are out of scope, but the latter may be evaluated be calling `tanhsinh` on each sub-interval separately. Parameters ---------- f : callable The function to be integrated. The signature must be:: f(xi: ndarray, *argsi) -> ndarray where each element of ``xi`` is a finite real number and ``argsi`` is a tuple, which may contain an arbitrary number of arrays that are broadcastable with ``xi``. `f` must be an elementwise function: see documentation of parameter `preserve_shape` for details. It must not mutate the array ``xi`` or the arrays in ``argsi``. If ``f`` returns a value with complex dtype when evaluated at either endpoint, subsequent arguments ``x`` will have complex dtype (but zero imaginary part). a, b : float array_like Real lower and upper limits of integration. Must be broadcastable with one another and with arrays in `args`. Elements may be infinite. args : tuple of array_like, optional Additional positional array arguments to be passed to `f`. Arrays must be broadcastable with one another and the arrays of `a` and `b`. If the callable for which the root is desired requires arguments that are not broadcastable with `x`, wrap that callable with `f` such that `f` accepts only `x` and broadcastable ``*args``. log : bool, default: False Setting to True indicates that `f` returns the log of the integrand and that `atol` and `rtol` are expressed as the logs of the absolute and relative errors. In this case, the result object will contain the log of the integral and error. This is useful for integrands for which numerical underflow or overflow would lead to inaccuracies. When ``log=True``, the integrand (the exponential of `f`) must be real, but it may be negative, in which case the log of the integrand is a complex number with an imaginary part that is an odd multiple of π. maxlevel : int, default: 10 The maximum refinement level of the algorithm. At the zeroth level, `f` is called once, performing 16 function evaluations. At each subsequent level, `f` is called once more, approximately doubling the number of function evaluations that have been performed. Accordingly, for many integrands, each successive level will double the number of accurate digits in the result (up to the limits of floating point precision). The algorithm will terminate after completing level `maxlevel` or after another termination condition is satisfied, whichever comes first. minlevel : int, default: 2 The level at which to begin iteration (default: 2). This does not change the total number of function evaluations or the abscissae at which the function is evaluated; it changes only the *number of times* `f` is called. If ``minlevel=k``, then the integrand is evaluated at all abscissae from levels ``0`` through ``k`` in a single call. Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is ignored, and `minlevel` is set equal to `maxlevel`. atol, rtol : float, optional Absolute termination tolerance (default: 0) and relative termination tolerance (default: ``eps**0.75``, where ``eps`` is the precision of the result dtype), respectively. Must be non-negative and finite if `log` is False, and must be expressed as the log of a non-negative and finite number if `log` is True. Iteration will stop when ``res.error < atol`` or ``res.error < res.integral * rtol``. preserve_shape : bool, default: False In the following, "arguments of `f`" refers to the array ``xi`` and any arrays within ``argsi``. Let ``shape`` be the broadcasted shape of `a`, `b`, and all elements of `args` (which is conceptually distinct from ``xi` and ``argsi`` passed into `f`). - When ``preserve_shape=False`` (default), `f` must accept arguments of *any* broadcastable shapes. - When ``preserve_shape=True``, `f` must accept arguments of shape ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of abscissae at which the function is being evaluated. In either case, for each scalar element ``xi[j]`` within ``xi``, the array returned by `f` must include the scalar ``f(xi[j])`` at the same index. Consequently, the shape of the output is always the shape of the input ``xi``. See Examples. 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 `tanhsinh` (but containing the current iterate's values of all variables). If `callback` raises a ``StopIteration``, the algorithm will terminate immediately and `tanhsinh` will return a result object. `callback` must not mutate `res` or its attributes. Returns ------- res : _RichResult An object similar to an instance of `scipy.optimize.OptimizeResult` with the following attributes. (The descriptions are written as though the values will be scalars; however, if `f` returns an array, the outputs will be arrays of the same shape.) success : bool array ``True`` when the algorithm terminated successfully (status ``0``). ``False`` otherwise. status : int array An integer representing the exit status of the algorithm. ``0`` : The algorithm converged to the specified tolerances. ``-1`` : (unused) ``-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). integral : float array An estimate of the integral. error : float array An estimate of the error. Only available if level two or higher has been completed; otherwise NaN. maxlevel : int array The maximum refinement level used. nfev : int array The number of points at which `f` was evaluated. See Also -------- quad Notes ----- Implements the algorithm as described in [1]_ with minor adaptations for finite-precision arithmetic, including some described by [2]_ and [3]_. The tanh-sinh scheme was originally introduced in [4]_. Two error estimation schemes are described in [1]_ Section 5: one attempts to detect and exploit quadratic convergence; the other simply compares the integral estimates at successive levels. While neither is theoretically rigorous or conservative, both work well in practice. Our error estimate uses the minimum of these two schemes with a lower bound of ``eps * res.integral``. Due to floating-point error in the abscissae, the function may be evaluated at the endpoints of the interval during iterations, but the values returned by the function at the endpoints will be ignored. References ---------- .. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of three high-precision quadrature schemes." Experimental Mathematics 14.3 (2005): 317-329. .. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for single and multiple integration using floating-point arithmetic." arXiv preprint arXiv:2007.15057 (2020). .. [3] van Engelen, Robert A. "Improving the Double Exponential Quadrature Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas." https://www.genivia.com/files/qthsh.pdf .. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for numerical integration." Publications of the Research Institute for Mathematical Sciences 9.3 (1974): 721-741. Examples -------- Evaluate the Gaussian integral: >>> import numpy as np >>> from scipy.integrate import tanhsinh >>> def f(x): ... return np.exp(-x**2) >>> res = tanhsinh(f, -np.inf, np.inf) >>> res.integral # true value is np.sqrt(np.pi), 1.7724538509055159 1.7724538509055159 >>> res.error # actual error is 0 4.0007963937534104e-16 The value of the Gaussian function (bell curve) is nearly zero for arguments sufficiently far from zero, so the value of the integral over a finite interval is nearly the same. >>> tanhsinh(f, -20, 20).integral 1.772453850905518 However, with unfavorable integration limits, the integration scheme may not be able to find the important region. >>> tanhsinh(f, -np.inf, 1000).integral 4.500490856616431 In such cases, or when there are singularities within the interval, break the integral into parts with endpoints at the important points. >>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral 1.772453850905404 For integration involving very large or very small magnitudes, use log-integration. (For illustrative purposes, the following example shows a case in which both regular and log-integration work, but for more extreme limits of integration, log-integration would avoid the underflow experienced when evaluating the integral normally.) >>> res = tanhsinh(f, 20, 30, rtol=1e-10) >>> res.integral, res.error (4.7819613911309014e-176, 4.670364401645202e-187) >>> def log_f(x): ... return -x**2 >>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10)) >>> np.exp(res.integral), np.exp(res.error) (4.7819613911306924e-176, 4.670364401645093e-187) The limits of integration and elements of `args` may be broadcastable arrays, and integration is performed elementwise. >>> from scipy import stats >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18) >>> a, b = dist.support() >>> x = np.linspace(a, b, 100) >>> res = tanhsinh(dist.pdf, a, x) >>> ref = dist.cdf(x) >>> np.allclose(res.integral, ref) True By default, `preserve_shape` is False, and therefore the callable `f` may be called with arrays of any broadcastable shapes. For example: >>> shapes = [] >>> def f(x, c): ... shape = np.broadcast_shapes(x.shape, c.shape) ... shapes.append(shape) ... return np.sin(c*x) >>> >>> c = [1, 10, 30, 100] >>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1) >>> shapes [(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)] To understand where these shapes are coming from - and to better understand how `tanhsinh` computes accurate results - note that higher values of ``c`` correspond with higher frequency sinusoids. The higher frequency sinusoids make the integrand more complicated, so more function evaluations are required to achieve the target accuracy: >>> res.nfev array([ 67, 131, 259, 515], dtype=int32) The initial ``shape``, ``(4,)``, corresponds with evaluating the integrand at a single abscissa and all four frequencies; this is used for input validation and to determine the size and dtype of the arrays that store results. The next shape corresponds with evaluating the integrand at an initial grid of abscissae and all four frequencies. Successive calls to the function double the total number of abscissae at which the function has been evaluated. However, in later function evaluations, the integrand is evaluated at fewer frequencies because the corresponding integral has already converged to the required tolerance. This saves function evaluations to improve performance, but it requires the function to accept arguments of any shape. "Vector-valued" integrands, such as those written for use with `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement. For example, consider >>> def f(x): ... return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2] This integrand is not compatible with `tanhsinh` as written; for instance, the shape of the output will not be the same as the shape of ``x``. Such a function *could* be converted to a compatible form with the introduction of additional parameters, but this would be inconvenient. In such cases, a simpler solution would be to use `preserve_shape`. >>> shapes = [] >>> def f(x): ... shapes.append(x.shape) ... x0, x1, x2, x3 = x ... return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)] >>> >>> a = np.zeros(4) >>> res = tanhsinh(f, a, 1, preserve_shape=True) >>> shapes [(4,), (4, 66), (4, 64), (4, 128), (4, 256)] Here, the broadcasted shape of `a` and `b` is ``(4,)``. With ``preserve_shape=True``, the function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe. Nignore)overinvaliddivider g?T) complex_okrxprrdtyper rg?rSnSkaerrhr rpiepsabnnitnfevstatusxr0fr0wr0xl0fl0wl0d4ainfbinfabinfa0 pair_cache)xjcwjindicesh0))r-r-)integralr")errorr$)r+r+)r,r,cRd|jzz |_t|j|j|jk(|\}}t |||j |j \|_|_t|j}||jdj||jdzz z ||j<d||jz dz |j|jz||j<||jxxdzcc<|S)Nr )r inclusiverworkrr!)r*r% _get_pairsr_transform_to_limitsr(r)xjr;rr7realr6r8r5)rBr:r;rEr=rrs _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py pre_func_evalztanhsinh..pre_func_evalsaiTVVRtzz(,((:OR/RLTWW DJJ1rwwr$**~/F/I+IJ4::"TYY-!+dggdii.@@499  499   c |jr||jxxjd|j|jdzzdjd|j|jdzz zz z cc<||jxxdj|j|jzzcc<n||jxxd|j|jdzzd|j|jdzz dzz zcc<||jxx|j|jdzzcc<t ||\}}|j j dr[|j dddf}r>tjj|tjdz |gdn|dz |z}||_ ||_ y)Nrr gr!raxis) r r7rEr6_euler_maclaurin_sumr#shaper logsumexpstackmathfjwjr")xfjrBrRr"Snm1r rs rGpost_func_evalz tanhsinh..post_func_evals 88 tzzNrvva$''$***=q*@&@A!"266!dggdjj.A1.D*D#E!E F GN tyyMQ (:!;; ;M tzzNDGGDJJ$7$: : !DGGDJJ$7$: :Q> ? @N tyyMTWWTYY/4 4M(D"5b 77== 771b5>DSV'##BHHdTXXa[.@"-E$FQOax"}  rIcb j|jjt}|jdk(rt |j |jk(} j r j nd} j|jj|j} j| j<|||j|<|||j|<tj |j"|<d||<nt%| \}}| k| kz} j' j)||j|jj|_tj |j"|<d||< rU j+|j} j-||dkDz}| j|jz|z}n j/|j|z}tj0|j"|<d||<|S)z>Terminate due to convergence or encountering non-finite valuesrrrT)zerosr"rNboolr+rr(r)asarrayinffullrnanisnanr$eim _ECONVERGEDr-_estimate_errorreshapeastyperFisinfisfinite _EVALUEERR) rBstopizerorerrr$Sn_real Sn_pos_infr"rr rrs rGcheck_terminationz#tanhsinh..check_terminationsxx Tx2 88q=466)*A::rvvg"5D77477==$bhh7?D!#D" aDGGAJ7DIIaL __DKKNDG)r2JD$-ABIIdDJJ$?ODI __DKKNDG ggdgg&G'*gk:Jbhhtww//D58ATWW%%-A AQ rIc|xjdz c_j|j|jddjffd|_y)Nrr!rK)r*concatr#r"newaxis)rBrs rGpost_termination_checkz(tanhsinh..post_termination_checksA ! ))TWWdggam&<=B)GrIcr-jr|djzdzz|d<n|dxxdzcc<|dzdz |d<d|d|ddk(<|d=|S)Nr>?r!r+rrr)anyr&)resrNr rnegativers rGcustomize_resultz"tanhsinh..customize_results 266(#!*o2550@40GGC O  OH % + %#SZ/!3J+-JE a( J rI) _tanhsinh_ivnperrstaterbrrNrdr_ _initializerc broadcast_to_transform_integralsr[rZr&finfor'rQr r\r]r^ empty_like _EINPROGRESSint32_get_base_steprFrXr_loop)4fr(r)r r rrrrrrmaxfuncinf_ainf_btempxsfsrNrr8r7r5r6r+r,rir&maxiterr'r#r$r-r.r/r0r1r2r3r4rBres_work_pairsrHrVrmrqrwrur"r=rvrs4 ` ``` @@@@rGtanhsinhrsLP F7C 1afh$ dNH8.5Q1c68X 4~x (HX FE JJ hqk114agg >xx{BHHQKuU8b=%U8b=%%%-q1$.<E E)-%Ar2tUE22??1e4e<=A2??1e4e<=A-AAr,J)Aq"htTICBFF7qD BEE ' +B!A%G ((5/  C |%(tDHHSM!c4i "''%U'3 4B68ffBrxx{RXXa[ 288BqE?23 BMM"%w /1Q3 7B BGGE266G7 8D bggeS%5%5RXXgF GF r "B B 2775266'77 8C 2775"&&76 7C 288E8/ 0C 2775"&&76 7C 2775"&&76 7C 288E8/ 0C "((5(. /B  I  I I I#% I+. I6; I@B IHK I **Q  I$&JJq'$: I  I I#' I06 I   I  I"  I(+  I14  I:=  IBD  I   I   I %*  I /1jjW.E  I4D1#$G IDKN *  D " (HX FNiihw4 &(9;Q(."nNN JwEEnN JsBS$SSScd|j|jz}tjtjd|z dz |j z }|t z }|j||dS)Nr rrr )r~smallest_normalrQasinhr r& _N_BASE_STEPSrZ)rrfmintmaxr=s rGrrsh RXXe_ , , ,D ::dhhqvz*RUU2 3D  B ::b: &r **rIc|d|zz }td|zz}|dk(r|j|dzn|jd|dzd}||z}|jdz }||j|z}||j |z} ||j| dzz } d|j | |j| zz } |dk(r| ddz n| d| d<| | fSNr rr)raranger&coshsinhexp) kr=rr%maxjjhpi_2u1u2r;r:s rG _compute_pairr s QT A !Q$ CF #a% !SUA(>A QB 5519D bggbk B bggbk B bggbk1n B rvvbzBGGBK' (CaBqEAIRUBqE 7NrIct|t|jjr||jjk7rR|j d|j_|j d|j_dg|j_|jj g}|jj g}tt|jjdz |dzD]}t|||\}}|j||j||jjj|jjd|jdz|j||j_|j||j_||j_y)Nrrr!) isinstancetyper9r=emptyr:r;r<rangelenrappendrNro) rr=rrBxjcswjsrhr:r;s rG _pair_cacher/sK b$t112 3rT__=O=O7O hhqkXXa[#$# OO   D ??   C 3t../11q5 9S2r*R C 2 &&t'>'>r'BSYYq\'QR S ))D/DOO3DOODOOrIct|jj|dzksBt|t |jj r||jj k7rt |||||jj}|jj}|jj}|rdn||} ||dz} |j|| | ||j|| | |fSr) rr9r<rrr=rr:r;rc) rr=rArrrBr:r;r<startends rGrCrCGs DOO # #$!+2tDOO$6$678 ## # 2r4 ( //  C   Boo%%GA E !A#,C 99Ss^U +RYYr%}e-L LLrIc||z dz }|j| |z|z||z|zfd}||z}|j||fd}|j||j||j|} }}||k|| k\z} d|| <||fS)Nr r!rKr)rorF) r:r;r(r)ralpharExj_reala_realb_realrs rGrDrDYs UaKE UFSL1$eckAo6R @B EB B8" %B!ggbk2771:rwwqzVVG& W%67GBwK r6MrIc|j|j|j}}}|j|j|j }}}|j j|j|jj} }} | j\} } t|j| d| dz| f\} }|j|d| dz| f\}}|j| d| dz| f\}}|j||dk(z}|j||dk(z}|j | |<|j|j| dd}|j!| |dd}|j!||dd}|j!||dd}|j||j|kD}||||<||||<||||<|j||<|j#|j|dd}|j!||dd}|j!||dd}|j!||dd}|j||j|k}||||<||||<||||<|j}|j$r||j%|zn||z}|j$r||j%|zn||z}|j$r |jn |j&} |j)| || ||_|j-||j.ddf|j}!|j-||j.ddf|j}"|!|||<|"|||<|j$r||j%|jzn||jz}#|j$r3t1j2|#|j%|j4zdn|j7|#d|j4z}$|||c|_|_|_|||c|_|_|_|#|$fS)Nr rTrLkeepdimsrKr!)r.r/r0r1r2r3rETr;rNrrbrer[argmaxrFtake_along_axisargminr absmaximumr4r|rprrOr%sum)%rTrBrr.r/r0r1r2r3rEr;n_xn_activexrxlfrflwrwl invalid_r invalid_lirxr_maxfr_maxwr_maxrilxl_minfl_minwl_minflwl0frwr0 magnitudefr0bfl0brRr"s% rGrMrMosHHdhhcCHHdhhcCBDD$''))BBHHMCRZZQq($;< =FB ZZQq(3 4FB ZZQq(3 4FBR B!G,IR B!G,IVVGByM 2772;Q 6B  BQ  / 2F   BQ  / 2F   BQ  / 2F "''#,&A AYCF AYCF AYCFFFByM 2772;Q 6B   BQ  / 2F   BQ  / 2F   BQ  / 2F "''#,&A AYCF AYCF AYCF B"&C"&&+ sSyE!%C"&&+ sSyE88Ijj5)9U+;1 ;vvdv$tvv-$'S DHdh#&S DHdh 8OrIc r |jdk(s|jdk(r*|j|j|j}||fS|j j }|jjd}tdd}|jjddk(rd|jz}||j}|j|j|ddf}|j|ddddd|f|d|zf} |jr(tj| fi||j|zn|j | fi||z} |j#| |jfd|_ |jdk(r*|j|j|j}||fS|jjddkrd|jz}||jdz }|j|j|jjdddf}|j|d d|f|d|zf} |jr(tj| fi||j|zn|j | fi||z} |j#| |jfd|_ |jd } |jd } |j%|j&d } |jr|j| } |j)tj|j+|j| |j,d zzgd}|j)tj|j+|j| |j,d zzgd}| |j/|j)|jdz}|j0}| |j)|jz}|j3||j4 kD|dz|z |j4 }|j+|d|z||g}|j7|j/|d||}||j)|jz }||fS|j9|j| z }|j9|j| z }| |j/|j9|jdz}|j0}| |j9|jz}|j3|dkD||j||j|z zd}|j+||dz||g}|j7|j/|d||}||j9|jz }||fS)Nrr!Trr rKrr.).).r!r rs)r*r+ full_liker"r]r9r<rNdictr#r%rbrRr rrOrrorZr'rFrPr&rr4wherer[clipr)rBrr]r<r axis_kwargsr%rfjwj_rlrRrUSnm2e1log_e1d1d2d3r4d5rdsr$rjs rGraras vv{dhh!mll477BFF+Cxoo%%Gww}}QHB.K  ww}}RA Jdffo**TYY1b(9:zz'!Q*-!C%/@AFJhh!!$6+6BRVVD0K014 ))T477O")5 vv{ll477BFF+Cx  ww}}R1 JdffQh**TYYq)91b(ABzz'#tt),x3.?@FJhh!!$6+6BRVVD0K014 ))T477O")5 777 D 777 D DHH b !B xx WWW&&rxx$:K0L'MTUV W WWW&&rxx$:K0L'MTUV W bffRWWTYY/bf9 9 WW bggdgg& &xxbffW bAglRVVG< XXtQVR, -wwrvvbqv)2r2bggdgg&& :VVDGGdN # VVDGGdN # "&& *&4 4 WW "&&/ !xxQRVVBZr %: ;Q? XXtRUB+ ,wwrvvbqv)2r2BFF477O# :rIc||k(}d\||<||<|j||j|k}||||c||<||<|j||j|z}d\||<||<|j|}|| || c||<||<|j|}t|}d\||<||<|||||||fS)N)rrr r)rFrdr) r(r)rab_samervr7r5r6r8s rGr}r}sAvG!AgJ' wwqzBGGAJ&H {AhKAhK8 HHQK"((1+ %EAeHah 88A;D$x!D'AdGQtW 88A;D BAdGQtW aXudD 00rIc (t||t||dd\}}d} t|s t| d} j |j dsj |j dr t| d} |dvr t| t |}||r j nd}||nd } tj|| d g}d } tj|j tjs t| |r5d } tjtj|rXt| d } tj|dks(tjtj|r t| |d}||n|d }td}||d}||n|}||n|}d} tj|||g}tj|j tj r]tj"tj$|r5tj"|j'tj(|k(s t| d} tj|dkr t| |j'tj(\}}}t+||}tj,| s| f} fd| D} d} | dvr t| | t| s td|||||||||| | | f S)NT broadcastforce_floatingr`f` must be callable.z1All elements of `a` and `b` must be real numbers.zcomplex floating`log` must be True or False.FTrr'`atol` and `rtol` must be real numbers.z/`atol` and `rtol` may not be positive infinity.z2`atol` and `rtol` must be non-negative and finite.rl z6`maxfun`, `maxlevel`, and `minlevel` must be integers.z:`maxfun`, `maxlevel`, and `minlevel` must be non-negative.c3@K|]}j|ywN)rZ).0argrs rG z_tanhsinh_iv..vs ,BJJsO ,sz'`preserve_shape` must be True or False.z`callback` must be callable.)rrcallable ValueErrorisdtyperrYr[ryrZ issubdtypefloatingrtisposinfrdfloatnumberallisrealrcint64miniterable)rr(r)r rrrrrr rrmessage rtol_tempparamsBIGINTrs @rGrxrx6s A B ad4B GDAq%G A;!!AG 177./zz!''#56!!,G -!! s)C |w1(bIZZy"- .F7G ==r{{ 3!! C 66"++f% &W% %F 66&1* (8!9W% % !9D<4VAYD 5\F ~(*~V6F!)vxHFG ZZ84 5F MM&,, 2ryy()v}}RXX.&89!!JG vvfqj!!!'rxx!8FHh8X&H ;;t w ,t ,D7G]*!!HX$6788 q!S&(H $nh <z real floatingrrrrrrrz3`atol`, `rtol` may not be positive infinity or NaN.z3`atol`, and `rtol` must be non-negative and finite.rz*`maxterms` must be a non-negative integer.)rrrrrrregetr[ryrZrrrtrr^intr)rr(r)stepr r maxterms tolerancesrrvalid_b valid_step valid_absteprrrr maxterms_ints rG_nsum_ivrs At $BAq$$tPRSJAq$%G A;!!JG ::agg< =!!1fGT"dQh/JZ'L,G -!!!)zJ >>&$ 'D |w1 >>&$ 'D(bIZZy"- .F7G ==r{{ 3!! G 66"++f%(88 9W% %G 666A:2;;v#6"67 8W% % !9D<4VAYDx=Lx8a<>!! ;;t w aD,c<tR OOrIri)r r r r rc ~ #t|||||||}|\ }}}} }}}} } #tj|f|d#}|\} } }}}#| d}#jt #j |||}#jt #j |||}t #j | |} #j ||z |z }#j|}||||||zz||<#j|j}#j|r #j nd|d}| |rdtj|zn|dz} ||||| | |f}#j|}#j|}#jt!|#j"}#j%t!|#j"}| }||k}|dz|k|z}#j||z|z}#j||z|z|z}||z|z|z}#j'|r4#j(#j(c||<||<d ||<||c||<||<d||<#j'|r|Dcgc]}|| } }t+||||||| |#}|dd \||<||<||xx|d z cc<d #j#j||#j"z||<#j'|rN|Dcgc]}|| }!}t-|||||||!|#}|dd \||<||<||<||xx|d z cc<#j'|rU|Dcgc]}|| }!}fd }"t-|"|| || |||!|#}|dd \||<||<||<||xx|d z cc<#j'|rq|Dcgc]}|| }!}|r#fd }"n#fd }"#j/||}t-|"||||||!|#}|dd \||<||<||<||xxd|d zz cc<|j1|d|j1|d}}|j1|d|j1|d}}t3||||dk(|Scc}wcc}wcc}wcc}w)aF!Evaluate a convergent finite or infinite series. For finite `a` and `b`, this evaluates:: f(a + np.arange(n)*step).sum() where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and unimodal. The number of terms in the sum may be very large or infinite, in which case a partial sum is evaluated directly and the remainder is approximated using integration. Parameters ---------- f : callable The function that evaluates terms to be summed. The signature must be:: f(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``. `f` must be an elementwise function: each element ``f(x)[i]`` must equal ``f(x[i])`` for all indices ``i``. It must not mutate the array ``x`` or the arrays in ``args``, and it must return NaN where the argument is NaN. `f` must represent a smooth, positive, unimodal function of `x` defined at *all reals* between `a` and `b`. a, b : float array_like Real lower and upper limits of summed terms. Must be broadcastable. Each element of `a` must be less than the corresponding element in `b`. step : float array_like Finite, positive, real step between summed terms. Must be broadcastable with `a` and `b`. Note that the number of terms included in the sum will be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure that ``f(b)`` is included if intended. args : tuple of array_like, optional Additional positional arguments to be passed to `f`. Must be arrays broadcastable with `a`, `b`, and `step`. If the callable to be summed requires arguments that are not broadcastable with `a`, `b`, and `step`, wrap that callable with `f` such that `f` accepts only `x` and broadcastable ``*args``. See Examples. log : bool, default: False Setting to True indicates that `f` returns the log of the terms and that `atol` and `rtol` are expressed as the logs of the absolute and relative errors. In this case, the result object will contain the log of the sum and error. This is useful for summands for which numerical underflow or overflow would lead to inaccuracies. maxterms : int, default: 2**20 The maximum number of terms to evaluate for direct summation. Additional function evaluations may be performed for input validation and integral evaluation. atol, rtol : float, optional Absolute termination tolerance (default: 0) and relative termination tolerance (default: ``eps**0.5``, where ``eps`` is the precision of the result dtype), respectively. Must be non-negative and finite if `log` is False, and must be expressed as the log of a non-negative and finite number if `log` is True. Returns ------- res : _RichResult An object similar to an instance of `scipy.optimize.OptimizeResult` with the following attributes. (The descriptions are written as though the values will be scalars; however, if `f` returns an array, the outputs will be arrays of the same shape.) success : bool ``True`` when the algorithm terminated successfully (status ``0``); ``False`` otherwise. status : int array An integer representing the exit status of the algorithm. - ``0`` : The algorithm converged to the specified tolerances. - ``-1`` : Element(s) of `a`, `b`, or `step` are invalid - ``-2`` : Numerical integration reached its iteration limit; the sum may be divergent. - ``-3`` : A non-finite value was encountered. - ``-4`` : The magnitude of the last term of the partial sum exceeds the tolerances, so the error estimate exceeds the tolerances. Consider increasing `maxterms` or loosening `tolerances`. Alternatively, the callable may not be unimodal, or the limits of summation may be too far from the function maximum. Consider increasing `maxterms` or breaking the sum into pieces. sum : float array An estimate of the sum. error : float array An estimate of the absolute error, assuming all terms are non-negative, the function is computed exactly, and direct summation is accurate to the precision of the result dtype. nfev : int array The number of points at which `f` was evaluated. See Also -------- mpmath.nsum Notes ----- The method implemented for infinite summation is related to the integral test for convergence of an infinite series: assuming `step` size 1 for simplicity of exposition, the sum of a monotone decreasing function is bounded by .. math:: \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u) Let :math:`a` represent `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a` represent `atol`, and :math:`\epsilon_r` represent `rtol`. The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx` as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise, let :math:`c = a + n`. Then the infinite sum is approximated as .. math:: \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2 and the reported error is :math:`f(c)/2` plus the error estimate of numerical integration. Note that the integral approximations may require evaluation of the function at points besides those that appear in the sum, so `f` must be a continuous and monotonically decreasing function defined for all reals within the integration interval. However, due to the nature of the integral approximation, the shape of the function between points that appear in the sum has little effect. If there is not a natural extension of the function to all reals, consider using linear interpolation, which is easy to evaluate and preserves monotonicity. The approach described above is generalized for non-unit `step` and finite `b` that is too large for direct evaluation of the sum, i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal functions by directly summing terms surrounding the maximum. This strategy may fail: - If the left limit is finite and the maximum is far from it. - If the right limit is finite and the maximum is far from it. - If both limits are finite and the maximum is far from the origin. In these cases, accuracy may be poor, and `nsum` may return status code ``4``. Although the callable `f` must be non-negative and unimodal, `nsum` can be used to evaluate more general forms of series. For instance, to evaluate an alternating series, pass a callable that returns the difference between pairs of adjacent terms, and adjust `step` accordingly. See Examples. References ---------- .. [1] Wikipedia. "Integral test for convergence." https://en.wikipedia.org/wiki/Integral_test_for_convergence Examples -------- Compute the infinite sum of the reciprocals of squared integers. >>> import numpy as np >>> from scipy.integrate import nsum >>> res = nsum(lambda k: 1/k**2, 1, np.inf) >>> ref = np.pi**2/6 # true value >>> res.error # estimated error np.float64(7.448762306416137e-09) >>> (res.sum - ref)/ref # true error np.float64(-1.839871898894426e-13) >>> res.nfev # number of points at which callable was evaluated np.int32(8561) Compute the infinite sums of the reciprocals of integers raised to powers ``p``, where ``p`` is an array. >>> from scipy import special >>> p = np.arange(3, 10) >>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,)) >>> ref = special.zeta(p, 1) >>> np.allclose(res.sum, ref) True Evaluate the alternating harmonic series. >>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2) >>> res.sum, res.sum - np.log(2) # result, difference vs analytical sum (np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14)) F)rrrrr N?rr!c| g|Srr )rSr rs rG_fznsum.._fsA2-rIcj|dk(tjdd}j|g|| g|gd}t j |d|zS)NrrrK)rrQr rPrrO)rSr log_factoroutrrs rGrznsum.._fsbXXadDHHSM1= hh! d Qr\D\:hC((15 BBrIc^j|dk(dd}|g|| g|z|zS)Nrrr)r)rSr factorrrs rGrznsum.._fs;!Q$Q/! d alTl2f<>%(,dll5.A".EDF 1Affk  ""k0222s R+ R05 R5 R:c|\}} } } } } } t|} |j||z |z | z}t|j|}|dd|jf|dd|jf|dd|jf}}}|Dcgc]}|dd|jf}}||j |||zz}||| |zdz zk\}|j ||<||g|}| ||<||j dz }| rtj|dn|j |d}| r'|j|tj| zn | t|z}|||fScc}w)Nrr r!rK) r roundrrprr]rrrOrFrQr r)rr(r)r r r'rrArr r'ri_inclusive_adjustmentsteps max_stepsa2b2step2rargs2ksi_nanrr,r(r)s rGr!r!sr&/"E3T1ay> HHa!et^ $'; ;EBFF5M"Iam$a2:: &6Q ]8KEB+/ 0CSBJJ  0E 0 bii i/%7 7B 2,U2144 5EBuI 2B BuI uyyby) )D*-"2&266"263FA&) TXXc]"sSV|A a: 1sE$c |\}}} } } } } |jtjd|} t||||| | |}|j |j| |j j }|r6tj|j|| |j zfd}n|| |j zz}|jdk(}|j||<|j}|d|jf}|d|jf}|Dcgc]}|d|jf}}| r(tjtj| nd}|jd|j!d|z|j| gf}|j#||}t%|dz}|||zz}||g|}|||zg|}||dd|jfkD||kDz}|j'|d}|j)||j dd z }||}||dzk(}|||zz} t+||| ||||d \}!}"}#|j-|!|!dkDz}$||$z}d||$<|j| |<t|| ||| | |}%||j!t%||f}&|r|j/|&|j0 n|j3|&}'|j5|}(|j7|(r |||(g|Dcgc]}||( c}|'|(<||j|(|#j8z}|r|j|})|!|%j |)z |&| z |'| z f}*tj|j|*d}+|"|%j:|)z |&| z |'| z |j<d zzf},|j?tj|j|,d}-n<|!|%j |z z|&dz z|'dz z}+|"|%j:|z z|&dz z|'dz z }-|%j|||<d ||dk(|z<|+|-||#|%j@z|z|j@zfScc}wcc}w)Nr r)r rrr rrKr.r!rF)rArs)!rZrQr rr|r>rNrrOrPr-r]rprlog2rorrcrrminimumr!rdrr[r#rertrr?r&rFr,).rr(r)r r r'rrr r4rrr r@lbtoli_skipr-r8r:rr; log2maxtermsn_stepsr,r<fksfksp1fk_insufficientn_fk_insufficientnti_fk_insufficientrleft left_error left_nfevleft_is_pos_infrightfkfbrhlog_stepS_termsr(E_termsr)s. rGr"r"st-6*E31dD( ::dhhqk: /D !Q4d DB //"**T*BKK,=,= >C #tbkk/A)B C!LD$$ YY"_F&&CK YYF 3 ? B bjj !E-1 2cSbjj ! 2E 27?4::dii12ALiiBIIa66 H:8NOPGii'G w>$& &A -1 4 T) )BqD 02a4 7llF7+FF7O02FFaK, ,- aUZZ/$6@ @@} 3^2s Q* Q/ )T)!rQnumpyryscipyr(scipy._lib._elementwise_iterative_method_lib_elementwise_iterative_methodr_scipy._lib._utilrscipy._lib._array_apirrrr__all__rrrrrrCrDrMrar}rxrr r r!r"r rIrGr_s 66(// (&!edQT%$Qh+, !H0M$,UpQh16J