quadpack.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. # Author: Travis Oliphant 2001
  2. # Author: Nathan Woods 2013 (nquad &c)
  3. from __future__ import division, print_function, absolute_import
  4. import sys
  5. import warnings
  6. from functools import partial
  7. from . import _quadpack
  8. import numpy
  9. from numpy import Inf
  10. __all__ = ['quad', 'dblquad', 'tplquad', 'nquad', 'quad_explain',
  11. 'IntegrationWarning']
  12. error = _quadpack.error
  13. class IntegrationWarning(UserWarning):
  14. """
  15. Warning on issues during integration.
  16. """
  17. pass
  18. def quad_explain(output=sys.stdout):
  19. """
  20. Print extra information about integrate.quad() parameters and returns.
  21. Parameters
  22. ----------
  23. output : instance with "write" method, optional
  24. Information about `quad` is passed to ``output.write()``.
  25. Default is ``sys.stdout``.
  26. Returns
  27. -------
  28. None
  29. """
  30. output.write(quad.__doc__)
  31. def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
  32. limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
  33. limlst=50):
  34. """
  35. Compute a definite integral.
  36. Integrate func from `a` to `b` (possibly infinite interval) using a
  37. technique from the Fortran library QUADPACK.
  38. Parameters
  39. ----------
  40. func : {function, scipy.LowLevelCallable}
  41. A Python function or method to integrate. If `func` takes many
  42. arguments, it is integrated along the axis corresponding to the
  43. first argument.
  44. If the user desires improved integration performance, then `f` may
  45. be a `scipy.LowLevelCallable` with one of the signatures::
  46. double func(double x)
  47. double func(double x, void *user_data)
  48. double func(int n, double *xx)
  49. double func(int n, double *xx, void *user_data)
  50. The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
  51. In the call forms with ``xx``, ``n`` is the length of the ``xx``
  52. array which contains ``xx[0] == x`` and the rest of the items are
  53. numbers contained in the ``args`` argument of quad.
  54. In addition, certain ctypes call signatures are supported for
  55. backward compatibility, but those should not be used in new code.
  56. a : float
  57. Lower limit of integration (use -numpy.inf for -infinity).
  58. b : float
  59. Upper limit of integration (use numpy.inf for +infinity).
  60. args : tuple, optional
  61. Extra arguments to pass to `func`.
  62. full_output : int, optional
  63. Non-zero to return a dictionary of integration information.
  64. If non-zero, warning messages are also suppressed and the
  65. message is appended to the output tuple.
  66. Returns
  67. -------
  68. y : float
  69. The integral of func from `a` to `b`.
  70. abserr : float
  71. An estimate of the absolute error in the result.
  72. infodict : dict
  73. A dictionary containing additional information.
  74. Run scipy.integrate.quad_explain() for more information.
  75. message
  76. A convergence message.
  77. explain
  78. Appended only with 'cos' or 'sin' weighting and infinite
  79. integration limits, it contains an explanation of the codes in
  80. infodict['ierlst']
  81. Other Parameters
  82. ----------------
  83. epsabs : float or int, optional
  84. Absolute error tolerance.
  85. epsrel : float or int, optional
  86. Relative error tolerance.
  87. limit : float or int, optional
  88. An upper bound on the number of subintervals used in the adaptive
  89. algorithm.
  90. points : (sequence of floats,ints), optional
  91. A sequence of break points in the bounded integration interval
  92. where local difficulties of the integrand may occur (e.g.,
  93. singularities, discontinuities). The sequence does not have
  94. to be sorted.
  95. weight : float or int, optional
  96. String indicating weighting function. Full explanation for this
  97. and the remaining arguments can be found below.
  98. wvar : optional
  99. Variables for use with weighting functions.
  100. wopts : optional
  101. Optional input for reusing Chebyshev moments.
  102. maxp1 : float or int, optional
  103. An upper bound on the number of Chebyshev moments.
  104. limlst : int, optional
  105. Upper bound on the number of cycles (>=3) for use with a sinusoidal
  106. weighting and an infinite end-point.
  107. See Also
  108. --------
  109. dblquad : double integral
  110. tplquad : triple integral
  111. nquad : n-dimensional integrals (uses `quad` recursively)
  112. fixed_quad : fixed-order Gaussian quadrature
  113. quadrature : adaptive Gaussian quadrature
  114. odeint : ODE integrator
  115. ode : ODE integrator
  116. simps : integrator for sampled data
  117. romb : integrator for sampled data
  118. scipy.special : for coefficients and roots of orthogonal polynomials
  119. Notes
  120. -----
  121. **Extra information for quad() inputs and outputs**
  122. If full_output is non-zero, then the third output argument
  123. (infodict) is a dictionary with entries as tabulated below. For
  124. infinite limits, the range is transformed to (0,1) and the
  125. optional outputs are given with respect to this transformed range.
  126. Let M be the input argument limit and let K be infodict['last'].
  127. The entries are:
  128. 'neval'
  129. The number of function evaluations.
  130. 'last'
  131. The number, K, of subintervals produced in the subdivision process.
  132. 'alist'
  133. A rank-1 array of length M, the first K elements of which are the
  134. left end points of the subintervals in the partition of the
  135. integration range.
  136. 'blist'
  137. A rank-1 array of length M, the first K elements of which are the
  138. right end points of the subintervals.
  139. 'rlist'
  140. A rank-1 array of length M, the first K elements of which are the
  141. integral approximations on the subintervals.
  142. 'elist'
  143. A rank-1 array of length M, the first K elements of which are the
  144. moduli of the absolute error estimates on the subintervals.
  145. 'iord'
  146. A rank-1 integer array of length M, the first L elements of
  147. which are pointers to the error estimates over the subintervals
  148. with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
  149. sequence ``infodict['iord']`` and let E be the sequence
  150. ``infodict['elist']``. Then ``E[I[1]], ..., E[I[L]]`` forms a
  151. decreasing sequence.
  152. If the input argument points is provided (i.e. it is not None),
  153. the following additional outputs are placed in the output
  154. dictionary. Assume the points sequence is of length P.
  155. 'pts'
  156. A rank-1 array of length P+2 containing the integration limits
  157. and the break points of the intervals in ascending order.
  158. This is an array giving the subintervals over which integration
  159. will occur.
  160. 'level'
  161. A rank-1 integer array of length M (=limit), containing the
  162. subdivision levels of the subintervals, i.e., if (aa,bb) is a
  163. subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
  164. are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
  165. if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
  166. 'ndin'
  167. A rank-1 integer array of length P+2. After the first integration
  168. over the intervals (pts[1], pts[2]), the error estimates over some
  169. of the intervals may have been increased artificially in order to
  170. put their subdivision forward. This array has ones in slots
  171. corresponding to the subintervals for which this happens.
  172. **Weighting the integrand**
  173. The input variables, *weight* and *wvar*, are used to weight the
  174. integrand by a select list of functions. Different integration
  175. methods are used to compute the integral with these weighting
  176. functions. The possible values of weight and the corresponding
  177. weighting functions are.
  178. ========== =================================== =====================
  179. ``weight`` Weight function used ``wvar``
  180. ========== =================================== =====================
  181. 'cos' cos(w*x) wvar = w
  182. 'sin' sin(w*x) wvar = w
  183. 'alg' g(x) = ((x-a)**alpha)*((b-x)**beta) wvar = (alpha, beta)
  184. 'alg-loga' g(x)*log(x-a) wvar = (alpha, beta)
  185. 'alg-logb' g(x)*log(b-x) wvar = (alpha, beta)
  186. 'alg-log' g(x)*log(x-a)*log(b-x) wvar = (alpha, beta)
  187. 'cauchy' 1/(x-c) wvar = c
  188. ========== =================================== =====================
  189. wvar holds the parameter w, (alpha, beta), or c depending on the weight
  190. selected. In these expressions, a and b are the integration limits.
  191. For the 'cos' and 'sin' weighting, additional inputs and outputs are
  192. available.
  193. For finite integration limits, the integration is performed using a
  194. Clenshaw-Curtis method which uses Chebyshev moments. For repeated
  195. calculations, these moments are saved in the output dictionary:
  196. 'momcom'
  197. The maximum level of Chebyshev moments that have been computed,
  198. i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
  199. computed for intervals of length ``|b-a| * 2**(-l)``,
  200. ``l=0,1,...,M_c``.
  201. 'nnlog'
  202. A rank-1 integer array of length M(=limit), containing the
  203. subdivision levels of the subintervals, i.e., an element of this
  204. array is equal to l if the corresponding subinterval is
  205. ``|b-a|* 2**(-l)``.
  206. 'chebmo'
  207. A rank-2 array of shape (25, maxp1) containing the computed
  208. Chebyshev moments. These can be passed on to an integration
  209. over the same interval by passing this array as the second
  210. element of the sequence wopts and passing infodict['momcom'] as
  211. the first element.
  212. If one of the integration limits is infinite, then a Fourier integral is
  213. computed (assuming w neq 0). If full_output is 1 and a numerical error
  214. is encountered, besides the error message attached to the output tuple,
  215. a dictionary is also appended to the output tuple which translates the
  216. error codes in the array ``info['ierlst']`` to English messages. The
  217. output information dictionary contains the following entries instead of
  218. 'last', 'alist', 'blist', 'rlist', and 'elist':
  219. 'lst'
  220. The number of subintervals needed for the integration (call it ``K_f``).
  221. 'rslst'
  222. A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
  223. contain the integral contribution over the interval
  224. ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
  225. and ``k=1,2,...,K_f``.
  226. 'erlst'
  227. A rank-1 array of length ``M_f`` containing the error estimate
  228. corresponding to the interval in the same position in
  229. ``infodict['rslist']``.
  230. 'ierlst'
  231. A rank-1 integer array of length ``M_f`` containing an error flag
  232. corresponding to the interval in the same position in
  233. ``infodict['rslist']``. See the explanation dictionary (last entry
  234. in the output tuple) for the meaning of the codes.
  235. Examples
  236. --------
  237. Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
  238. >>> from scipy import integrate
  239. >>> x2 = lambda x: x**2
  240. >>> integrate.quad(x2, 0, 4)
  241. (21.333333333333332, 2.3684757858670003e-13)
  242. >>> print(4**3 / 3.) # analytical result
  243. 21.3333333333
  244. Calculate :math:`\\int^\\infty_0 e^{-x} dx`
  245. >>> invexp = lambda x: np.exp(-x)
  246. >>> integrate.quad(invexp, 0, np.inf)
  247. (1.0, 5.842605999138044e-11)
  248. >>> f = lambda x,a : a*x
  249. >>> y, err = integrate.quad(f, 0, 1, args=(1,))
  250. >>> y
  251. 0.5
  252. >>> y, err = integrate.quad(f, 0, 1, args=(3,))
  253. >>> y
  254. 1.5
  255. Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
  256. y parameter as 1::
  257. testlib.c =>
  258. double func(int n, double args[n]){
  259. return args[0]*args[0] + args[1]*args[1];}
  260. compile to library testlib.*
  261. ::
  262. from scipy import integrate
  263. import ctypes
  264. lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
  265. lib.func.restype = ctypes.c_double
  266. lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
  267. integrate.quad(lib.func,0,1,(1))
  268. #(1.3333333333333333, 1.4802973661668752e-14)
  269. print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
  270. # 1.3333333333333333
  271. Be aware that pulse shapes and other sharp features as compared to the
  272. size of the integration interval may not be integrated correctly using
  273. this method. A simplified example of this limitation is integrating a
  274. y-axis reflected step function with many zero values within the integrals
  275. bounds.
  276. >>> y = lambda x: 1 if x<=0 else 0
  277. >>> integrate.quad(y, -1, 1)
  278. (1.0, 1.1102230246251565e-14)
  279. >>> integrate.quad(y, -1, 100)
  280. (1.0000000002199108, 1.0189464580163188e-08)
  281. >>> integrate.quad(y, -1, 10000)
  282. (0.0, 0.0)
  283. """
  284. if not isinstance(args, tuple):
  285. args = (args,)
  286. # check the limits of integration: \int_a^b, expect a < b
  287. flip, a, b = b < a, min(a, b), max(a, b)
  288. if weight is None:
  289. retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
  290. points)
  291. else:
  292. retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
  293. limlst, limit, maxp1, weight, wvar, wopts)
  294. if flip:
  295. retval = (-retval[0],) + retval[1:]
  296. ier = retval[-1]
  297. if ier == 0:
  298. return retval[:-1]
  299. msgs = {80: "A Python error occurred possibly while calling the function.",
  300. 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,
  301. 2: "The occurrence of roundoff error is detected, which prevents \n the requested tolerance from being achieved. The error may be \n underestimated.",
  302. 3: "Extremely bad integrand behavior occurs at some points of the\n integration interval.",
  303. 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.",
  304. 5: "The integral is probably divergent, or slowly convergent.",
  305. 6: "The input is invalid.",
  306. 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.",
  307. 'unknown': "Unknown error."}
  308. if weight in ['cos','sin'] and (b == Inf or a == -Inf):
  309. 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."
  310. 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."
  311. 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."
  312. explain = {1: "The maximum number of subdivisions (= limit) has been \n achieved on this cycle.",
  313. 2: "The occurrence of roundoff error is detected and prevents\n the tolerance imposed on this cycle from being achieved.",
  314. 3: "Extremely bad integrand behavior occurs at some points of\n this cycle.",
  315. 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.",
  316. 5: "The integral over this cycle is probably divergent or slowly convergent."}
  317. try:
  318. msg = msgs[ier]
  319. except KeyError:
  320. msg = msgs['unknown']
  321. if ier in [1,2,3,4,5,7]:
  322. if full_output:
  323. if weight in ['cos', 'sin'] and (b == Inf or a == Inf):
  324. return retval[:-1] + (msg, explain)
  325. else:
  326. return retval[:-1] + (msg,)
  327. else:
  328. warnings.warn(msg, IntegrationWarning, stacklevel=2)
  329. return retval[:-1]
  330. elif ier == 6: # Forensic decision tree when QUADPACK throws ier=6
  331. if epsabs <= 0: # Small error tolerance - applies to all methods
  332. if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
  333. msg = ("If 'errabs'<=0, 'epsrel' must be greater than both"
  334. " 5e-29 and 50*(machine epsilon).")
  335. elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == Inf):
  336. msg = ("Sine or cosine weighted intergals with infinite domain"
  337. " must have 'epsabs'>0.")
  338. elif weight is None:
  339. if points is None: # QAGSE/QAGIE
  340. msg = ("Invalid 'limit' argument. There must be"
  341. " at least one subinterval")
  342. else: # QAGPE
  343. if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
  344. msg = ("All break points in 'points' must lie within the"
  345. " integration limits.")
  346. elif len(points) >= limit:
  347. msg = ("Number of break points ({:d})"
  348. " must be less than subinterval"
  349. " limit ({:d})").format(len(points), limit)
  350. else:
  351. if maxp1 < 1:
  352. msg = "Chebyshev moment limit maxp1 must be >=1."
  353. elif weight in ('cos', 'sin') and abs(a+b) == Inf: # QAWFE
  354. msg = "Cycle limit limlst must be >=3."
  355. elif weight.startswith('alg'): # QAWSE
  356. if min(wvar) < -1:
  357. msg = "wvar parameters (alpha, beta) must both be >= -1."
  358. if b < a:
  359. msg = "Integration limits a, b must satistfy a<b."
  360. elif weight == 'cauchy' and wvar in (a, b):
  361. msg = ("Parameter 'wvar' must not equal"
  362. " integration limits 'a' or 'b'.")
  363. raise ValueError(msg)
  364. def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points):
  365. infbounds = 0
  366. if (b != Inf and a != -Inf):
  367. pass # standard integration
  368. elif (b == Inf and a != -Inf):
  369. infbounds = 1
  370. bound = a
  371. elif (b == Inf and a == -Inf):
  372. infbounds = 2
  373. bound = 0 # ignored
  374. elif (b != Inf and a == -Inf):
  375. infbounds = -1
  376. bound = b
  377. else:
  378. raise RuntimeError("Infinity comparisons don't work for you.")
  379. if points is None:
  380. if infbounds == 0:
  381. return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
  382. else:
  383. return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
  384. else:
  385. if infbounds != 0:
  386. raise ValueError("Infinity inputs cannot be used with break points.")
  387. else:
  388. #Duplicates force function evaluation at sinular points
  389. the_points = numpy.unique(points)
  390. the_points = the_points[a < the_points]
  391. the_points = the_points[the_points < b]
  392. the_points = numpy.concatenate((the_points, (0., 0.)))
  393. return _quadpack._qagpe(func,a,b,the_points,args,full_output,epsabs,epsrel,limit)
  394. def _quad_weight(func,a,b,args,full_output,epsabs,epsrel,limlst,limit,maxp1,weight,wvar,wopts):
  395. if weight not in ['cos','sin','alg','alg-loga','alg-logb','alg-log','cauchy']:
  396. raise ValueError("%s not a recognized weighting function." % weight)
  397. strdict = {'cos':1,'sin':2,'alg':1,'alg-loga':2,'alg-logb':3,'alg-log':4}
  398. if weight in ['cos','sin']:
  399. integr = strdict[weight]
  400. if (b != Inf and a != -Inf): # finite limits
  401. if wopts is None: # no precomputed chebyshev moments
  402. return _quadpack._qawoe(func, a, b, wvar, integr, args, full_output,
  403. epsabs, epsrel, limit, maxp1,1)
  404. else: # precomputed chebyshev moments
  405. momcom = wopts[0]
  406. chebcom = wopts[1]
  407. return _quadpack._qawoe(func, a, b, wvar, integr, args, full_output,
  408. epsabs, epsrel, limit, maxp1, 2, momcom, chebcom)
  409. elif (b == Inf and a != -Inf):
  410. return _quadpack._qawfe(func, a, wvar, integr, args, full_output,
  411. epsabs,limlst,limit,maxp1)
  412. elif (b != Inf and a == -Inf): # remap function and interval
  413. if weight == 'cos':
  414. def thefunc(x,*myargs):
  415. y = -x
  416. func = myargs[0]
  417. myargs = (y,) + myargs[1:]
  418. return func(*myargs)
  419. else:
  420. def thefunc(x,*myargs):
  421. y = -x
  422. func = myargs[0]
  423. myargs = (y,) + myargs[1:]
  424. return -func(*myargs)
  425. args = (func,) + args
  426. return _quadpack._qawfe(thefunc, -b, wvar, integr, args,
  427. full_output, epsabs, limlst, limit, maxp1)
  428. else:
  429. raise ValueError("Cannot integrate with this weight from -Inf to +Inf.")
  430. else:
  431. if a in [-Inf,Inf] or b in [-Inf,Inf]:
  432. raise ValueError("Cannot integrate with this weight over an infinite interval.")
  433. if weight.startswith('alg'):
  434. integr = strdict[weight]
  435. return _quadpack._qawse(func, a, b, wvar, integr, args,
  436. full_output, epsabs, epsrel, limit)
  437. else: # weight == 'cauchy'
  438. return _quadpack._qawce(func, a, b, wvar, args, full_output,
  439. epsabs, epsrel, limit)
  440. def dblquad(func, a, b, gfun, hfun, args=(), epsabs=1.49e-8, epsrel=1.49e-8):
  441. """
  442. Compute a double integral.
  443. Return the double (definite) integral of ``func(y, x)`` from ``x = a..b``
  444. and ``y = gfun(x)..hfun(x)``.
  445. Parameters
  446. ----------
  447. func : callable
  448. A Python function or method of at least two variables: y must be the
  449. first argument and x the second argument.
  450. a, b : float
  451. The limits of integration in x: `a` < `b`
  452. gfun : callable or float
  453. The lower boundary curve in y which is a function taking a single
  454. floating point argument (x) and returning a floating point result
  455. or a float indicating a constant boundary curve.
  456. hfun : callable or float
  457. The upper boundary curve in y (same requirements as `gfun`).
  458. args : sequence, optional
  459. Extra arguments to pass to `func`.
  460. epsabs : float, optional
  461. Absolute tolerance passed directly to the inner 1-D quadrature
  462. integration. Default is 1.49e-8.
  463. epsrel : float, optional
  464. Relative tolerance of the inner 1-D integrals. Default is 1.49e-8.
  465. Returns
  466. -------
  467. y : float
  468. The resultant integral.
  469. abserr : float
  470. An estimate of the error.
  471. See also
  472. --------
  473. quad : single integral
  474. tplquad : triple integral
  475. nquad : N-dimensional integrals
  476. fixed_quad : fixed-order Gaussian quadrature
  477. quadrature : adaptive Gaussian quadrature
  478. odeint : ODE integrator
  479. ode : ODE integrator
  480. simps : integrator for sampled data
  481. romb : integrator for sampled data
  482. scipy.special : for coefficients and roots of orthogonal polynomials
  483. Examples
  484. --------
  485. Compute the double integral of ``x * y**2`` over the box
  486. ``x`` ranging from 0 to 2 and ``y`` ranging from 0 to 1.
  487. >>> from scipy import integrate
  488. >>> f = lambda y, x: x*y**2
  489. >>> integrate.dblquad(f, 0, 2, lambda x: 0, lambda x: 1)
  490. (0.6666666666666667, 7.401486830834377e-15)
  491. """
  492. def temp_ranges(*args):
  493. return [gfun(args[0]) if callable(gfun) else gfun,
  494. hfun(args[0]) if callable(hfun) else hfun]
  495. return nquad(func, [temp_ranges, [a, b]], args=args,
  496. opts={"epsabs": epsabs, "epsrel": epsrel})
  497. def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
  498. epsrel=1.49e-8):
  499. """
  500. Compute a triple (definite) integral.
  501. Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
  502. ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
  503. Parameters
  504. ----------
  505. func : function
  506. A Python function or method of at least three variables in the
  507. order (z, y, x).
  508. a, b : float
  509. The limits of integration in x: `a` < `b`
  510. gfun : function or float
  511. The lower boundary curve in y which is a function taking a single
  512. floating point argument (x) and returning a floating point result
  513. or a float indicating a constant boundary curve.
  514. hfun : function or float
  515. The upper boundary curve in y (same requirements as `gfun`).
  516. qfun : function or float
  517. The lower boundary surface in z. It must be a function that takes
  518. two floats in the order (x, y) and returns a float or a float
  519. indicating a constant boundary surface.
  520. rfun : function or float
  521. The upper boundary surface in z. (Same requirements as `qfun`.)
  522. args : tuple, optional
  523. Extra arguments to pass to `func`.
  524. epsabs : float, optional
  525. Absolute tolerance passed directly to the innermost 1-D quadrature
  526. integration. Default is 1.49e-8.
  527. epsrel : float, optional
  528. Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
  529. Returns
  530. -------
  531. y : float
  532. The resultant integral.
  533. abserr : float
  534. An estimate of the error.
  535. See Also
  536. --------
  537. quad: Adaptive quadrature using QUADPACK
  538. quadrature: Adaptive Gaussian quadrature
  539. fixed_quad: Fixed-order Gaussian quadrature
  540. dblquad: Double integrals
  541. nquad : N-dimensional integrals
  542. romb: Integrators for sampled data
  543. simps: Integrators for sampled data
  544. ode: ODE integrators
  545. odeint: ODE integrators
  546. scipy.special: For coefficients and roots of orthogonal polynomials
  547. Examples
  548. --------
  549. Compute the triple integral of ``x * y * z``, over ``x`` ranging
  550. from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
  551. >>> from scipy import integrate
  552. >>> f = lambda z, y, x: x*y*z
  553. >>> integrate.tplquad(f, 1, 2, lambda x: 2, lambda x: 3,
  554. ... lambda x, y: 0, lambda x, y: 1)
  555. (1.8750000000000002, 3.324644794257407e-14)
  556. """
  557. # f(z, y, x)
  558. # qfun/rfun (x, y)
  559. # gfun/hfun(x)
  560. # nquad will hand (y, x, t0, ...) to ranges0
  561. # nquad will hand (x, t0, ...) to ranges1
  562. # Stupid different API...
  563. def ranges0(*args):
  564. return [qfun(args[1], args[0]) if callable(qfun) else qfun,
  565. rfun(args[1], args[0]) if callable(rfun) else rfun]
  566. def ranges1(*args):
  567. return [gfun(args[0]) if callable(gfun) else gfun,
  568. hfun(args[0]) if callable(hfun) else hfun]
  569. ranges = [ranges0, ranges1, [a, b]]
  570. return nquad(func, ranges, args=args,
  571. opts={"epsabs": epsabs, "epsrel": epsrel})
  572. def nquad(func, ranges, args=None, opts=None, full_output=False):
  573. """
  574. Integration over multiple variables.
  575. Wraps `quad` to enable integration over multiple variables.
  576. Various options allow improved integration of discontinuous functions, as
  577. well as the use of weighted integration, and generally finer control of the
  578. integration process.
  579. Parameters
  580. ----------
  581. func : {callable, scipy.LowLevelCallable}
  582. The function to be integrated. Has arguments of ``x0, ... xn``,
  583. ``t0, tm``, where integration is carried out over ``x0, ... xn``, which
  584. must be floats. Function signature should be
  585. ``func(x0, x1, ..., xn, t0, t1, ..., tm)``. Integration is carried out
  586. in order. That is, integration over ``x0`` is the innermost integral,
  587. and ``xn`` is the outermost.
  588. If the user desires improved integration performance, then `f` may
  589. be a `scipy.LowLevelCallable` with one of the signatures::
  590. double func(int n, double *xx)
  591. double func(int n, double *xx, void *user_data)
  592. where ``n`` is the number of extra parameters and args is an array
  593. of doubles of the additional parameters, the ``xx`` array contains the
  594. coordinates. The ``user_data`` is the data contained in the
  595. `scipy.LowLevelCallable`.
  596. ranges : iterable object
  597. Each element of ranges may be either a sequence of 2 numbers, or else
  598. a callable that returns such a sequence. ``ranges[0]`` corresponds to
  599. integration over x0, and so on. If an element of ranges is a callable,
  600. then it will be called with all of the integration arguments available,
  601. as well as any parametric arguments. e.g. if
  602. ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
  603. either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
  604. args : iterable object, optional
  605. Additional arguments ``t0, ..., tn``, required by `func`, `ranges`, and
  606. ``opts``.
  607. opts : iterable object or dict, optional
  608. Options to be passed to `quad`. May be empty, a dict, or
  609. a sequence of dicts or functions that return a dict. If empty, the
  610. default options from scipy.integrate.quad are used. If a dict, the same
  611. options are used for all levels of integraion. If a sequence, then each
  612. element of the sequence corresponds to a particular integration. e.g.
  613. opts[0] corresponds to integration over x0, and so on. If a callable,
  614. the signature must be the same as for ``ranges``. The available
  615. options together with their default values are:
  616. - epsabs = 1.49e-08
  617. - epsrel = 1.49e-08
  618. - limit = 50
  619. - points = None
  620. - weight = None
  621. - wvar = None
  622. - wopts = None
  623. For more information on these options, see `quad` and `quad_explain`.
  624. full_output : bool, optional
  625. Partial implementation of ``full_output`` from scipy.integrate.quad.
  626. The number of integrand function evaluations ``neval`` can be obtained
  627. by setting ``full_output=True`` when calling nquad.
  628. Returns
  629. -------
  630. result : float
  631. The result of the integration.
  632. abserr : float
  633. The maximum of the estimates of the absolute error in the various
  634. integration results.
  635. out_dict : dict, optional
  636. A dict containing additional information on the integration.
  637. See Also
  638. --------
  639. quad : 1-dimensional numerical integration
  640. dblquad, tplquad : double and triple integrals
  641. fixed_quad : fixed-order Gaussian quadrature
  642. quadrature : adaptive Gaussian quadrature
  643. Examples
  644. --------
  645. >>> from scipy import integrate
  646. >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
  647. ... 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
  648. >>> points = [[lambda x1,x2,x3 : 0.2*x3 + 0.5 + 0.25*x1], [], [], []]
  649. >>> def opts0(*args, **kwargs):
  650. ... return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
  651. >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
  652. ... opts=[opts0,{},{},{}], full_output=True)
  653. (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
  654. >>> scale = .1
  655. >>> def func2(x0, x1, x2, x3, t0, t1):
  656. ... return x0*x1*x3**2 + np.sin(x2) + 1 + (1 if x0+t1*x1-t0>0 else 0)
  657. >>> def lim0(x1, x2, x3, t0, t1):
  658. ... return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
  659. ... scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
  660. >>> def lim1(x2, x3, t0, t1):
  661. ... return [scale * (t0*x2 + t1*x3) - 1,
  662. ... scale * (t0*x2 + t1*x3) + 1]
  663. >>> def lim2(x3, t0, t1):
  664. ... return [scale * (x3 + t0**2*t1**3) - 1,
  665. ... scale * (x3 + t0**2*t1**3) + 1]
  666. >>> def lim3(t0, t1):
  667. ... return [scale * (t0+t1) - 1, scale * (t0+t1) + 1]
  668. >>> def opts0(x1, x2, x3, t0, t1):
  669. ... return {'points' : [t0 - t1*x1]}
  670. >>> def opts1(x2, x3, t0, t1):
  671. ... return {}
  672. >>> def opts2(x3, t0, t1):
  673. ... return {}
  674. >>> def opts3(t0, t1):
  675. ... return {}
  676. >>> integrate.nquad(func2, [lim0, lim1, lim2, lim3], args=(0,0),
  677. ... opts=[opts0, opts1, opts2, opts3])
  678. (25.066666666666666, 2.7829590483937256e-13)
  679. """
  680. depth = len(ranges)
  681. ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
  682. if args is None:
  683. args = ()
  684. if opts is None:
  685. opts = [dict([])] * depth
  686. if isinstance(opts, dict):
  687. opts = [_OptFunc(opts)] * depth
  688. else:
  689. opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
  690. return _NQuad(func, ranges, opts, full_output).integrate(*args)
  691. class _RangeFunc(object):
  692. def __init__(self, range_):
  693. self.range_ = range_
  694. def __call__(self, *args):
  695. """Return stored value.
  696. *args needed because range_ can be float or func, and is called with
  697. variable number of parameters.
  698. """
  699. return self.range_
  700. class _OptFunc(object):
  701. def __init__(self, opt):
  702. self.opt = opt
  703. def __call__(self, *args):
  704. """Return stored dict."""
  705. return self.opt
  706. class _NQuad(object):
  707. def __init__(self, func, ranges, opts, full_output):
  708. self.abserr = 0
  709. self.func = func
  710. self.ranges = ranges
  711. self.opts = opts
  712. self.maxdepth = len(ranges)
  713. self.full_output = full_output
  714. if self.full_output:
  715. self.out_dict = {'neval': 0}
  716. def integrate(self, *args, **kwargs):
  717. depth = kwargs.pop('depth', 0)
  718. if kwargs:
  719. raise ValueError('unexpected kwargs')
  720. # Get the integration range and options for this depth.
  721. ind = -(depth + 1)
  722. fn_range = self.ranges[ind]
  723. low, high = fn_range(*args)
  724. fn_opt = self.opts[ind]
  725. opt = dict(fn_opt(*args))
  726. if 'points' in opt:
  727. opt['points'] = [x for x in opt['points'] if low <= x <= high]
  728. if depth + 1 == self.maxdepth:
  729. f = self.func
  730. else:
  731. f = partial(self.integrate, depth=depth+1)
  732. quad_r = quad(f, low, high, args=args, full_output=self.full_output,
  733. **opt)
  734. value = quad_r[0]
  735. abserr = quad_r[1]
  736. if self.full_output:
  737. infodict = quad_r[2]
  738. # The 'neval' parameter in full_output returns the total
  739. # number of times the integrand function was evaluated.
  740. # Therefore, only the innermost integration loop counts.
  741. if depth + 1 == self.maxdepth:
  742. self.out_dict['neval'] += infodict['neval']
  743. self.abserr = max(self.abserr, abserr)
  744. if depth > 0:
  745. return value
  746. else:
  747. # Final result of n-D integration with error
  748. if self.full_output:
  749. return value, self.abserr, self.out_dict
  750. else:
  751. return value, self.abserr