_quadpack_py.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. # Author: Travis Oliphant 2001
  2. # Author: Nathan Woods 2013 (nquad &c)
  3. import sys
  4. import warnings
  5. from functools import partial
  6. from . import _quadpack
  7. import numpy as np
  8. from scipy._lib._array_api import xp_capabilities
  9. __all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
  10. class IntegrationWarning(UserWarning):
  11. """
  12. Warning on issues during integration.
  13. """
  14. pass
  15. @xp_capabilities(np_only=True)
  16. def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
  17. limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
  18. limlst=50, complex_func=False):
  19. """
  20. Compute a definite integral.
  21. Integrate func from `a` to `b` (possibly infinite interval) using a
  22. technique from the Fortran library QUADPACK.
  23. Parameters
  24. ----------
  25. func : {function, scipy.LowLevelCallable}
  26. A Python function or method to integrate. If `func` takes many
  27. arguments, it is integrated along the axis corresponding to the
  28. first argument.
  29. If the user desires improved integration performance, then `f` may
  30. be a `scipy.LowLevelCallable` with one of the signatures::
  31. double func(double x)
  32. double func(double x, void *user_data)
  33. double func(int n, double *xx)
  34. double func(int n, double *xx, void *user_data)
  35. The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
  36. In the call forms with ``xx``, ``n`` is the length of the ``xx``
  37. array which contains ``xx[0] == x`` and the rest of the items are
  38. numbers contained in the ``args`` argument of quad.
  39. In addition, certain ctypes call signatures are supported for
  40. backward compatibility, but those should not be used in new code.
  41. a : float
  42. Lower limit of integration (use -numpy.inf for -infinity).
  43. b : float
  44. Upper limit of integration (use numpy.inf for +infinity).
  45. args : tuple, optional
  46. Extra arguments to pass to `func`.
  47. full_output : int, optional
  48. Non-zero to return a dictionary of integration information.
  49. If non-zero, warning messages are also suppressed and the
  50. message is appended to the output tuple.
  51. complex_func : bool, optional
  52. Indicate if the function's (`func`) return type is real
  53. (``complex_func=False``: default) or complex (``complex_func=True``).
  54. In both cases, the function's argument is real.
  55. If full_output is also non-zero, the `infodict`, `message`, and
  56. `explain` for the real and complex components are returned in
  57. a dictionary with keys "real output" and "imag output".
  58. Returns
  59. -------
  60. y : float
  61. The integral of func from `a` to `b`.
  62. abserr : float
  63. An estimate of the absolute error in the result.
  64. infodict : dict
  65. A dictionary containing additional information.
  66. message
  67. A convergence message.
  68. explain
  69. Appended only with 'cos' or 'sin' weighting and infinite
  70. integration limits, it contains an explanation of the codes in
  71. infodict['ierlst']
  72. Other Parameters
  73. ----------------
  74. epsabs : float or int, optional
  75. Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
  76. an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
  77. where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
  78. numerical approximation. See `epsrel` below.
  79. epsrel : float or int, optional
  80. Relative error tolerance. Default is 1.49e-8.
  81. If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
  82. and ``50 * (machine epsilon)``. See `epsabs` above.
  83. limit : float or int, optional
  84. An upper bound on the number of subintervals used in the adaptive
  85. algorithm.
  86. points : (sequence of floats,ints), optional
  87. A sequence of break points in the bounded integration interval
  88. where local difficulties of the integrand may occur (e.g.,
  89. singularities, discontinuities). The sequence does not have
  90. to be sorted. Note that this option cannot be used in conjunction
  91. with ``weight``.
  92. weight : float or int, optional
  93. String indicating weighting function. Full explanation for this
  94. and the remaining arguments can be found below.
  95. wvar : optional
  96. Variables for use with weighting functions.
  97. wopts : optional
  98. Optional input for reusing Chebyshev moments.
  99. maxp1 : float or int, optional
  100. An upper bound on the number of Chebyshev moments.
  101. limlst : int, optional
  102. Upper bound on the number of cycles (>=3) for use with a sinusoidal
  103. weighting and an infinite end-point.
  104. See Also
  105. --------
  106. dblquad : double integral
  107. tplquad : triple integral
  108. nquad : n-dimensional integrals (uses `quad` recursively)
  109. fixed_quad : fixed-order Gaussian quadrature
  110. simpson : integrator for sampled data
  111. romb : integrator for sampled data
  112. scipy.special : for coefficients and roots of orthogonal polynomials
  113. Notes
  114. -----
  115. For valid results, the integral must converge; behavior for divergent
  116. integrals is not guaranteed.
  117. **Extra information for quad() inputs and outputs**
  118. If full_output is non-zero, then the third output argument
  119. (infodict) is a dictionary with entries as tabulated below. For
  120. infinite limits, the range is transformed to (0,1) and the
  121. optional outputs are given with respect to this transformed range.
  122. Let M be the input argument limit and let K be infodict['last'].
  123. The entries are:
  124. 'neval'
  125. The number of function evaluations.
  126. 'last'
  127. The number, K, of subintervals produced in the subdivision process.
  128. 'alist'
  129. A rank-1 array of length M, the first K elements of which are the
  130. left end points of the subintervals in the partition of the
  131. integration range.
  132. 'blist'
  133. A rank-1 array of length M, the first K elements of which are the
  134. right end points of the subintervals.
  135. 'rlist'
  136. A rank-1 array of length M, the first K elements of which are the
  137. integral approximations on the subintervals.
  138. 'elist'
  139. A rank-1 array of length M, the first K elements of which are the
  140. moduli of the absolute error estimates on the subintervals.
  141. 'iord'
  142. A rank-1 integer array of length M, the first L elements of
  143. which are pointers to the error estimates over the subintervals
  144. with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
  145. sequence ``infodict['iord']`` and let E be the sequence
  146. ``infodict['elist']``. Then ``E[I[1]], ..., E[I[L]]`` forms a
  147. decreasing sequence.
  148. If the input argument points is provided (i.e., it is not None),
  149. the following additional outputs are placed in the output
  150. dictionary. Assume the points sequence is of length P.
  151. 'pts'
  152. A rank-1 array of length P+2 containing the integration limits
  153. and the break points of the intervals in ascending order.
  154. This is an array giving the subintervals over which integration
  155. will occur.
  156. 'level'
  157. A rank-1 integer array of length M (=limit), containing the
  158. subdivision levels of the subintervals, i.e., if (aa,bb) is a
  159. subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
  160. are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
  161. if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
  162. 'ndin'
  163. A rank-1 integer array of length P+2. After the first integration
  164. over the intervals (pts[1], pts[2]), the error estimates over some
  165. of the intervals may have been increased artificially in order to
  166. put their subdivision forward. This array has ones in slots
  167. corresponding to the subintervals for which this happens.
  168. **Weighting the integrand**
  169. The input variables, *weight* and *wvar*, are used to weight the
  170. integrand by a select list of functions. Different integration
  171. methods are used to compute the integral with these weighting
  172. functions, and these do not support specifying break points. The
  173. possible values of weight and the corresponding weighting functions are.
  174. ========== =================================== =====================
  175. ``weight`` Weight function used ``wvar``
  176. ========== =================================== =====================
  177. 'cos' cos(w*x) wvar = w
  178. 'sin' sin(w*x) wvar = w
  179. 'alg' g(x) = ((x-a)**alpha)*((b-x)**beta) wvar = (alpha, beta)
  180. 'alg-loga' g(x)*log(x-a) wvar = (alpha, beta)
  181. 'alg-logb' g(x)*log(b-x) wvar = (alpha, beta)
  182. 'alg-log' g(x)*log(x-a)*log(b-x) wvar = (alpha, beta)
  183. 'cauchy' 1/(x-c) wvar = c
  184. ========== =================================== =====================
  185. wvar holds the parameter w, (alpha, beta), or c depending on the weight
  186. selected. In these expressions, a and b are the integration limits.
  187. For the 'cos' and 'sin' weighting, additional inputs and outputs are
  188. available.
  189. For weighted integrals with finite integration limits, the integration
  190. is performed using a Clenshaw-Curtis method, which uses Chebyshev moments.
  191. For repeated calculations, these moments are saved in the output dictionary:
  192. 'momcom'
  193. The maximum level of Chebyshev moments that have been computed,
  194. i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
  195. computed for intervals of length ``|b-a| * 2**(-l)``,
  196. ``l=0,1,...,M_c``.
  197. 'nnlog'
  198. A rank-1 integer array of length M(=limit), containing the
  199. subdivision levels of the subintervals, i.e., an element of this
  200. array is equal to l if the corresponding subinterval is
  201. ``|b-a|* 2**(-l)``.
  202. 'chebmo'
  203. A rank-2 array of shape (25, maxp1) containing the computed
  204. Chebyshev moments. These can be passed on to an integration
  205. over the same interval by passing this array as the second
  206. element of the sequence wopts and passing infodict['momcom'] as
  207. the first element.
  208. If one of the integration limits is infinite, then a Fourier integral is
  209. computed (assuming w neq 0). If full_output is 1 and a numerical error
  210. is encountered, besides the error message attached to the output tuple,
  211. a dictionary is also appended to the output tuple which translates the
  212. error codes in the array ``info['ierlst']`` to English messages. The
  213. output information dictionary contains the following entries instead of
  214. 'last', 'alist', 'blist', 'rlist', and 'elist':
  215. 'lst'
  216. The number of subintervals needed for the integration (call it ``K_f``).
  217. 'rslst'
  218. A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
  219. contain the integral contribution over the interval
  220. ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
  221. and ``k=1,2,...,K_f``.
  222. 'erlst'
  223. A rank-1 array of length ``M_f`` containing the error estimate
  224. corresponding to the interval in the same position in
  225. ``infodict['rslist']``.
  226. 'ierlst'
  227. A rank-1 integer array of length ``M_f`` containing an error flag
  228. corresponding to the interval in the same position in
  229. ``infodict['rslist']``. See the explanation dictionary (last entry
  230. in the output tuple) for the meaning of the codes.
  231. **Details of QUADPACK level routines**
  232. `quad` calls routines from the FORTRAN library QUADPACK. This section
  233. provides details on the conditions for each routine to be called and a
  234. short description of each routine. The routine called depends on
  235. `weight`, `points` and the integration limits `a` and `b`.
  236. ================ ============== ========== =====================
  237. QUADPACK routine `weight` `points` infinite bounds
  238. ================ ============== ========== =====================
  239. qagse None No No
  240. qagie None No Yes
  241. qagpe None Yes No
  242. qawoe 'sin', 'cos' No No
  243. qawfe 'sin', 'cos' No either `a` or `b`
  244. qawse 'alg*' No No
  245. qawce 'cauchy' No No
  246. ================ ============== ========== =====================
  247. The following provides a short description from [1]_ for each
  248. routine.
  249. qagse
  250. is an integrator based on globally adaptive interval
  251. subdivision in connection with extrapolation, which will
  252. eliminate the effects of integrand singularities of
  253. several types. The integration is performed using a 21-point Gauss-Kronrod
  254. quadrature within each subinterval.
  255. qagie
  256. handles integration over infinite intervals. The infinite range is
  257. mapped onto a finite interval and subsequently the same strategy as
  258. in ``QAGS`` is applied.
  259. qagpe
  260. serves the same purposes as QAGS, but also allows the
  261. user to provide explicit information about the location
  262. and type of trouble-spots i.e. the abscissae of internal
  263. singularities, discontinuities and other difficulties of
  264. the integrand function.
  265. qawoe
  266. is an integrator for the evaluation of
  267. :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or
  268. :math:`\\int^b_a \\sin(\\omega x)f(x)dx`
  269. over a finite interval [a,b], where :math:`\\omega` and :math:`f`
  270. are specified by the user. The rule evaluation component is based
  271. on the modified Clenshaw-Curtis technique
  272. An adaptive subdivision scheme is used in connection
  273. with an extrapolation procedure, which is a modification
  274. of that in ``QAGS`` and allows the algorithm to deal with
  275. singularities in :math:`f(x)`.
  276. qawfe
  277. calculates the Fourier transform
  278. :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or
  279. :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`
  280. for user-provided :math:`\\omega` and :math:`f`. The procedure of
  281. ``QAWO`` is applied on successive finite intervals, and convergence
  282. acceleration by means of the :math:`\\varepsilon`-algorithm is applied
  283. to the series of integral approximations.
  284. qawse
  285. approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where
  286. :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with
  287. :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the
  288. following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,
  289. :math:`\\log(x-a)\\log(b-x)`.
  290. The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the
  291. function :math:`v`. A globally adaptive subdivision strategy is
  292. applied, with modified Clenshaw-Curtis integration on those
  293. subintervals which contain `a` or `b`.
  294. qawce
  295. compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be
  296. interpreted as a Cauchy principal value integral, for user specified
  297. :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
  298. Clenshaw-Curtis integration is used on those intervals containing the
  299. point :math:`x = c`.
  300. **Integration of Complex Function of a Real Variable**
  301. A complex valued function, :math:`f`, of a real variable can be written as
  302. :math:`f = g + ih`. Similarly, the integral of :math:`f` can be
  303. written as
  304. .. math::
  305. \\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx
  306. assuming that the integrals of :math:`g` and :math:`h` exist
  307. over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
  308. complex-valued functions by integrating the real and imaginary components
  309. separately.
  310. References
  311. ----------
  312. .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
  313. Überhuber, Christoph W.; Kahaner, David (1983).
  314. QUADPACK: A subroutine package for automatic integration.
  315. Springer-Verlag.
  316. ISBN 978-3-540-12553-2.
  317. .. [2] McCullough, Thomas; Phillips, Keith (1973).
  318. Foundations of Analysis in the Complex Plane.
  319. Holt Rinehart Winston.
  320. ISBN 0-03-086370-8
  321. Examples
  322. --------
  323. Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
  324. >>> from scipy import integrate
  325. >>> import numpy as np
  326. >>> x2 = lambda x: x**2
  327. >>> integrate.quad(x2, 0, 4)
  328. (21.333333333333332, 2.3684757858670003e-13)
  329. >>> print(4**3 / 3.) # analytical result
  330. 21.3333333333
  331. Calculate :math:`\\int^\\infty_0 e^{-x} dx`
  332. >>> invexp = lambda x: np.exp(-x)
  333. >>> integrate.quad(invexp, 0, np.inf)
  334. (1.0, 5.842605999138044e-11)
  335. Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`
  336. >>> f = lambda x, a: a*x
  337. >>> y, err = integrate.quad(f, 0, 1, args=(1,))
  338. >>> y
  339. 0.5
  340. >>> y, err = integrate.quad(f, 0, 1, args=(3,))
  341. >>> y
  342. 1.5
  343. Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
  344. y parameter as 1::
  345. testlib.c =>
  346. double func(int n, double args[n]){
  347. return args[0]*args[0] + args[1]*args[1];}
  348. compile to library testlib.*
  349. ::
  350. from scipy import integrate
  351. import ctypes
  352. lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
  353. lib.func.restype = ctypes.c_double
  354. lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
  355. integrate.quad(lib.func,0,1,(1))
  356. #(1.3333333333333333, 1.4802973661668752e-14)
  357. print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
  358. # 1.3333333333333333
  359. Be aware that pulse shapes and other sharp features as compared to the
  360. size of the integration interval may not be integrated correctly using
  361. this method. A simplified example of this limitation is integrating a
  362. y-axis reflected step function with many zero values within the integrals
  363. bounds.
  364. >>> y = lambda x: 1 if x<=0 else 0
  365. >>> integrate.quad(y, -1, 1)
  366. (1.0, 1.1102230246251565e-14)
  367. >>> integrate.quad(y, -1, 100)
  368. (1.0000000002199108, 1.0189464580163188e-08)
  369. >>> integrate.quad(y, -1, 10000)
  370. (0.0, 0.0)
  371. """
  372. if not isinstance(args, tuple):
  373. args = (args,)
  374. # Shortcut for empty interval, also works for improper integrals.
  375. if a == b:
  376. if full_output == 0:
  377. return (0., 0.)
  378. else:
  379. infodict = {"neval": 0, "last": 0,
  380. "alist": np.full(limit, np.nan, dtype=np.float64),
  381. "blist": np.full(limit, np.nan, dtype=np.float64),
  382. "rlist": np.zeros(limit, dtype=np.float64),
  383. "elist": np.zeros(limit, dtype=np.float64),
  384. "iord" : np.zeros(limit, dtype=np.int32)}
  385. if complex_func:
  386. return (0.+0.j, 0.+0.j, {"real": infodict, "imag": infodict})
  387. else:
  388. return (0., 0., infodict)
  389. # check the limits of integration: \int_a^b, expect a < b
  390. flip, a, b = b < a, min(a, b), max(a, b)
  391. if complex_func:
  392. def imfunc(x, *args):
  393. return func(x, *args).imag
  394. def refunc(x, *args):
  395. return func(x, *args).real
  396. re_retval = quad(refunc, a, b, args, full_output, epsabs,
  397. epsrel, limit, points, weight, wvar, wopts,
  398. maxp1, limlst, complex_func=False)
  399. im_retval = quad(imfunc, a, b, args, full_output, epsabs,
  400. epsrel, limit, points, weight, wvar, wopts,
  401. maxp1, limlst, complex_func=False)
  402. integral = re_retval[0] + 1j*im_retval[0]
  403. error_estimate = re_retval[1] + 1j*im_retval[1]
  404. retval = integral, error_estimate
  405. if full_output:
  406. msgexp = {}
  407. msgexp["real"] = re_retval[2:]
  408. msgexp["imag"] = im_retval[2:]
  409. retval = retval + (msgexp,)
  410. return retval
  411. if weight is None:
  412. retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
  413. points)
  414. else:
  415. if points is not None:
  416. msg = ("Break points cannot be specified when using weighted integrand.\n"
  417. "Continuing, ignoring specified points.")
  418. warnings.warn(msg, IntegrationWarning, stacklevel=2)
  419. retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
  420. limlst, limit, maxp1, weight, wvar, wopts)
  421. if flip:
  422. retval = (-retval[0],) + retval[1:]
  423. ier = retval[-1]
  424. if ier == 0:
  425. return retval[:-1]
  426. msgs = {80: "A Python error occurred possibly while calling the function.",
  427. 1: f"The maximum number of subdivisions ({limit}) has been achieved.\n "
  428. f"If increasing the limit yields no improvement it is advised to "
  429. f"analyze \n the integrand in order to determine the difficulties. "
  430. f"If the position of a \n local difficulty can be determined "
  431. f"(singularity, discontinuity) one will \n probably gain from "
  432. f"splitting up the interval and calling the integrator \n on the "
  433. f"subranges. Perhaps a special-purpose integrator should be used.",
  434. 2: "The occurrence of roundoff error is detected, which prevents \n "
  435. "the requested tolerance from being achieved. "
  436. "The error may be \n underestimated.",
  437. 3: "Extremely bad integrand behavior occurs at some points of the\n "
  438. "integration interval.",
  439. 4: "The algorithm does not converge. Roundoff error is detected\n "
  440. "in the extrapolation table. It is assumed that the requested "
  441. "tolerance\n cannot be achieved, and that the returned result "
  442. "(if full_output = 1) is \n the best which can be obtained.",
  443. 5: "The integral is probably divergent, or slowly convergent.",
  444. 6: "The input is invalid.",
  445. 7: "Abnormal termination of the routine. The estimates for result\n "
  446. "and error are less reliable. It is assumed that the requested "
  447. "accuracy\n has not been achieved.",
  448. 'unknown': "Unknown error."}
  449. if weight in ['cos','sin'] and (b == np.inf or a == -np.inf):
  450. msgs[1] = (
  451. "The maximum number of cycles allowed has been achieved., e.e.\n of "
  452. "subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n "
  453. "*pi/abs(omega), for k = 1, 2, ..., lst. "
  454. "One can allow more cycles by increasing the value of limlst. "
  455. "Look at info['ierlst'] with full_output=1."
  456. )
  457. msgs[4] = (
  458. "The extrapolation table constructed for convergence acceleration\n of "
  459. "the series formed by the integral contributions over the cycles, \n does "
  460. "not converge to within the requested accuracy. "
  461. "Look at \n info['ierlst'] with full_output=1."
  462. )
  463. msgs[7] = (
  464. "Bad integrand behavior occurs within one or more of the cycles.\n "
  465. "Location and type of the difficulty involved can be determined from \n "
  466. "the vector info['ierlist'] obtained with full_output=1."
  467. )
  468. explain = {1: "The maximum number of subdivisions (= limit) has been \n "
  469. "achieved on this cycle.",
  470. 2: "The occurrence of roundoff error is detected and prevents\n "
  471. "the tolerance imposed on this cycle from being achieved.",
  472. 3: "Extremely bad integrand behavior occurs at some points of\n "
  473. "this cycle.",
  474. 4: "The integral over this cycle does not converge (to within the "
  475. "required accuracy) due to roundoff in the extrapolation "
  476. "procedure invoked on this cycle. It is assumed that the result "
  477. "on this interval is the best which can be obtained.",
  478. 5: "The integral over this cycle is probably divergent or "
  479. "slowly convergent."}
  480. try:
  481. msg = msgs[ier]
  482. except KeyError:
  483. msg = msgs['unknown']
  484. if ier in [1,2,3,4,5,7]:
  485. if full_output:
  486. if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf):
  487. return retval[:-1] + (msg, explain)
  488. else:
  489. return retval[:-1] + (msg,)
  490. else:
  491. warnings.warn(msg, IntegrationWarning, stacklevel=2)
  492. return retval[:-1]
  493. elif ier == 6: # Forensic decision tree when QUADPACK throws ier=6
  494. if epsabs <= 0: # Small error tolerance - applies to all methods
  495. if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
  496. msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both"
  497. " 5e-29 and 50*(machine epsilon).")
  498. elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf):
  499. msg = ("Sine or cosine weighted integrals with infinite domain"
  500. " must have 'epsabs'>0.")
  501. elif weight is None:
  502. if points is None: # QAGSE/QAGIE
  503. msg = ("Invalid 'limit' argument. There must be"
  504. " at least one subinterval")
  505. else: # QAGPE
  506. if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
  507. msg = ("All break points in 'points' must lie within the"
  508. " integration limits.")
  509. elif len(points) >= limit:
  510. msg = (f"Number of break points ({len(points):d}) "
  511. f"must be less than subinterval limit ({limit:d})")
  512. else:
  513. if maxp1 < 1:
  514. msg = "Chebyshev moment limit maxp1 must be >=1."
  515. elif weight in ('cos', 'sin') and abs(a+b) == np.inf: # QAWFE
  516. msg = "Cycle limit limlst must be >=3."
  517. elif weight.startswith('alg'): # QAWSE
  518. if min(wvar) < -1:
  519. msg = "wvar parameters (alpha, beta) must both be >= -1."
  520. if b < a:
  521. msg = "Integration limits a, b must satistfy a<b."
  522. elif weight == 'cauchy' and wvar in (a, b):
  523. msg = ("Parameter 'wvar' must not equal"
  524. " integration limits 'a' or 'b'.")
  525. raise ValueError(msg)
  526. def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points):
  527. infbounds = 0
  528. if (b != np.inf and a != -np.inf):
  529. pass # standard integration
  530. elif (b == np.inf and a != -np.inf):
  531. infbounds = 1
  532. bound = a
  533. elif (b == np.inf and a == -np.inf):
  534. infbounds = 2
  535. bound = 0 # ignored
  536. elif (b != np.inf and a == -np.inf):
  537. infbounds = -1
  538. bound = b
  539. else:
  540. raise RuntimeError("Infinity comparisons don't work for you.")
  541. if points is None:
  542. if infbounds == 0:
  543. return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
  544. else:
  545. return _quadpack._qagie(func, bound, infbounds, args, full_output,
  546. epsabs, epsrel, limit)
  547. else:
  548. if infbounds != 0:
  549. raise ValueError("Infinity inputs cannot be used with break points.")
  550. else:
  551. #Duplicates force function evaluation at singular points
  552. the_points = np.unique(points)
  553. the_points = the_points[a < the_points]
  554. the_points = the_points[the_points < b]
  555. the_points = np.concatenate((the_points, (0., 0.)))
  556. return _quadpack._qagpe(func, a, b, the_points, args, full_output,
  557. epsabs, epsrel, limit)
  558. def _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
  559. limlst, limit, maxp1,weight, wvar, wopts):
  560. if weight not in ['cos','sin','alg','alg-loga','alg-logb','alg-log','cauchy']:
  561. raise ValueError(f"{weight} not a recognized weighting function.")
  562. strdict = {'cos':1,'sin':2,'alg':1,'alg-loga':2,'alg-logb':3,'alg-log':4}
  563. if weight in ['cos','sin']:
  564. integr = strdict[weight]
  565. if (b != np.inf and a != -np.inf): # finite limits
  566. if wopts is None: # no precomputed Chebyshev moments
  567. return _quadpack._qawoe(func, a, b, wvar, integr, args, full_output,
  568. epsabs, epsrel, limit, maxp1,1)
  569. else: # precomputed Chebyshev moments
  570. momcom = wopts[0]
  571. chebcom = wopts[1]
  572. return _quadpack._qawoe(func, a, b, wvar, integr, args,
  573. full_output,epsabs, epsrel, limit, maxp1, 2,
  574. momcom, chebcom)
  575. elif (b == np.inf and a != -np.inf):
  576. return _quadpack._qawfe(func, a, wvar, integr, args, full_output,
  577. epsabs, limlst, limit, maxp1)
  578. elif (b != np.inf and a == -np.inf): # remap function and interval
  579. if weight == 'cos':
  580. def thefunc(x,*myargs):
  581. y = -x
  582. func = myargs[0]
  583. myargs = (y,) + myargs[1:]
  584. return func(*myargs)
  585. else:
  586. def thefunc(x,*myargs):
  587. y = -x
  588. func = myargs[0]
  589. myargs = (y,) + myargs[1:]
  590. return -func(*myargs)
  591. args = (func,) + args
  592. return _quadpack._qawfe(thefunc, -b, wvar, integr, args,
  593. full_output, epsabs, limlst, limit, maxp1)
  594. else:
  595. raise ValueError("Cannot integrate with this weight from -Inf to +Inf.")
  596. else:
  597. if a in [-np.inf, np.inf] or b in [-np.inf, np.inf]:
  598. message = "Cannot integrate with this weight over an infinite interval."
  599. raise ValueError(message)
  600. if weight.startswith('alg'):
  601. integr = strdict[weight]
  602. return _quadpack._qawse(func, a, b, wvar, integr, args,
  603. full_output, epsabs, epsrel, limit)
  604. else: # weight == 'cauchy'
  605. return _quadpack._qawce(func, a, b, wvar, args, full_output,
  606. epsabs, epsrel, limit)
  607. @xp_capabilities(np_only=True)
  608. def dblquad(func, a, b, gfun, hfun, args=(), epsabs=1.49e-8, epsrel=1.49e-8):
  609. """
  610. Compute a double integral.
  611. Return the double (definite) integral of ``func(y, x)`` from ``x = a..b``
  612. and ``y = gfun(x)..hfun(x)``.
  613. Parameters
  614. ----------
  615. func : callable
  616. A Python function or method of at least two variables: y must be the
  617. first argument and x the second argument.
  618. a, b : float
  619. The limits of integration in x: `a` < `b`
  620. gfun : callable or float
  621. The lower boundary curve in y which is a function taking a single
  622. floating point argument (x) and returning a floating point result
  623. or a float indicating a constant boundary curve.
  624. hfun : callable or float
  625. The upper boundary curve in y (same requirements as `gfun`).
  626. args : sequence, optional
  627. Extra arguments to pass to `func`.
  628. epsabs : float, optional
  629. Absolute tolerance passed directly to the inner 1-D quadrature
  630. integration. Default is 1.49e-8. ``dblquad`` tries to obtain
  631. an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
  632. where ``i`` = inner integral of ``func(y, x)`` from ``gfun(x)``
  633. to ``hfun(x)``, and ``result`` is the numerical approximation.
  634. See `epsrel` below.
  635. epsrel : float, optional
  636. Relative tolerance of the inner 1-D integrals. Default is 1.49e-8.
  637. If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
  638. and ``50 * (machine epsilon)``. See `epsabs` above.
  639. Returns
  640. -------
  641. y : float
  642. The resultant integral.
  643. abserr : float
  644. An estimate of the error.
  645. See Also
  646. --------
  647. quad : single integral
  648. tplquad : triple integral
  649. nquad : N-dimensional integrals
  650. fixed_quad : fixed-order Gaussian quadrature
  651. simpson : integrator for sampled data
  652. romb : integrator for sampled data
  653. scipy.special : for coefficients and roots of orthogonal polynomials
  654. Notes
  655. -----
  656. For valid results, the integral must converge; behavior for divergent
  657. integrals is not guaranteed.
  658. **Details of QUADPACK level routines**
  659. `quad` calls routines from the FORTRAN library QUADPACK. This section
  660. provides details on the conditions for each routine to be called and a
  661. short description of each routine. For each level of integration, ``qagse``
  662. is used for finite limits or ``qagie`` is used if either limit (or both!)
  663. are infinite. The following provides a short description from [1]_ for each
  664. routine.
  665. qagse
  666. is an integrator based on globally adaptive interval
  667. subdivision in connection with extrapolation, which will
  668. eliminate the effects of integrand singularities of
  669. several types. The integration is is performed using a 21-point Gauss-Kronrod
  670. quadrature within each subinterval.
  671. qagie
  672. handles integration over infinite intervals. The infinite range is
  673. mapped onto a finite interval and subsequently the same strategy as
  674. in ``QAGS`` is applied.
  675. References
  676. ----------
  677. .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
  678. Überhuber, Christoph W.; Kahaner, David (1983).
  679. QUADPACK: A subroutine package for automatic integration.
  680. Springer-Verlag.
  681. ISBN 978-3-540-12553-2.
  682. Examples
  683. --------
  684. Compute the double integral of ``x * y**2`` over the box
  685. ``x`` ranging from 0 to 2 and ``y`` ranging from 0 to 1.
  686. That is, :math:`\\int^{x=2}_{x=0} \\int^{y=1}_{y=0} x y^2 \\,dy \\,dx`.
  687. >>> import numpy as np
  688. >>> from scipy import integrate
  689. >>> f = lambda y, x: x*y**2
  690. >>> integrate.dblquad(f, 0, 2, 0, 1)
  691. (0.6666666666666667, 7.401486830834377e-15)
  692. Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1
  693. \\,dy \\,dx`.
  694. >>> f = lambda y, x: 1
  695. >>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos)
  696. (0.41421356237309503, 1.1083280054755938e-14)
  697. Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx`
  698. for :math:`a=1, 3`.
  699. >>> f = lambda y, x, a: a*x*y
  700. >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,))
  701. (0.33333333333333337, 5.551115123125783e-15)
  702. >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,))
  703. (0.9999999999999999, 1.6653345369377348e-14)
  704. Compute the two-dimensional Gaussian Integral, which is the integral of the
  705. Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over
  706. :math:`(-\\infty,+\\infty)`. That is, compute the integral
  707. :math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`.
  708. >>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2))
  709. >>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)
  710. (3.141592653589777, 2.5173086737433208e-08)
  711. """
  712. def temp_ranges(*args):
  713. return [gfun(args[0]) if callable(gfun) else gfun,
  714. hfun(args[0]) if callable(hfun) else hfun]
  715. return nquad(func, [temp_ranges, [a, b]], args=args,
  716. opts={"epsabs": epsabs, "epsrel": epsrel})
  717. @xp_capabilities(np_only=True)
  718. def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
  719. epsrel=1.49e-8):
  720. """
  721. Compute a triple (definite) integral.
  722. Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
  723. ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
  724. Parameters
  725. ----------
  726. func : function
  727. A Python function or method of at least three variables in the
  728. order (z, y, x).
  729. a, b : float
  730. The limits of integration in x: `a` < `b`
  731. gfun : function or float
  732. The lower boundary curve in y which is a function taking a single
  733. floating point argument (x) and returning a floating point result
  734. or a float indicating a constant boundary curve.
  735. hfun : function or float
  736. The upper boundary curve in y (same requirements as `gfun`).
  737. qfun : function or float
  738. The lower boundary surface in z. It must be a function that takes
  739. two floats in the order (x, y) and returns a float or a float
  740. indicating a constant boundary surface.
  741. rfun : function or float
  742. The upper boundary surface in z. (Same requirements as `qfun`.)
  743. args : tuple, optional
  744. Extra arguments to pass to `func`.
  745. epsabs : float, optional
  746. Absolute tolerance passed directly to the innermost 1-D quadrature
  747. integration. Default is 1.49e-8.
  748. epsrel : float, optional
  749. Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
  750. Returns
  751. -------
  752. y : float
  753. The resultant integral.
  754. abserr : float
  755. An estimate of the error.
  756. See Also
  757. --------
  758. quad : Adaptive quadrature using QUADPACK
  759. fixed_quad : Fixed-order Gaussian quadrature
  760. dblquad : Double integrals
  761. nquad : N-dimensional integrals
  762. romb : Integrators for sampled data
  763. simpson : Integrators for sampled data
  764. scipy.special : For coefficients and roots of orthogonal polynomials
  765. Notes
  766. -----
  767. For valid results, the integral must converge; behavior for divergent
  768. integrals is not guaranteed.
  769. **Details of QUADPACK level routines**
  770. `quad` calls routines from the FORTRAN library QUADPACK. This section
  771. provides details on the conditions for each routine to be called and a
  772. short description of each routine. For each level of integration, ``qagse``
  773. is used for finite limits or ``qagie`` is used, if either limit (or both!)
  774. are infinite. The following provides a short description from [1]_ for each
  775. routine.
  776. qagse
  777. is an integrator based on globally adaptive interval
  778. subdivision in connection with extrapolation, which will
  779. eliminate the effects of integrand singularities of
  780. several types. The integration is is performed using a 21-point Gauss-Kronrod
  781. quadrature within each subinterval.
  782. qagie
  783. handles integration over infinite intervals. The infinite range is
  784. mapped onto a finite interval and subsequently the same strategy as
  785. in ``QAGS`` is applied.
  786. References
  787. ----------
  788. .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
  789. Überhuber, Christoph W.; Kahaner, David (1983).
  790. QUADPACK: A subroutine package for automatic integration.
  791. Springer-Verlag.
  792. ISBN 978-3-540-12553-2.
  793. Examples
  794. --------
  795. Compute the triple integral of ``x * y * z``, over ``x`` ranging
  796. from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
  797. That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z
  798. \\,dz \\,dy \\,dx`.
  799. >>> import numpy as np
  800. >>> from scipy import integrate
  801. >>> f = lambda z, y, x: x*y*z
  802. >>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1)
  803. (1.8749999999999998, 3.3246447942574074e-14)
  804. Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0}
  805. \\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`.
  806. Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f``
  807. takes arguments in the order (z, y, x).
  808. >>> f = lambda z, y, x: x*y*z
  809. >>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y)
  810. (0.05416666666666668, 2.1774196738157757e-14)
  811. Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0}
  812. a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`.
  813. >>> f = lambda z, y, x, a: a*x*y*z
  814. >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,))
  815. (0.125, 5.527033708952211e-15)
  816. >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,))
  817. (0.375, 1.6581101126856635e-14)
  818. Compute the three-dimensional Gaussian Integral, which is the integral of
  819. the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over
  820. :math:`(-\\infty,+\\infty)`. That is, compute the integral
  821. :math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz
  822. \\,dy\\,dx`.
  823. >>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2))
  824. >>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf)
  825. (5.568327996830833, 4.4619078828029765e-08)
  826. """
  827. # f(z, y, x)
  828. # qfun/rfun(x, y)
  829. # gfun/hfun(x)
  830. # nquad will hand (y, x, t0, ...) to ranges0
  831. # nquad will hand (x, t0, ...) to ranges1
  832. # Only qfun / rfun is different API...
  833. def ranges0(*args):
  834. return [qfun(args[1], args[0]) if callable(qfun) else qfun,
  835. rfun(args[1], args[0]) if callable(rfun) else rfun]
  836. def ranges1(*args):
  837. return [gfun(args[0]) if callable(gfun) else gfun,
  838. hfun(args[0]) if callable(hfun) else hfun]
  839. ranges = [ranges0, ranges1, [a, b]]
  840. return nquad(func, ranges, args=args,
  841. opts={"epsabs": epsabs, "epsrel": epsrel})
  842. @xp_capabilities(np_only=True)
  843. def nquad(func, ranges, args=None, opts=None, full_output=False):
  844. r"""
  845. Integration over multiple variables.
  846. Wraps `quad` to enable integration over multiple variables.
  847. Various options allow improved integration of discontinuous functions, as
  848. well as the use of weighted integration, and generally finer control of the
  849. integration process.
  850. Parameters
  851. ----------
  852. func : {callable, scipy.LowLevelCallable}
  853. The function to be integrated. Has arguments of ``x0, ..., xn``,
  854. ``t0, ..., tm``, where integration is carried out over ``x0, ..., xn``,
  855. which must be floats. Where ``t0, ..., tm`` are extra arguments
  856. passed in args.
  857. Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.
  858. Integration is carried out in order. That is, integration over ``x0``
  859. is the innermost integral, and ``xn`` is the outermost.
  860. If the user desires improved integration performance, then `f` may
  861. be a `scipy.LowLevelCallable` with one of the signatures::
  862. double func(int n, double *xx)
  863. double func(int n, double *xx, void *user_data)
  864. where ``n`` is the number of variables and args. The ``xx`` array
  865. contains the coordinates and extra arguments. ``user_data`` is the data
  866. contained in the `scipy.LowLevelCallable`.
  867. ranges : iterable object
  868. Each element of ranges may be either a sequence of 2 numbers, or else
  869. a callable that returns such a sequence. ``ranges[0]`` corresponds to
  870. integration over x0, and so on. If an element of ranges is a callable,
  871. then it will be called with all of the integration arguments available,
  872. as well as any parametric arguments. e.g., if
  873. ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
  874. either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
  875. args : iterable object, optional
  876. Additional arguments ``t0, ..., tn``, required by ``func``, ``ranges``,
  877. and ``opts``.
  878. opts : iterable object or dict, optional
  879. Options to be passed to `quad`. May be empty, a dict, or
  880. a sequence of dicts or functions that return a dict. If empty, the
  881. default options from scipy.integrate.quad are used. If a dict, the same
  882. options are used for all levels of integraion. If a sequence, then each
  883. element of the sequence corresponds to a particular integration. e.g.,
  884. ``opts[0]`` corresponds to integration over ``x0``, and so on. If a
  885. callable, the signature must be the same as for ``ranges``. The
  886. available options together with their default values are:
  887. - epsabs = 1.49e-08
  888. - epsrel = 1.49e-08
  889. - limit = 50
  890. - points = None
  891. - weight = None
  892. - wvar = None
  893. - wopts = None
  894. For more information on these options, see `quad`.
  895. full_output : bool, optional
  896. Partial implementation of ``full_output`` from scipy.integrate.quad.
  897. The number of integrand function evaluations ``neval`` can be obtained
  898. by setting ``full_output=True`` when calling nquad.
  899. Returns
  900. -------
  901. result : float
  902. The result of the integration.
  903. abserr : float
  904. The maximum of the estimates of the absolute error in the various
  905. integration results.
  906. out_dict : dict, optional
  907. A dict containing additional information on the integration.
  908. See Also
  909. --------
  910. quad : 1-D numerical integration
  911. dblquad, tplquad : double and triple integrals
  912. fixed_quad : fixed-order Gaussian quadrature
  913. Notes
  914. -----
  915. For valid results, the integral must converge; behavior for divergent
  916. integrals is not guaranteed.
  917. **Details of QUADPACK level routines**
  918. `nquad` calls routines from the FORTRAN library QUADPACK. This section
  919. provides details on the conditions for each routine to be called and a
  920. short description of each routine. The routine called depends on
  921. `weight`, `points` and the integration limits `a` and `b`.
  922. ================ ============== ========== =====================
  923. QUADPACK routine `weight` `points` infinite bounds
  924. ================ ============== ========== =====================
  925. qagse None No No
  926. qagie None No Yes
  927. qagpe None Yes No
  928. qawoe 'sin', 'cos' No No
  929. qawfe 'sin', 'cos' No either `a` or `b`
  930. qawse 'alg*' No No
  931. qawce 'cauchy' No No
  932. ================ ============== ========== =====================
  933. The following provides a short description from [1]_ for each
  934. routine.
  935. qagse
  936. is an integrator based on globally adaptive interval
  937. subdivision in connection with extrapolation, which will
  938. eliminate the effects of integrand singularities of
  939. several types. The integration is is performed using a 21-point Gauss-Kronrod
  940. quadrature within each subinterval.
  941. qagie
  942. handles integration over infinite intervals. The infinite range is
  943. mapped onto a finite interval and subsequently the same strategy as
  944. in ``QAGS`` is applied.
  945. qagpe
  946. serves the same purposes as QAGS, but also allows the
  947. user to provide explicit information about the location
  948. and type of trouble-spots i.e. the abscissae of internal
  949. singularities, discontinuities and other difficulties of
  950. the integrand function.
  951. qawoe
  952. is an integrator for the evaluation of
  953. :math:`\int^b_a \cos(\omega x)f(x)dx` or
  954. :math:`\int^b_a \sin(\omega x)f(x)dx`
  955. over a finite interval [a,b], where :math:`\omega` and :math:`f`
  956. are specified by the user. The rule evaluation component is based
  957. on the modified Clenshaw-Curtis technique
  958. An adaptive subdivision scheme is used in connection
  959. with an extrapolation procedure, which is a modification
  960. of that in ``QAGS`` and allows the algorithm to deal with
  961. singularities in :math:`f(x)`.
  962. qawfe
  963. calculates the Fourier transform
  964. :math:`\int^\infty_a \cos(\omega x)f(x)dx` or
  965. :math:`\int^\infty_a \sin(\omega x)f(x)dx`
  966. for user-provided :math:`\omega` and :math:`f`. The procedure of
  967. ``QAWO`` is applied on successive finite intervals, and convergence
  968. acceleration by means of the :math:`\varepsilon`-algorithm is applied
  969. to the series of integral approximations.
  970. qawse
  971. approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
  972. :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
  973. :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
  974. following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
  975. :math:`\log(x-a)\log(b-x)`.
  976. The user specifies :math:`\alpha`, :math:`\beta` and the type of the
  977. function :math:`v`. A globally adaptive subdivision strategy is
  978. applied, with modified Clenshaw-Curtis integration on those
  979. subintervals which contain `a` or `b`.
  980. qawce
  981. compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
  982. interpreted as a Cauchy principal value integral, for user specified
  983. :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
  984. Clenshaw-Curtis integration is used on those intervals containing the
  985. point :math:`x = c`.
  986. References
  987. ----------
  988. .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
  989. Überhuber, Christoph W.; Kahaner, David (1983).
  990. QUADPACK: A subroutine package for automatic integration.
  991. Springer-Verlag.
  992. ISBN 978-3-540-12553-2.
  993. Examples
  994. --------
  995. Calculate
  996. .. math::
  997. \int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0}
  998. f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 ,
  999. where
  1000. .. math::
  1001. f(x_0, x_1, x_2, x_3) = \begin{cases}
  1002. x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\
  1003. x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0)
  1004. \end{cases} .
  1005. >>> import numpy as np
  1006. >>> from scipy import integrate
  1007. >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
  1008. ... 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
  1009. >>> def opts0(*args, **kwargs):
  1010. ... return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
  1011. >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
  1012. ... opts=[opts0,{},{},{}], full_output=True)
  1013. (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
  1014. Calculate
  1015. .. math::
  1016. \int^{t_0+t_1+1}_{t_0+t_1-1}
  1017. \int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1}
  1018. \int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1}
  1019. f(x_0,x_1, x_2,t_0,t_1)
  1020. \,dx_0 \,dx_1 \,dx_2,
  1021. where
  1022. .. math::
  1023. f(x_0, x_1, x_2, t_0, t_1) = \begin{cases}
  1024. x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\
  1025. x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0)
  1026. \end{cases}
  1027. and :math:`(t_0, t_1) = (0, 1)` .
  1028. >>> def func2(x0, x1, x2, t0, t1):
  1029. ... return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0)
  1030. >>> def lim0(x1, x2, t0, t1):
  1031. ... return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1]
  1032. >>> def lim1(x2, t0, t1):
  1033. ... return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1]
  1034. >>> def lim2(t0, t1):
  1035. ... return [t0 + t1 - 1, t0 + t1 + 1]
  1036. >>> def opts0(x1, x2, t0, t1):
  1037. ... return {'points' : [t0 - t1*x1]}
  1038. >>> def opts1(x2, t0, t1):
  1039. ... return {}
  1040. >>> def opts2(t0, t1):
  1041. ... return {}
  1042. >>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1),
  1043. ... opts=[opts0, opts1, opts2])
  1044. (36.099919226771625, 1.8546948553373528e-07)
  1045. """
  1046. depth = len(ranges)
  1047. ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
  1048. if args is None:
  1049. args = ()
  1050. if opts is None:
  1051. opts = [dict([])] * depth
  1052. if isinstance(opts, dict):
  1053. opts = [_OptFunc(opts)] * depth
  1054. else:
  1055. opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
  1056. return _NQuad(func, ranges, opts, full_output).integrate(*args)
  1057. class _RangeFunc:
  1058. def __init__(self, range_):
  1059. self.range_ = range_
  1060. def __call__(self, *args):
  1061. """Return stored value.
  1062. *args needed because range_ can be float or func, and is called with
  1063. variable number of parameters.
  1064. """
  1065. return self.range_
  1066. class _OptFunc:
  1067. def __init__(self, opt):
  1068. self.opt = opt
  1069. def __call__(self, *args):
  1070. """Return stored dict."""
  1071. return self.opt
  1072. class _NQuad:
  1073. def __init__(self, func, ranges, opts, full_output):
  1074. self.abserr = 0
  1075. self.func = func
  1076. self.ranges = ranges
  1077. self.opts = opts
  1078. self.maxdepth = len(ranges)
  1079. self.full_output = full_output
  1080. if self.full_output:
  1081. self.out_dict = {'neval': 0}
  1082. def integrate(self, *args, **kwargs):
  1083. depth = kwargs.pop('depth', 0)
  1084. if kwargs:
  1085. raise ValueError('unexpected kwargs')
  1086. # Get the integration range and options for this depth.
  1087. ind = -(depth + 1)
  1088. fn_range = self.ranges[ind]
  1089. low, high = fn_range(*args)
  1090. fn_opt = self.opts[ind]
  1091. opt = dict(fn_opt(*args))
  1092. if 'points' in opt:
  1093. opt['points'] = [x for x in opt['points'] if low <= x <= high]
  1094. if depth + 1 == self.maxdepth:
  1095. f = self.func
  1096. else:
  1097. f = partial(self.integrate, depth=depth+1)
  1098. quad_r = quad(f, low, high, args=args, full_output=self.full_output,
  1099. **opt)
  1100. value = quad_r[0]
  1101. abserr = quad_r[1]
  1102. if self.full_output:
  1103. infodict = quad_r[2]
  1104. # The 'neval' parameter in full_output returns the total
  1105. # number of times the integrand function was evaluated.
  1106. # Therefore, only the innermost integration loop counts.
  1107. if depth + 1 == self.maxdepth:
  1108. self.out_dict['neval'] += infodict['neval']
  1109. self.abserr = max(self.abserr, abserr)
  1110. if depth > 0:
  1111. return value
  1112. else:
  1113. # Final result of N-D integration with error
  1114. if self.full_output:
  1115. return value, self.abserr, self.out_dict
  1116. else:
  1117. return value, self.abserr