_tanhsinh.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. # mypy: disable-error-code="attr-defined"
  2. import math
  3. import numpy as np
  4. from scipy import special
  5. import scipy._lib._elementwise_iterative_method as eim
  6. from scipy._lib._util import _RichResult
  7. from scipy._lib._array_api import (array_namespace, xp_copy, xp_ravel,
  8. xp_promote, xp_capabilities)
  9. __all__ = ['nsum']
  10. # todo:
  11. # figure out warning situation
  12. # address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521
  13. # without `minweight`, we are also suppressing infinities within the interval.
  14. # Is that OK? If so, we can probably get rid of `status=3`.
  15. # Add heuristic to stop when improvement is too slow / antithrashing
  16. # support singularities? interval subdivision? this feature will be added
  17. # eventually, but do we adjust the interface now?
  18. # When doing log-integration, should the tolerances control the error of the
  19. # log-integral or the error of the integral? The trouble is that `log`
  20. # inherently looses some precision so it may not be possible to refine
  21. # the integral further. Example: 7th moment of stats.f(15, 20)
  22. # respect function evaluation limit?
  23. # make public?
  24. @xp_capabilities(skip_backends=[('array_api_strict', 'No fancy indexing.'),
  25. ('jax.numpy', 'No mutation.'),
  26. ('dask.array',
  27. 'Data-dependent shapes in boolean index assignment')])
  28. def tanhsinh(f, a, b, *, args=(), log=False, maxlevel=None, minlevel=2,
  29. atol=None, rtol=None, preserve_shape=False, callback=None):
  30. """Evaluate a convergent integral numerically using tanh-sinh quadrature.
  31. In practice, tanh-sinh quadrature achieves quadratic convergence for
  32. many integrands: the number of accurate *digits* scales roughly linearly
  33. with the number of function evaluations [1]_.
  34. Either or both of the limits of integration may be infinite, and
  35. singularities at the endpoints are acceptable. Divergent integrals and
  36. integrands with non-finite derivatives or singularities within an interval
  37. are out of scope, but the latter may be evaluated be calling `tanhsinh` on
  38. each sub-interval separately.
  39. Parameters
  40. ----------
  41. f : callable
  42. The function to be integrated. The signature must be::
  43. f(xi: ndarray, *argsi) -> ndarray
  44. where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
  45. which may contain an arbitrary number of arrays that are broadcastable
  46. with ``xi``. `f` must be an elementwise function: see documentation of parameter
  47. `preserve_shape` for details. It must not mutate the array ``xi`` or the arrays
  48. in ``argsi``.
  49. If ``f`` returns a value with complex dtype when evaluated at
  50. either endpoint, subsequent arguments ``x`` will have complex dtype
  51. (but zero imaginary part).
  52. a, b : float array_like
  53. Real lower and upper limits of integration. Must be broadcastable with one
  54. another and with arrays in `args`. Elements may be infinite.
  55. args : tuple of array_like, optional
  56. Additional positional array arguments to be passed to `f`. Arrays
  57. must be broadcastable with one another and the arrays of `a` and `b`.
  58. If the callable for which the root is desired requires arguments that are
  59. not broadcastable with `x`, wrap that callable with `f` such that `f`
  60. accepts only `x` and broadcastable ``*args``.
  61. log : bool, default: False
  62. Setting to True indicates that `f` returns the log of the integrand
  63. and that `atol` and `rtol` are expressed as the logs of the absolute
  64. and relative errors. In this case, the result object will contain the
  65. log of the integral and error. This is useful for integrands for which
  66. numerical underflow or overflow would lead to inaccuracies.
  67. When ``log=True``, the integrand (the exponential of `f`) must be real,
  68. but it may be negative, in which case the log of the integrand is a
  69. complex number with an imaginary part that is an odd multiple of π.
  70. maxlevel : int, default: 10
  71. The maximum refinement level of the algorithm.
  72. At the zeroth level, `f` is called once, performing 16 function
  73. evaluations. At each subsequent level, `f` is called once more,
  74. approximately doubling the number of function evaluations that have
  75. been performed. Accordingly, for many integrands, each successive level
  76. will double the number of accurate digits in the result (up to the
  77. limits of floating point precision).
  78. The algorithm will terminate after completing level `maxlevel` or after
  79. another termination condition is satisfied, whichever comes first.
  80. minlevel : int, default: 2
  81. The level at which to begin iteration (default: 2). This does not
  82. change the total number of function evaluations or the abscissae at
  83. which the function is evaluated; it changes only the *number of times*
  84. `f` is called. If ``minlevel=k``, then the integrand is evaluated at
  85. all abscissae from levels ``0`` through ``k`` in a single call.
  86. Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is
  87. ignored, and `minlevel` is set equal to `maxlevel`.
  88. atol, rtol : float, optional
  89. Absolute termination tolerance (default: 0) and relative termination
  90. tolerance (default: ``eps**0.75``, where ``eps`` is the precision of
  91. the result dtype), respectively. Must be non-negative and finite if
  92. `log` is False, and must be expressed as the log of a non-negative and
  93. finite number if `log` is True. Iteration will stop when
  94. ``res.error < atol`` or ``res.error < res.integral * rtol``.
  95. preserve_shape : bool, default: False
  96. In the following, "arguments of `f`" refers to the array ``xi`` and
  97. any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
  98. of `a`, `b`, and all elements of `args` (which is conceptually
  99. distinct from ``xi`` and ``argsi`` passed into `f`).
  100. - When ``preserve_shape=False`` (default), `f` must accept arguments
  101. of *any* broadcastable shapes.
  102. - When ``preserve_shape=True``, `f` must accept arguments of shape
  103. ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
  104. abscissae at which the function is being evaluated.
  105. In either case, for each scalar element ``xi[j]`` within ``xi``, the array
  106. returned by `f` must include the scalar ``f(xi[j])`` at the same index.
  107. Consequently, the shape of the output is always the shape of the input
  108. ``xi``.
  109. See Examples.
  110. callback : callable, optional
  111. An optional user-supplied function to be called before the first
  112. iteration and after each iteration.
  113. Called as ``callback(res)``, where ``res`` is a ``_RichResult``
  114. similar to that returned by `tanhsinh` (but containing the
  115. current iterate's values of all variables). If `callback` raises a
  116. ``StopIteration``, the algorithm will terminate immediately and
  117. `tanhsinh` will return a result object. `callback` must not mutate
  118. `res` or its attributes.
  119. Returns
  120. -------
  121. res : _RichResult
  122. An object similar to an instance of `scipy.optimize.OptimizeResult` with the
  123. following attributes. (The descriptions are written as though the values will
  124. be scalars; however, if `f` returns an array, the outputs will be
  125. arrays of the same shape.)
  126. success : bool array
  127. ``True`` when the algorithm terminated successfully (status ``0``).
  128. ``False`` otherwise.
  129. status : int array
  130. An integer representing the exit status of the algorithm.
  131. - ``0`` : The algorithm converged to the specified tolerances.
  132. - ``-1`` : (unused)
  133. - ``-2`` : The maximum number of iterations was reached.
  134. - ``-3`` : A non-finite value was encountered.
  135. - ``-4`` : Iteration was terminated by `callback`.
  136. - ``1`` : The algorithm is proceeding normally (in `callback` only).
  137. integral : float array
  138. An estimate of the integral.
  139. error : float array
  140. An estimate of the error. Only available if level two or higher
  141. has been completed; otherwise NaN.
  142. maxlevel : int array
  143. The maximum refinement level used.
  144. nfev : int array
  145. The number of points at which `f` was evaluated.
  146. See Also
  147. --------
  148. quad
  149. Notes
  150. -----
  151. Implements the algorithm as described in [1]_ with minor adaptations for
  152. finite-precision arithmetic, including some described by [2]_ and [3]_. The
  153. tanh-sinh scheme was originally introduced in [4]_.
  154. Two error estimation schemes are described in [1]_ Section 5: one attempts to
  155. detect and exploit quadratic convergence; the other simply compares the integral
  156. estimates at successive levels. While neither is theoretically rigorous or
  157. conservative, both work well in practice. Our error estimate uses the minimum of
  158. these two schemes with a lower bound of ``eps * res.integral``.
  159. Due to floating-point error in the abscissae, the function may be evaluated
  160. at the endpoints of the interval during iterations, but the values returned by
  161. the function at the endpoints will be ignored.
  162. References
  163. ----------
  164. .. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of
  165. three high-precision quadrature schemes." Experimental Mathematics 14.3
  166. (2005): 317-329.
  167. .. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for
  168. single and multiple integration using floating-point arithmetic."
  169. arXiv preprint arXiv:2007.15057 (2020).
  170. .. [3] van Engelen, Robert A. "Improving the Double Exponential Quadrature
  171. Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas."
  172. https://www.genivia.com/files/qthsh.pdf
  173. .. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for
  174. numerical integration." Publications of the Research Institute for
  175. Mathematical Sciences 9.3 (1974): 721-741.
  176. Examples
  177. --------
  178. Evaluate the Gaussian integral:
  179. >>> import numpy as np
  180. >>> from scipy.integrate import tanhsinh
  181. >>> def f(x):
  182. ... return np.exp(-x**2)
  183. >>> res = tanhsinh(f, -np.inf, np.inf)
  184. >>> res.integral # true value is np.sqrt(np.pi), 1.7724538509055159
  185. 1.7724538509055159
  186. >>> res.error # actual error is 0
  187. 4.0007963937534104e-16
  188. The value of the Gaussian function (bell curve) is nearly zero for
  189. arguments sufficiently far from zero, so the value of the integral
  190. over a finite interval is nearly the same.
  191. >>> tanhsinh(f, -20, 20).integral
  192. 1.772453850905518
  193. However, with unfavorable integration limits, the integration scheme
  194. may not be able to find the important region.
  195. >>> tanhsinh(f, -np.inf, 1000).integral
  196. 4.500490856616431
  197. In such cases, or when there are singularities within the interval,
  198. break the integral into parts with endpoints at the important points.
  199. >>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral
  200. 1.772453850905404
  201. For integration involving very large or very small magnitudes, use
  202. log-integration. (For illustrative purposes, the following example shows a
  203. case in which both regular and log-integration work, but for more extreme
  204. limits of integration, log-integration would avoid the underflow
  205. experienced when evaluating the integral normally.)
  206. >>> res = tanhsinh(f, 20, 30, rtol=1e-10)
  207. >>> res.integral, res.error
  208. (4.7819613911309014e-176, 4.670364401645202e-187)
  209. >>> def log_f(x):
  210. ... return -x**2
  211. >>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10))
  212. >>> np.exp(res.integral), np.exp(res.error)
  213. (4.7819613911306924e-176, 4.670364401645093e-187)
  214. The limits of integration and elements of `args` may be broadcastable
  215. arrays, and integration is performed elementwise.
  216. >>> from scipy import stats
  217. >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18)
  218. >>> a, b = dist.support()
  219. >>> x = np.linspace(a, b, 100)
  220. >>> res = tanhsinh(dist.pdf, a, x)
  221. >>> ref = dist.cdf(x)
  222. >>> np.allclose(res.integral, ref)
  223. True
  224. By default, `preserve_shape` is False, and therefore the callable
  225. `f` may be called with arrays of any broadcastable shapes.
  226. For example:
  227. >>> shapes = []
  228. >>> def f(x, c):
  229. ... shape = np.broadcast_shapes(x.shape, c.shape)
  230. ... shapes.append(shape)
  231. ... return np.sin(c*x)
  232. >>>
  233. >>> c = [1, 10, 30, 100]
  234. >>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1)
  235. >>> shapes
  236. [(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)]
  237. To understand where these shapes are coming from - and to better
  238. understand how `tanhsinh` computes accurate results - note that
  239. higher values of ``c`` correspond with higher frequency sinusoids.
  240. The higher frequency sinusoids make the integrand more complicated,
  241. so more function evaluations are required to achieve the target
  242. accuracy:
  243. >>> res.nfev
  244. array([ 67, 131, 259, 515], dtype=int32)
  245. The initial ``shape``, ``(4,)``, corresponds with evaluating the
  246. integrand at a single abscissa and all four frequencies; this is used
  247. for input validation and to determine the size and dtype of the arrays
  248. that store results. The next shape corresponds with evaluating the
  249. integrand at an initial grid of abscissae and all four frequencies.
  250. Successive calls to the function double the total number of abscissae at
  251. which the function has been evaluated. However, in later function
  252. evaluations, the integrand is evaluated at fewer frequencies because
  253. the corresponding integral has already converged to the required
  254. tolerance. This saves function evaluations to improve performance, but
  255. it requires the function to accept arguments of any shape.
  256. "Vector-valued" integrands, such as those written for use with
  257. `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement.
  258. For example, consider
  259. >>> def f(x):
  260. ... return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2]
  261. This integrand is not compatible with `tanhsinh` as written; for instance,
  262. the shape of the output will not be the same as the shape of ``x``. Such a
  263. function *could* be converted to a compatible form with the introduction of
  264. additional parameters, but this would be inconvenient. In such cases,
  265. a simpler solution would be to use `preserve_shape`.
  266. >>> shapes = []
  267. >>> def f(x):
  268. ... shapes.append(x.shape)
  269. ... x0, x1, x2, x3 = x
  270. ... return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)]
  271. >>>
  272. >>> a = np.zeros(4)
  273. >>> res = tanhsinh(f, a, 1, preserve_shape=True)
  274. >>> shapes
  275. [(4,), (4, 66), (4, 64), (4, 128), (4, 256)]
  276. Here, the broadcasted shape of `a` and `b` is ``(4,)``. With
  277. ``preserve_shape=True``, the function may be called with argument
  278. ``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe.
  279. """
  280. maxfun = None # unused right now
  281. (f, a, b, log, maxfun, maxlevel, minlevel,
  282. atol, rtol, args, preserve_shape, callback, xp) = _tanhsinh_iv(
  283. f, a, b, log, maxfun, maxlevel, minlevel, atol,
  284. rtol, args, preserve_shape, callback)
  285. # Initialization
  286. # `eim._initialize` does several important jobs, including
  287. # ensuring that limits, each of the `args`, and the output of `f`
  288. # broadcast correctly and are of consistent types. To save a function
  289. # evaluation, I pass the midpoint of the integration interval. This comes
  290. # at a cost of some gymnastics to ensure that the midpoint has the right
  291. # shape and dtype. Did you know that 0d and >0d arrays follow different
  292. # type promotion rules?
  293. with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
  294. c = xp.reshape((xp_ravel(a) + xp_ravel(b))/2, a.shape)
  295. inf_a, inf_b = xp.isinf(a), xp.isinf(b)
  296. c[inf_a] = b[inf_a] - 1. # takes care of infinite a
  297. c[inf_b] = a[inf_b] + 1. # takes care of infinite b
  298. c[inf_a & inf_b] = 0. # takes care of infinite a and b
  299. temp = eim._initialize(f, (c,), args, complex_ok=True,
  300. preserve_shape=preserve_shape, xp=xp)
  301. f, xs, fs, args, shape, dtype, xp = temp
  302. a = xp_ravel(xp.astype(xp.broadcast_to(a, shape), dtype))
  303. b = xp_ravel(xp.astype(xp.broadcast_to(b, shape), dtype))
  304. # Transform improper integrals
  305. a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b, xp)
  306. # Define variables we'll need
  307. nit, nfev = 0, 1 # one function evaluation performed above
  308. zero = -xp.inf if log else 0
  309. pi = xp.asarray(xp.pi, dtype=dtype)[()]
  310. maxiter = maxlevel - minlevel + 1
  311. eps = xp.finfo(dtype).eps
  312. if rtol is None:
  313. rtol = 0.75*math.log(eps) if log else eps**0.75
  314. Sn = xp_ravel(xp.full(shape, zero, dtype=dtype)) # latest integral estimate
  315. Sn[xp.isnan(a) | xp.isnan(b) | xp.isnan(fs[0])] = xp.nan
  316. Sk = xp.reshape(xp.empty_like(Sn), (-1, 1))[:, 0:0] # all integral estimates
  317. aerr = xp_ravel(xp.full(shape, xp.nan, dtype=dtype)) # absolute error
  318. status = xp_ravel(xp.full(shape, eim._EINPROGRESS, dtype=xp.int32))
  319. h0 = _get_base_step(dtype, xp)
  320. h0 = xp.real(h0) # base step
  321. # For term `d4` of error estimate ([1] Section 5), we need to keep the
  322. # most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin
  323. # sum. Here, we initialize these variables.
  324. xr0 = xp_ravel(xp.full(shape, -xp.inf, dtype=dtype))
  325. fr0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
  326. wr0 = xp_ravel(xp.zeros(shape, dtype=dtype))
  327. xl0 = xp_ravel(xp.full(shape, xp.inf, dtype=dtype))
  328. fl0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
  329. wl0 = xp_ravel(xp.zeros(shape, dtype=dtype))
  330. d4 = xp_ravel(xp.zeros(shape, dtype=dtype))
  331. work = _RichResult(
  332. Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps,
  333. a=xp.reshape(a, (-1, 1)), b=xp.reshape(b, (-1, 1)), # integration limits
  334. n=minlevel, nit=nit, nfev=nfev, status=status, # iter/eval counts
  335. xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4, # err est
  336. ainf=ainf, binf=binf, abinf=abinf, a0=xp.reshape(a0, (-1, 1)), # transforms
  337. # Store the xjc/wj pair cache in an object so they can't get compressed
  338. # Using RichResult to allow dot notation, but a dictionary would suffice
  339. pair_cache=_RichResult(xjc=None, wj=None, indices=[0], h0=None)) # pair cache
  340. # Constant scalars don't need to be put in `work` unless they need to be
  341. # passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel.
  342. # Correspondence between terms in the `work` object and the result
  343. res_work_pairs = [('status', 'status'), ('integral', 'Sn'),
  344. ('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')]
  345. def pre_func_eval(work):
  346. # Determine abscissae at which to evaluate `f`
  347. work.h = h0 / 2**work.n
  348. xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype,
  349. inclusive=(work.n == minlevel), xp=xp, work=work)
  350. work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b, xp)
  351. # Perform abscissae substitutions for infinite limits of integration
  352. xj = xp_copy(work.xj)
  353. xj[work.abinf] = xj[work.abinf] / (1 - xp.real(xj[work.abinf])**2)
  354. xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf]
  355. xj[work.ainf] *= -1
  356. return xj
  357. def post_func_eval(x, fj, work):
  358. # Weight integrand as required by substitutions for infinite limits
  359. if work.log:
  360. fj[work.abinf] += (xp.log(1 + work.xj[work.abinf]**2)
  361. - 2*xp.log(1 - work.xj[work.abinf]**2))
  362. fj[work.binf] -= 2 * xp.log(work.xj[work.binf])
  363. else:
  364. fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) /
  365. (1 - work.xj[work.abinf]**2)**2)
  366. fj[work.binf] *= work.xj[work.binf]**-2.
  367. # Estimate integral with Euler-Maclaurin Sum
  368. fjwj, Sn = _euler_maclaurin_sum(fj, work, xp)
  369. if work.Sk.shape[-1]:
  370. Snm1 = work.Sk[:, -1]
  371. Sn = (special.logsumexp(xp.stack([Snm1 - math.log(2), Sn]), axis=0) if log
  372. else Snm1 / 2 + Sn)
  373. work.fjwj = fjwj
  374. work.Sn = Sn
  375. def check_termination(work):
  376. """Terminate due to convergence or encountering non-finite values"""
  377. stop = xp.zeros(work.Sn.shape, dtype=bool)
  378. # Terminate before first iteration if integration limits are equal
  379. if work.nit == 0:
  380. i = xp_ravel(work.a == work.b) # ravel singleton dimension
  381. zero = xp.asarray(-xp.inf if log else 0.)
  382. zero = xp.full(work.Sn.shape, zero, dtype=Sn.dtype)
  383. zero[xp.isnan(Sn)] = xp.nan
  384. work.Sn[i] = zero[i]
  385. work.aerr[i] = zero[i]
  386. work.status[i] = eim._ECONVERGED
  387. stop[i] = True
  388. else:
  389. # Terminate if convergence criterion is met
  390. rerr, aerr = _estimate_error(work, xp)
  391. i = (rerr < rtol) | (aerr < atol)
  392. work.aerr = xp.reshape(xp.astype(aerr, work.dtype), work.Sn.shape)
  393. work.status[i] = eim._ECONVERGED
  394. stop[i] = True
  395. # Terminate if integral estimate becomes invalid
  396. if log:
  397. Sn_real = xp.real(work.Sn)
  398. Sn_pos_inf = xp.isinf(Sn_real) & (Sn_real > 0)
  399. i = (Sn_pos_inf | xp.isnan(work.Sn)) & ~stop
  400. else:
  401. i = ~xp.isfinite(work.Sn) & ~stop
  402. work.status[i] = eim._EVALUEERR
  403. stop[i] = True
  404. return stop
  405. def post_termination_check(work):
  406. work.n += 1
  407. work.Sk = xp.concat((work.Sk, work.Sn[:, xp.newaxis]), axis=-1)
  408. return
  409. def customize_result(res, shape):
  410. # If the integration limits were such that b < a, we reversed them
  411. # to perform the calculation, and the final result needs to be negated.
  412. if log and xp.any(negative):
  413. res['integral'] = res['integral'] + negative * xp.pi * 1.0j
  414. else:
  415. res['integral'][negative] *= -1
  416. # For this algorithm, it seems more appropriate to report the maximum
  417. # level rather than the number of iterations in which it was performed.
  418. res['maxlevel'] = minlevel + res['nit'] - 1
  419. res['maxlevel'][res['nit'] == 0] = -1
  420. del res['nit']
  421. return shape
  422. # Suppress all warnings initially, since there are many places in the code
  423. # for which this is expected behavior.
  424. with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
  425. res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval,
  426. post_func_eval, check_termination, post_termination_check,
  427. customize_result, res_work_pairs, xp, preserve_shape)
  428. return res
  429. def _get_base_step(dtype, xp):
  430. # Compute the base step length for the provided dtype. Theoretically, the
  431. # Euler-Maclaurin sum is infinite, but it gets cut off when either the
  432. # weights underflow or the abscissae cannot be distinguished from the
  433. # limits of integration. The latter happens to occur first for float32 and
  434. # float64, and it occurs when `xjc` (the abscissa complement)
  435. # in `_compute_pair` underflows. We can solve for the argument `tmax` at
  436. # which it will underflow using [2] Eq. 13.
  437. fmin = 4*xp.finfo(dtype).smallest_normal # stay a little away from the limit
  438. tmax = math.asinh(math.log(2/fmin - 1) / xp.pi)
  439. # Based on this, we can choose a base step size `h` for level 0.
  440. # The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is
  441. # the level and `m` is an integer we get to choose. I choose
  442. # m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a
  443. # power of 2 makes floating point arithmetic more predictable. It also
  444. # results in a base step size close to `1`, which is what [1] uses (and I
  445. # used here until I found [2] and these ideas settled).
  446. h0 = tmax / _N_BASE_STEPS
  447. return xp.asarray(h0, dtype=dtype)[()]
  448. _N_BASE_STEPS = 8
  449. def _compute_pair(k, h0, xp):
  450. # Compute the abscissa-weight pairs for each level k. See [1] page 9.
  451. # For now, we compute and store in 64-bit precision. If higher-precision
  452. # data types become better supported, it would be good to compute these
  453. # using the highest precision available. Or, once there is an Array API-
  454. # compatible arbitrary precision array, we can compute at the required
  455. # precision.
  456. # "....each level k of abscissa-weight pairs uses h = 2 **-k"
  457. # We adapt to floating point arithmetic using ideas of [2].
  458. h = h0 / 2**k
  459. max = _N_BASE_STEPS * 2**k
  460. # For iterations after the first, "....the integrand function needs to be
  461. # evaluated only at the odd-indexed abscissas at each level."
  462. j = xp.arange(max+1) if k == 0 else xp.arange(1, max+1, 2)
  463. jh = j * h
  464. # "In this case... the weights wj = u1/cosh(u2)^2, where..."
  465. pi_2 = xp.pi / 2
  466. u1 = pi_2*xp.cosh(jh)
  467. u2 = pi_2*xp.sinh(jh)
  468. # Denominators get big here. Overflow then underflow doesn't need warning.
  469. # with np.errstate(under='ignore', over='ignore'):
  470. wj = u1 / xp.cosh(u2)**2
  471. # "We actually store 1-xj = 1/(...)."
  472. xjc = 1 / (xp.exp(u2) * xp.cosh(u2)) # complement of xj = xp.tanh(u2)
  473. # When level k == 0, the zeroth xj corresponds with xj = 0. To simplify
  474. # code, the function will be evaluated there twice; each gets half weight.
  475. wj[0] = wj[0] / 2 if k == 0 else wj[0]
  476. return xjc, wj # store at full precision
  477. def _pair_cache(k, h0, xp, work):
  478. # Cache the abscissa-weight pairs up to a specified level.
  479. # Abscissae and weights of consecutive levels are concatenated.
  480. # `index` records the indices that correspond with each level:
  481. # `xjc[index[k]:index[k+1]` extracts the level `k` abscissae.
  482. if not isinstance(h0, type(work.pair_cache.h0)) or h0 != work.pair_cache.h0:
  483. work.pair_cache.xjc = xp.empty(0)
  484. work.pair_cache.wj = xp.empty(0)
  485. work.pair_cache.indices = [0]
  486. xjcs = [work.pair_cache.xjc]
  487. wjs = [work.pair_cache.wj]
  488. for i in range(len(work.pair_cache.indices)-1, k + 1):
  489. xjc, wj = _compute_pair(i, h0, xp)
  490. xjcs.append(xjc)
  491. wjs.append(wj)
  492. work.pair_cache.indices.append(work.pair_cache.indices[-1] + xjc.shape[0])
  493. work.pair_cache.xjc = xp.concat(xjcs)
  494. work.pair_cache.wj = xp.concat(wjs)
  495. work.pair_cache.h0 = h0
  496. def _get_pairs(k, h0, inclusive, dtype, xp, work):
  497. # Retrieve the specified abscissa-weight pairs from the cache
  498. # If `inclusive`, return all up to and including the specified level
  499. if (len(work.pair_cache.indices) <= k+2
  500. or not isinstance (h0, type(work.pair_cache.h0))
  501. or h0 != work.pair_cache.h0):
  502. _pair_cache(k, h0, xp, work)
  503. xjc = work.pair_cache.xjc
  504. wj = work.pair_cache.wj
  505. indices = work.pair_cache.indices
  506. start = 0 if inclusive else indices[k]
  507. end = indices[k+1]
  508. return xp.astype(xjc[start:end], dtype), xp.astype(wj[start:end], dtype)
  509. def _transform_to_limits(xjc, wj, a, b, xp):
  510. # Transform integral according to user-specified limits. This is just
  511. # math that follows from the fact that the standard limits are (-1, 1).
  512. # Note: If we had stored xj instead of xjc, we would have
  513. # xj = alpha * xj + beta, where beta = (a + b)/2
  514. alpha = (b - a) / 2
  515. xj = xp.concat((-alpha * xjc + b, alpha * xjc + a), axis=-1)
  516. wj = wj*alpha # arguments get broadcasted, so we can't use *=
  517. wj = xp.concat((wj, wj), axis=-1)
  518. # Points at the boundaries can be generated due to finite precision
  519. # arithmetic, but these function values aren't supposed to be included in
  520. # the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at
  521. # these points; however, we can't easily filter out points since this
  522. # function is vectorized. Instead, zero the weights.
  523. # Note: values may have complex dtype, but have zero imaginary part
  524. xj_real, a_real, b_real = xp.real(xj), xp.real(a), xp.real(b)
  525. invalid = (xj_real <= a_real) | (xj_real >= b_real)
  526. wj[invalid] = 0
  527. return xj, wj
  528. def _euler_maclaurin_sum(fj, work, xp):
  529. # Perform the Euler-Maclaurin Sum, [1] Section 4
  530. # The error estimate needs to know the magnitude of the last term
  531. # omitted from the Euler-Maclaurin sum. This is a bit involved because
  532. # it may have been computed at a previous level. I sure hope it's worth
  533. # all the trouble.
  534. xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0
  535. xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0
  536. # It is much more convenient to work with the transposes of our work
  537. # variables here.
  538. xj, fj, wj = work.xj.T, fj.T, work.wj.T
  539. n_x, n_active = xj.shape # number of abscissae, number of active elements
  540. # We'll work with the left and right sides separately
  541. xr, xl = xp_copy(xp.reshape(xj, (2, n_x // 2, n_active))) # this gets modified
  542. fr, fl = xp.reshape(fj, (2, n_x // 2, n_active))
  543. wr, wl = xp.reshape(wj, (2, n_x // 2, n_active))
  544. invalid_r = ~xp.isfinite(fr) | (wr == 0)
  545. invalid_l = ~xp.isfinite(fl) | (wl == 0)
  546. # integer index of the maximum abscissa at this level
  547. xr[invalid_r] = -xp.inf
  548. ir = xp.argmax(xp.real(xr), axis=0, keepdims=True)
  549. # abscissa, function value, and weight at this index
  550. ### Not Array API Compatible... yet ###
  551. xr_max = xp.take_along_axis(xr, ir, axis=0)[0]
  552. fr_max = xp.take_along_axis(fr, ir, axis=0)[0]
  553. wr_max = xp.take_along_axis(wr, ir, axis=0)[0]
  554. # boolean indices at which maximum abscissa at this level exceeds
  555. # the incumbent maximum abscissa (from all previous levels)
  556. # note: abscissa may have complex dtype, but will have zero imaginary part
  557. j = xp.real(xr_max) > xp.real(xr0)
  558. # Update record of the incumbent abscissa, function value, and weight
  559. xr0[j] = xr_max[j]
  560. fr0[j] = fr_max[j]
  561. wr0[j] = wr_max[j]
  562. # integer index of the minimum abscissa at this level
  563. xl[invalid_l] = xp.inf
  564. il = xp.argmin(xp.real(xl), axis=0, keepdims=True)
  565. # abscissa, function value, and weight at this index
  566. xl_min = xp.take_along_axis(xl, il, axis=0)[0]
  567. fl_min = xp.take_along_axis(fl, il, axis=0)[0]
  568. wl_min = xp.take_along_axis(wl, il, axis=0)[0]
  569. # boolean indices at which minimum abscissa at this level is less than
  570. # the incumbent minimum abscissa (from all previous levels)
  571. # note: abscissa may have complex dtype, but will have zero imaginary part
  572. j = xp.real(xl_min) < xp.real(xl0)
  573. # Update record of the incumbent abscissa, function value, and weight
  574. xl0[j] = xl_min[j]
  575. fl0[j] = fl_min[j]
  576. wl0[j] = wl_min[j]
  577. fj = fj.T
  578. # Compute the error estimate `d4` - the magnitude of the leftmost or
  579. # rightmost term, whichever is greater.
  580. flwl0 = fl0 + xp.log(wl0) if work.log else fl0 * wl0 # leftmost term
  581. frwr0 = fr0 + xp.log(wr0) if work.log else fr0 * wr0 # rightmost term
  582. magnitude = xp.real if work.log else xp.abs
  583. work.d4 = xp.maximum(magnitude(flwl0), magnitude(frwr0))
  584. # There are two approaches to dealing with function values that are
  585. # numerically infinite due to approaching a singularity - zero them, or
  586. # replace them with the function value at the nearest non-infinite point.
  587. # [3] pg. 22 suggests the latter, so let's do that given that we have the
  588. # information.
  589. fr0b = xp.broadcast_to(fr0[xp.newaxis, :], fr.shape)
  590. fl0b = xp.broadcast_to(fl0[xp.newaxis, :], fl.shape)
  591. fr[invalid_r] = fr0b[invalid_r]
  592. fl[invalid_l] = fl0b[invalid_l]
  593. # When wj is zero, log emits a warning
  594. # with np.errstate(divide='ignore'):
  595. fjwj = fj + xp.log(work.wj) if work.log else fj * work.wj
  596. # update integral estimate
  597. Sn = (special.logsumexp(fjwj + xp.log(work.h), axis=-1) if work.log
  598. else xp.sum(fjwj, axis=-1) * work.h)
  599. work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0
  600. work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0
  601. return fjwj, Sn
  602. def _estimate_error(work, xp):
  603. # Estimate the error according to [1] Section 5
  604. if work.n == 0 or work.nit == 0:
  605. # The paper says to use "one" as the error before it can be calculated.
  606. # NaN seems to be more appropriate.
  607. nan = xp.full_like(work.Sn, xp.nan)
  608. return nan, nan
  609. indices = work.pair_cache.indices
  610. n_active = work.Sn.shape[0] # number of active elements
  611. axis_kwargs = dict(axis=-1, keepdims=True)
  612. # With a jump start (starting at level higher than 0), we haven't
  613. # explicitly calculated the integral estimate at lower levels. But we have
  614. # all the function value-weight products, so we can compute the
  615. # lower-level estimates.
  616. if work.Sk.shape[-1] == 0:
  617. h = 2 * work.h # step size at this level
  618. n_x = indices[work.n] # number of abscissa up to this level
  619. # The right and left fjwj terms from all levels are concatenated along
  620. # the last axis. Get out only the terms up to this level.
  621. fjwj_rl = xp.reshape(work.fjwj, (n_active, 2, -1))
  622. fjwj = xp.reshape(fjwj_rl[:, :, :n_x], (n_active, 2*n_x))
  623. # Compute the Euler-Maclaurin sum at this level
  624. Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
  625. else xp.sum(fjwj, **axis_kwargs) * h)
  626. work.Sk = xp.concat((Snm1, work.Sk), axis=-1)
  627. if work.n == 1:
  628. nan = xp.full_like(work.Sn, xp.nan)
  629. return nan, nan
  630. # The paper says not to calculate the error for n<=2, but it's not clear
  631. # about whether it starts at level 0 or level 1. We start at level 0, so
  632. # why not compute the error beginning in level 2?
  633. if work.Sk.shape[-1] < 2:
  634. h = 4 * work.h # step size at this level
  635. n_x = indices[work.n-1] # number of abscissa up to this level
  636. # The right and left fjwj terms from all levels are concatenated along
  637. # the last axis. Get out only the terms up to this level.
  638. fjwj_rl = xp.reshape(work.fjwj, (work.Sn.shape[0], 2, -1))
  639. fjwj = xp.reshape(fjwj_rl[..., :n_x], (n_active, 2*n_x))
  640. # Compute the Euler-Maclaurin sum at this level
  641. Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
  642. else xp.sum(fjwj, **axis_kwargs) * h)
  643. work.Sk = xp.concat((Snm2, work.Sk), axis=-1)
  644. Snm2 = work.Sk[..., -2]
  645. Snm1 = work.Sk[..., -1]
  646. e1 = xp.asarray(work.eps)[()]
  647. if work.log:
  648. log_e1 = xp.log(e1)
  649. # Currently, only real integrals are supported in log-scale. All
  650. # complex values have imaginary part in increments of pi*j, which just
  651. # carries sign information of the original integral, so use of
  652. # `xp.real` here is equivalent to absolute value in real scale.
  653. d1 = xp.real(special.logsumexp(xp.stack([work.Sn, Snm1 + work.pi*1j]), axis=0))
  654. d2 = xp.real(special.logsumexp(xp.stack([work.Sn, Snm2 + work.pi*1j]), axis=0))
  655. d3 = log_e1 + xp.max(xp.real(work.fjwj), axis=-1)
  656. d4 = work.d4
  657. d5 = log_e1 + xp.real(work.Sn)
  658. temp = xp.where(d1 > -xp.inf, d1 ** 2 / d2, -xp.inf)
  659. ds = xp.stack([temp, 2 * d1, d3, d4])
  660. aerr = xp.clip(xp.max(ds, axis=0), d5, d1)
  661. rerr = aerr - xp.real(work.Sn)
  662. else:
  663. # Note: explicit computation of log10 of each of these is unnecessary.
  664. d1 = xp.abs(work.Sn - Snm1)
  665. d2 = xp.abs(work.Sn - Snm2)
  666. d3 = e1 * xp.max(xp.abs(work.fjwj), axis=-1)
  667. d4 = work.d4
  668. d5 = e1 * xp.abs(work.Sn)
  669. temp = xp.where(d1 > 0, d1**(xp.log(d1)/xp.log(d2)), 0)
  670. ds = xp.stack([temp, d1**2, d3, d4])
  671. aerr = xp.clip(xp.max(ds, axis=0), d5, d1)
  672. rerr = aerr/xp.abs(work.Sn)
  673. return rerr, aerr
  674. def _transform_integrals(a, b, xp):
  675. # Transform integrals to a form with finite a <= b
  676. # For b == a (even infinite), we ensure that the limits remain equal
  677. # For b < a, we reverse the limits and will multiply the final result by -1
  678. # For infinite limit on the right, we use the substitution x = 1/t - 1 + a
  679. # For infinite limit on the left, we substitute x = -x and treat as above
  680. # For infinite limits, we substitute x = t / (1-t**2)
  681. ab_same = (a == b)
  682. a[ab_same], b[ab_same] = 1, 1
  683. # `a, b` may have complex dtype but have zero imaginary part
  684. negative = xp.real(b) < xp.real(a)
  685. a[negative], b[negative] = b[negative], a[negative]
  686. abinf = xp.isinf(a) & xp.isinf(b)
  687. a[abinf], b[abinf] = -1, 1
  688. ainf = xp.isinf(a)
  689. a[ainf], b[ainf] = -b[ainf], -a[ainf]
  690. binf = xp.isinf(b)
  691. a0 = xp_copy(a)
  692. a[binf], b[binf] = 0, 1
  693. return a, b, a0, negative, abinf, ainf, binf
  694. def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel,
  695. atol, rtol, args, preserve_shape, callback):
  696. # Input validation and standardization
  697. xp = array_namespace(a, b)
  698. a, b = xp_promote(a, b, broadcast=True, force_floating=True, xp=xp)
  699. message = '`f` must be callable.'
  700. if not callable(f):
  701. raise ValueError(message)
  702. message = 'All elements of `a` and `b` must be real numbers.'
  703. if (xp.isdtype(a.dtype, 'complex floating')
  704. or xp.isdtype(b.dtype, 'complex floating')):
  705. raise ValueError(message)
  706. message = '`log` must be True or False.'
  707. if log not in {True, False}:
  708. raise ValueError(message)
  709. log = bool(log)
  710. if atol is None:
  711. atol = -xp.inf if log else 0
  712. rtol_temp = rtol if rtol is not None else 0.
  713. # using NumPy for convenience here; these are just floats, not arrays
  714. params = np.asarray([atol, rtol_temp, 0.])
  715. message = "`atol` and `rtol` must be real numbers."
  716. if not np.issubdtype(params.dtype, np.floating):
  717. raise ValueError(message)
  718. if log:
  719. message = '`atol` and `rtol` may not be positive infinity.'
  720. if np.any(np.isposinf(params)):
  721. raise ValueError(message)
  722. else:
  723. message = '`atol` and `rtol` must be non-negative and finite.'
  724. if np.any(params < 0) or np.any(np.isinf(params)):
  725. raise ValueError(message)
  726. atol = params[0]
  727. rtol = rtol if rtol is None else params[1]
  728. BIGINT = float(2**62)
  729. if maxfun is None and maxlevel is None:
  730. maxlevel = 10
  731. maxfun = BIGINT if maxfun is None else maxfun
  732. maxlevel = BIGINT if maxlevel is None else maxlevel
  733. message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.'
  734. params = np.asarray([maxfun, maxlevel, minlevel])
  735. if not (np.issubdtype(params.dtype, np.number)
  736. and np.all(np.isreal(params))
  737. and np.all(params.astype(np.int64) == params)):
  738. raise ValueError(message)
  739. message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.'
  740. if np.any(params < 0):
  741. raise ValueError(message)
  742. maxfun, maxlevel, minlevel = params.astype(np.int64)
  743. minlevel = min(minlevel, maxlevel)
  744. if not np.iterable(args):
  745. args = (args,)
  746. args = (xp.asarray(arg) for arg in args)
  747. message = '`preserve_shape` must be True or False.'
  748. if preserve_shape not in {True, False}:
  749. raise ValueError(message)
  750. if callback is not None and not callable(callback):
  751. raise ValueError('`callback` must be callable.')
  752. return (f, a, b, log, maxfun, maxlevel, minlevel,
  753. atol, rtol, args, preserve_shape, callback, xp)
  754. def _nsum_iv(f, a, b, step, args, log, maxterms, tolerances):
  755. # Input validation and standardization
  756. xp = array_namespace(a, b, step)
  757. a, b, step = xp_promote(a, b, step, broadcast=True, force_floating=True, xp=xp)
  758. message = '`f` must be callable.'
  759. if not callable(f):
  760. raise ValueError(message)
  761. message = 'All elements of `a`, `b`, and `step` must be real numbers.'
  762. if not xp.isdtype(a.dtype, ('integral', 'real floating')):
  763. raise ValueError(message)
  764. valid_b = b >= a # NaNs will be False
  765. valid_step = xp.isfinite(step) & (step > 0)
  766. valid_abstep = valid_b & valid_step
  767. message = '`log` must be True or False.'
  768. if log not in {True, False}:
  769. raise ValueError(message)
  770. tolerances = {} if tolerances is None else tolerances
  771. atol = tolerances.get('atol', None)
  772. if atol is None:
  773. atol = -xp.inf if log else 0
  774. rtol = tolerances.get('rtol', None)
  775. rtol_temp = rtol if rtol is not None else 0.
  776. # using NumPy for convenience here; these are just floats, not arrays
  777. params = np.asarray([atol, rtol_temp, 0.])
  778. message = "`atol` and `rtol` must be real numbers."
  779. if not np.issubdtype(params.dtype, np.floating):
  780. raise ValueError(message)
  781. if log:
  782. message = '`atol`, `rtol` may not be positive infinity or NaN.'
  783. if np.any(np.isposinf(params) | np.isnan(params)):
  784. raise ValueError(message)
  785. else:
  786. message = '`atol`, and `rtol` must be non-negative and finite.'
  787. if np.any((params < 0) | (~np.isfinite(params))):
  788. raise ValueError(message)
  789. atol = params[0]
  790. rtol = rtol if rtol is None else params[1]
  791. maxterms_int = int(maxterms)
  792. if maxterms_int != maxterms or maxterms < 0:
  793. message = "`maxterms` must be a non-negative integer."
  794. raise ValueError(message)
  795. if not np.iterable(args):
  796. args = (args,)
  797. return f, a, b, step, valid_abstep, args, log, maxterms_int, atol, rtol, xp
  798. @xp_capabilities(skip_backends=[('torch', 'data-apis/array-api-compat#271'),
  799. ('array_api_strict', 'No fancy indexing.'),
  800. ('jax.numpy', 'No mutation.'),
  801. ('dask.array',
  802. 'Data-dependent shapes in boolean index assignment')])
  803. def nsum(f, a, b, *, step=1, args=(), log=False, maxterms=int(2**20), tolerances=None):
  804. r"""Evaluate a convergent finite or infinite series.
  805. For finite `a` and `b`, this evaluates::
  806. f(a + np.arange(n)*step).sum()
  807. where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and
  808. unimodal. The number of terms in the sum may be very large or infinite,
  809. in which case a partial sum is evaluated directly and the remainder is
  810. approximated using integration.
  811. Parameters
  812. ----------
  813. f : callable
  814. The function that evaluates terms to be summed. The signature must be::
  815. f(x: ndarray, *args) -> ndarray
  816. where each element of ``x`` is a finite real and ``args`` is a tuple,
  817. which may contain an arbitrary number of arrays that are broadcastable
  818. with ``x``.
  819. `f` must be an elementwise function: each element ``f(x)[i]``
  820. must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
  821. array ``x`` or the arrays in ``args``, and it must return NaN where
  822. the argument is NaN.
  823. `f` must represent a smooth, positive, unimodal function of `x` defined at
  824. *all reals* between `a` and `b`.
  825. a, b : float array_like
  826. Real lower and upper limits of summed terms. Must be broadcastable.
  827. Each element of `a` must be less than the corresponding element in `b`.
  828. step : float array_like
  829. Finite, positive, real step between summed terms. Must be broadcastable
  830. with `a` and `b`. Note that the number of terms included in the sum will
  831. be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure
  832. that ``f(b)`` is included if intended.
  833. args : tuple of array_like, optional
  834. Additional positional arguments to be passed to `f`. Must be arrays
  835. broadcastable with `a`, `b`, and `step`. If the callable to be summed
  836. requires arguments that are not broadcastable with `a`, `b`, and `step`,
  837. wrap that callable with `f` such that `f` accepts only `x` and
  838. broadcastable ``*args``. See Examples.
  839. log : bool, default: False
  840. Setting to True indicates that `f` returns the log of the terms
  841. and that `atol` and `rtol` are expressed as the logs of the absolute
  842. and relative errors. In this case, the result object will contain the
  843. log of the sum and error. This is useful for summands for which
  844. numerical underflow or overflow would lead to inaccuracies.
  845. maxterms : int, default: 2**20
  846. The maximum number of terms to evaluate for direct summation.
  847. Additional function evaluations may be performed for input
  848. validation and integral evaluation.
  849. atol, rtol : float, optional
  850. Absolute termination tolerance (default: 0) and relative termination
  851. tolerance (default: ``eps**0.5``, where ``eps`` is the precision of
  852. the result dtype), respectively. Must be non-negative
  853. and finite if `log` is False, and must be expressed as the log of a
  854. non-negative and finite number if `log` is True.
  855. Returns
  856. -------
  857. res : _RichResult
  858. An object similar to an instance of `scipy.optimize.OptimizeResult` with the
  859. following attributes. (The descriptions are written as though the values will
  860. be scalars; however, if `f` returns an array, the outputs will be
  861. arrays of the same shape.)
  862. success : bool
  863. ``True`` when the algorithm terminated successfully (status ``0``);
  864. ``False`` otherwise.
  865. status : int array
  866. An integer representing the exit status of the algorithm.
  867. - ``0`` : The algorithm converged to the specified tolerances.
  868. - ``-1`` : Element(s) of `a`, `b`, or `step` are invalid
  869. - ``-2`` : Numerical integration reached its iteration limit;
  870. the sum may be divergent.
  871. - ``-3`` : A non-finite value was encountered.
  872. - ``-4`` : The magnitude of the last term of the partial sum exceeds
  873. the tolerances, so the error estimate exceeds the tolerances.
  874. Consider increasing `maxterms` or loosening `tolerances`.
  875. Alternatively, the callable may not be unimodal, or the limits of
  876. summation may be too far from the function maximum. Consider
  877. increasing `maxterms` or breaking the sum into pieces.
  878. sum : float array
  879. An estimate of the sum.
  880. error : float array
  881. An estimate of the absolute error, assuming all terms are non-negative,
  882. the function is computed exactly, and direct summation is accurate to
  883. the precision of the result dtype.
  884. nfev : int array
  885. The number of points at which `f` was evaluated.
  886. See Also
  887. --------
  888. mpmath.nsum
  889. Notes
  890. -----
  891. The method implemented for infinite summation is related to the integral
  892. test for convergence of an infinite series: assuming `step` size 1 for
  893. simplicity of exposition, the sum of a monotone decreasing function is bounded by
  894. .. math::
  895. \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u)
  896. Let :math:`a` represent `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a`
  897. represent `atol`, and :math:`\epsilon_r` represent `rtol`.
  898. The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx`
  899. as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such
  900. that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise,
  901. let :math:`c = a + n`. Then the infinite sum is approximated as
  902. .. math::
  903. \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2
  904. and the reported error is :math:`f(c)/2` plus the error estimate of
  905. numerical integration. Note that the integral approximations may require
  906. evaluation of the function at points besides those that appear in the sum,
  907. so `f` must be a continuous and monotonically decreasing function defined
  908. for all reals within the integration interval. However, due to the nature
  909. of the integral approximation, the shape of the function between points
  910. that appear in the sum has little effect. If there is not a natural
  911. extension of the function to all reals, consider using linear interpolation,
  912. which is easy to evaluate and preserves monotonicity.
  913. The approach described above is generalized for non-unit
  914. `step` and finite `b` that is too large for direct evaluation of the sum,
  915. i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal
  916. functions by directly summing terms surrounding the maximum.
  917. This strategy may fail:
  918. - If the left limit is finite and the maximum is far from it.
  919. - If the right limit is finite and the maximum is far from it.
  920. - If both limits are finite and the maximum is far from the origin.
  921. In these cases, accuracy may be poor, and `nsum` may return status code ``4``.
  922. Although the callable `f` must be non-negative and unimodal,
  923. `nsum` can be used to evaluate more general forms of series. For instance, to
  924. evaluate an alternating series, pass a callable that returns the difference
  925. between pairs of adjacent terms, and adjust `step` accordingly. See Examples.
  926. References
  927. ----------
  928. .. [1] Wikipedia. "Integral test for convergence."
  929. https://en.wikipedia.org/wiki/Integral_test_for_convergence
  930. Examples
  931. --------
  932. Compute the infinite sum of the reciprocals of squared integers.
  933. >>> import numpy as np
  934. >>> from scipy.integrate import nsum
  935. >>> res = nsum(lambda k: 1/k**2, 1, np.inf)
  936. >>> ref = np.pi**2/6 # true value
  937. >>> res.error # estimated error
  938. np.float64(7.448762306416137e-09)
  939. >>> (res.sum - ref)/ref # true error
  940. np.float64(-1.839871898894426e-13)
  941. >>> res.nfev # number of points at which callable was evaluated
  942. np.int32(8561)
  943. Compute the infinite sums of the reciprocals of integers raised to powers ``p``,
  944. where ``p`` is an array.
  945. >>> from scipy import special
  946. >>> p = np.arange(3, 10)
  947. >>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,))
  948. >>> ref = special.zeta(p, 1)
  949. >>> np.allclose(res.sum, ref)
  950. True
  951. Evaluate the alternating harmonic series.
  952. >>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2)
  953. >>> res.sum, res.sum - np.log(2) # result, difference vs analytical sum
  954. (np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14))
  955. """ # noqa: E501
  956. # Potential future work:
  957. # - improve error estimate of `_direct` sum
  958. # - add other methods for convergence acceleration (Richardson, epsilon)
  959. # - support negative monotone increasing functions?
  960. # - b < a / negative step?
  961. # - complex-valued function?
  962. # - check for violations of monotonicity?
  963. # Function-specific input validation / standardization
  964. tmp = _nsum_iv(f, a, b, step, args, log, maxterms, tolerances)
  965. f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol, xp = tmp
  966. # Additional elementwise algorithm input validation / standardization
  967. tmp = eim._initialize(f, (a,), args, complex_ok=False, xp=xp)
  968. f, xs, fs, args, shape, dtype, xp = tmp
  969. # Finish preparing `a`, `b`, and `step` arrays
  970. a = xs[0]
  971. b = xp.astype(xp_ravel(xp.broadcast_to(b, shape)), dtype)
  972. step = xp.astype(xp_ravel(xp.broadcast_to(step, shape)), dtype)
  973. valid_abstep = xp_ravel(xp.broadcast_to(valid_abstep, shape))
  974. nterms = xp.floor((b - a) / step)
  975. finite_terms = xp.isfinite(nterms)
  976. b[finite_terms] = a[finite_terms] + nterms[finite_terms]*step[finite_terms]
  977. # Define constants
  978. eps = xp.finfo(dtype).eps
  979. zero = xp.asarray(-xp.inf if log else 0, dtype=dtype)[()]
  980. if rtol is None:
  981. rtol = 0.5*math.log(eps) if log else eps**0.5
  982. constants = (dtype, log, eps, zero, rtol, atol, maxterms)
  983. # Prepare result arrays
  984. S = xp.empty_like(a)
  985. E = xp.empty_like(a)
  986. status = xp.zeros(len(a), dtype=xp.int32)
  987. nfev = xp.ones(len(a), dtype=xp.int32) # one function evaluation above
  988. # Branch for direct sum evaluation / integral approximation / invalid input
  989. i0 = ~valid_abstep # invalid
  990. i0b = b < a # zero
  991. i1 = (nterms + 1 <= maxterms) & ~i0 # direct sum evaluation
  992. i2 = xp.isfinite(a) & ~i1 & ~i0 # infinite sum to the right
  993. i3 = xp.isfinite(b) & ~i2 & ~i1 & ~i0 # infinite sum to the left
  994. i4 = ~i3 & ~i2 & ~i1 & ~i0 # infinite sum on both sides
  995. if xp.any(i0):
  996. S[i0], E[i0] = xp.nan, xp.nan
  997. status[i0] = -1
  998. S[i0b], E[i0b] = zero, zero
  999. status[i0b] = 0
  1000. if xp.any(i1):
  1001. args_direct = [arg[i1] for arg in args]
  1002. tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants, xp)
  1003. S[i1], E[i1] = tmp[:-1]
  1004. nfev[i1] += tmp[-1]
  1005. status[i1] = -3 * xp.asarray(~xp.isfinite(S[i1]), dtype=xp.int32)
  1006. if xp.any(i2):
  1007. args_indirect = [arg[i2] for arg in args]
  1008. tmp = _integral_bound(f, a[i2], b[i2], step[i2],
  1009. args_indirect, constants, xp)
  1010. S[i2], E[i2], status[i2] = tmp[:-1]
  1011. nfev[i2] += tmp[-1]
  1012. if xp.any(i3):
  1013. args_indirect = [arg[i3] for arg in args]
  1014. def _f(x, *args): return f(-x, *args)
  1015. tmp = _integral_bound(_f, -b[i3], -a[i3], step[i3],
  1016. args_indirect, constants, xp)
  1017. S[i3], E[i3], status[i3] = tmp[:-1]
  1018. nfev[i3] += tmp[-1]
  1019. if xp.any(i4):
  1020. args_indirect = [arg[i4] for arg in args]
  1021. # There are two obvious high-level strategies:
  1022. # - Do two separate half-infinite sums (e.g. from -inf to 0 and 1 to inf)
  1023. # - Make a callable that returns f(x) + f(-x) and do a single half-infinite sum
  1024. # I thought the latter would have about half the overhead, so I went that way.
  1025. # Then there are two ways of ensuring that f(0) doesn't get counted twice.
  1026. # - Evaluate the sum from 1 to inf and add f(0)
  1027. # - Evaluate the sum from 0 to inf and subtract f(0)
  1028. # - Evaluate the sum from 0 to inf, but apply a weight of 0.5 when `x = 0`
  1029. # The last option has more overhead, but is simpler to implement correctly
  1030. # (especially getting the status message right)
  1031. if log:
  1032. def _f(x, *args):
  1033. log_factor = xp.where(x==0, math.log(0.5), 0)
  1034. out = xp.stack([f(x, *args), f(-x, *args)], axis=0)
  1035. return special.logsumexp(out, axis=0) + log_factor
  1036. else:
  1037. def _f(x, *args):
  1038. factor = xp.where(x==0, 0.5, 1)
  1039. return (f(x, *args) + f(-x, *args)) * factor
  1040. zero = xp.zeros_like(a[i4])
  1041. tmp = _integral_bound(_f, zero, b[i4], step[i4], args_indirect, constants, xp)
  1042. S[i4], E[i4], status[i4] = tmp[:-1]
  1043. nfev[i4] += 2*tmp[-1]
  1044. # Return results
  1045. S, E = S.reshape(shape)[()], E.reshape(shape)[()]
  1046. status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()]
  1047. return _RichResult(sum=S, error=E, status=status, success=status == 0,
  1048. nfev=nfev)
  1049. def _direct(f, a, b, step, args, constants, xp, inclusive=True):
  1050. # Directly evaluate the sum.
  1051. # When used in the context of distributions, `args` would contain the
  1052. # distribution parameters. We have broadcasted for simplicity, but we could
  1053. # reduce function evaluations when distribution parameters are the same but
  1054. # sum limits differ. Roughly:
  1055. # - compute the function at all points between min(a) and max(b),
  1056. # - compute the cumulative sum,
  1057. # - take the difference between elements of the cumulative sum
  1058. # corresponding with b and a.
  1059. # This is left to future enhancement
  1060. dtype, log, eps, zero, _, _, _ = constants
  1061. # To allow computation in a single vectorized call, find the maximum number
  1062. # of points (over all slices) at which the function needs to be evaluated.
  1063. # Note: if `inclusive` is `True`, then we want `1` more term in the sum.
  1064. # I didn't think it was great style to use `True` as `1` in Python, so I
  1065. # explicitly converted it to an `int` before using it.
  1066. inclusive_adjustment = int(inclusive)
  1067. steps = xp.round((b - a) / step) + inclusive_adjustment
  1068. # Equivalently, steps = xp.round((b - a) / step) + inclusive
  1069. max_steps = int(xp.max(steps))
  1070. # In each slice, the function will be evaluated at the same number of points,
  1071. # but excessive points (those beyond the right sum limit `b`) are replaced
  1072. # with NaN to (potentially) reduce the time of these unnecessary calculations.
  1073. # Use a new last axis for these calculations for consistency with other
  1074. # elementwise algorithms.
  1075. a2, b2, step2 = a[:, xp.newaxis], b[:, xp.newaxis], step[:, xp.newaxis]
  1076. args2 = [arg[:, xp.newaxis] for arg in args]
  1077. ks = a2 + xp.arange(max_steps, dtype=dtype) * step2
  1078. i_nan = ks >= (b2 + inclusive_adjustment*step2/2)
  1079. ks[i_nan] = xp.nan
  1080. fs = f(ks, *args2)
  1081. # The function evaluated at NaN is NaN, and NaNs are zeroed in the sum.
  1082. # In some cases it may be faster to loop over slices than to vectorize
  1083. # like this. This is an optimization that can be added later.
  1084. fs[i_nan] = zero
  1085. nfev = max_steps - i_nan.sum(axis=-1)
  1086. S = special.logsumexp(fs, axis=-1) if log else xp.sum(fs, axis=-1)
  1087. # Rough, non-conservative error estimate. See gh-19667 for improvement ideas.
  1088. E = xp.real(S) + math.log(eps) if log else eps * abs(S)
  1089. return S, E, nfev
  1090. def _integral_bound(f, a, b, step, args, constants, xp):
  1091. # Estimate the sum with integral approximation
  1092. dtype, log, _, _, rtol, atol, maxterms = constants
  1093. log2 = xp.asarray(math.log(2), dtype=dtype)
  1094. # Get a lower bound on the sum and compute effective absolute tolerance
  1095. lb = tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log)
  1096. tol = xp.broadcast_to(xp.asarray(atol), lb.integral.shape)
  1097. if log:
  1098. tol = special.logsumexp(xp.stack((tol, rtol + lb.integral)), axis=0)
  1099. else:
  1100. tol = tol + rtol*lb.integral
  1101. i_skip = lb.status == -3 # avoid unnecessary f_evals if integral is divergent
  1102. tol[i_skip] = xp.nan
  1103. status = lb.status
  1104. # As in `_direct`, we'll need a temporary new axis for points
  1105. # at which to evaluate the function. Append axis at the end for
  1106. # consistency with other elementwise algorithms.
  1107. a2 = a[..., xp.newaxis]
  1108. step2 = step[..., xp.newaxis]
  1109. args2 = [arg[..., xp.newaxis] for arg in args]
  1110. # Find the location of a term that is less than the tolerance (if possible)
  1111. log2maxterms = math.floor(math.log2(maxterms)) if maxterms else 0
  1112. n_steps = xp.concat((2**xp.arange(0, log2maxterms), xp.asarray([maxterms])))
  1113. n_steps = xp.astype(n_steps, dtype)
  1114. nfev = len(n_steps) * 2
  1115. ks = a2 + n_steps * step2
  1116. fks = f(ks, *args2)
  1117. fksp1 = f(ks + step2, *args2) # check that the function is decreasing
  1118. fk_insufficient = (fks > tol[:, xp.newaxis]) | (fksp1 > fks)
  1119. n_fk_insufficient = xp.sum(fk_insufficient, axis=-1)
  1120. nt = xp.minimum(n_fk_insufficient, n_steps.shape[-1]-1)
  1121. n_steps = n_steps[nt]
  1122. # If `maxterms` is insufficient (i.e. either the magnitude of the last term of the
  1123. # partial sum exceeds the tolerance or the function is not decreasing), finish the
  1124. # calculation, but report nonzero status. (Improvement: separate the status codes
  1125. # for these two cases.)
  1126. i_fk_insufficient = (n_fk_insufficient == nfev//2)
  1127. # Directly evaluate the sum up to this term
  1128. k = a + n_steps * step
  1129. left, left_error, left_nfev = _direct(f, a, k, step, args,
  1130. constants, xp, inclusive=False)
  1131. left_is_pos_inf = xp.isinf(left) & (left > 0)
  1132. i_skip |= left_is_pos_inf # if sum is infinite, no sense in continuing
  1133. status[left_is_pos_inf] = -3
  1134. k[i_skip] = xp.nan
  1135. # Use integration to estimate the remaining sum
  1136. # Possible optimization for future work: if there were no terms less than
  1137. # the tolerance, there is no need to compute the integral to better accuracy.
  1138. # Something like:
  1139. # atol = xp.maximum(atol, xp.minimum(fk/2 - fb/2))
  1140. # rtol = xp.maximum(rtol, xp.minimum((fk/2 - fb/2)/left))
  1141. # where `fk`/`fb` are currently calculated below.
  1142. right = tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log)
  1143. # Calculate the full estimate and error from the pieces
  1144. fk = fks[xp.arange(len(fks)), nt]
  1145. # fb = f(b, *args), but some functions return NaN at infinity.
  1146. # instead of 0 like they must (for the sum to be convergent).
  1147. fb = xp.full_like(fk, -xp.inf) if log else xp.zeros_like(fk)
  1148. i = xp.isfinite(b)
  1149. if xp.any(i): # better not call `f` with empty arrays
  1150. fb[i] = f(b[i], *[arg[i] for arg in args])
  1151. nfev = nfev + xp.asarray(i, dtype=left_nfev.dtype)
  1152. if log:
  1153. log_step = xp.log(step)
  1154. S_terms = (left, right.integral - log_step, fk - log2, fb - log2)
  1155. S = special.logsumexp(xp.stack(S_terms), axis=0)
  1156. E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+xp.pi*1j)
  1157. E = xp.real(special.logsumexp(xp.stack(E_terms), axis=0))
  1158. else:
  1159. S = left + right.integral/step + fk/2 + fb/2
  1160. E = left_error + right.error/step + fk/2 - fb/2
  1161. status[~i_skip] = right.status[~i_skip]
  1162. status[(status == 0) & i_fk_insufficient] = -4
  1163. return S, E, status, left_nfev + right.nfev + nfev + lb.nfev