_quadpack_py.py 51 KB

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