
    [h                         S SK r SSKJr   " S S\5      r " S S\5      r " S S	\5      r " S
 S\5      r\S:X  a  S SK	r	\	R                  " 5         gg)    N   )xrangec                   b    \ rS rSrSrS rS rSS jrSS jrSS jr	S r
S	 rSS
 jrSS jrSrg)QuadratureRule   a"  
Quadrature rules are implemented using this class, in order to
simplify the code and provide a common infrastructure
for tasks such as error estimation and node caching.

You can implement a custom quadrature rule by subclassing
:class:`QuadratureRule` and implementing the appropriate
methods. The subclass can then be used by :func:`~mpmath.quad` by
passing it as the *method* argument.

:class:`QuadratureRule` instances are supposed to be singletons.
:class:`QuadratureRule` therefore implements instance caching
in :func:`~mpmath.__new__`.
c                 :    Xl         0 U l        0 U l        0 U l        g N)ctxstandard_cachetransformed_cacheinterval_count)selfr
   s     R/var/www/auris/envauris/lib/python3.13/site-packages/mpmath/calculus/quadrature.py__init__QuadratureRule.__init__   s     !#     c                 .    0 U l         0 U l        0 U l        g)z
Delete cached node data.
N)r   r   r   )r   s    r   clearQuadratureRule.clear   s     !!# r   c                     [         e)z
Compute nodes for the standard interval `[-1, 1]`. Subclasses
should probably implement only this method, and use
:func:`~mpmath.get_nodes` method to retrieve the nodes.
)NotImplementedError)r   degreeprecverboses       r   
calc_nodesQuadratureRule.calc_nodes#   s
     "!r   c                    XX44nX`R                   ;   a  U R                   U   $ U R                  R                  n US-   U R                  l        X44U R                  ;   a  U R                  X44   nO!U R	                  X4U5      nXR                  X44'   U R                  XX%5      nX`R                  ;   a  XR                   U'   OSU R                  U'   XpR                  l        U$ ! XpR                  l        f = f)aO  
Return nodes for given interval, degree and precision. The
nodes are retrieved from a cache if already computed;
otherwise they are computed by calling :func:`~mpmath.calc_nodes`
and are then cached.

Subclasses should probably not implement this method,
but just implement :func:`~mpmath.calc_nodes` for the actual
node computation.
   T)r   r
   r   r   r   transform_nodesr   )	r   abr   r   r   keyorignodess	            r   	get_nodesQuadratureRule.get_nodes+   s     V"((())#..xx}}	! GDHHM~!4!44++FL9g>49##FL1((1>E))).3&&s++/##C( HHM !HHMs   BC" "C4c                    U R                   nUR                  U5      nUR                  U5      nUR                  nX#4U* U4:X  a  U$ UR                  S5      n/ nUR	                  U5      (       d  UR	                  U5      (       Ga5  X#4UR
                  UR                  4:X  a9  U* n	U H.  u  pX-  nXl-
  nX-  nX-  n
XU-  -  nUR                  X45        M0     U$ X%R
                  :X  a:  US-   nU H-  u  pSX-   -  nUU-
  n
XUS-  -  -  nUR                  X45        M/     U$ X5R                  :X  a:  US-
  nU H-  u  pSX-   -  nUU-   n
XUS-  -  -  nUR                  X45        M/     U$ X%R                  :X  d  X5R
                  :X  a)  U R                  XX$5       V
Vs/ s H	  u  pX* 4PM     snn
$ [        eX2-
  S-  nX2-   S-  nU H!  u  pUR                  UUU
-  -   UU-  45        M#     U$ s  snn
f )a  
Rescale standardized nodes (for `[-1, 1]`) to a general
interval `[a, b]`. For a finite interval, a simple linear
change of variables is used. Otherwise, the following
transformations are used:

.. math ::

    \lbrack a, \infty \rbrack : t = \frac{1}{x} + (a-1)

    \lbrack -\infty, b \rbrack : t = (b+1) - \frac{1}{x}

    \lbrack -\infty, \infty \rbrack : t = \frac{x}{\sqrt{1-x^2}}

      ?   r   )
r
   convertonempfisinfninfinfappendr   r   )r   r$   r    r!   r   r
   r+   half	new_nodesp05xwx2px1spx1b1ua1CDs                       r   r   QuadratureRule.transform_nodesL   s      hhKKNKKNgg6sdC[ Lwws|	99Q<<399Q<<v#((CGG,,e!DAB&C8DAcMA$$aV, "> 1 hhqS!DA15	A1AadNA$$aV,	 ", # ggqS!DA15	A1AadNA$$aV,	 "  gghh,0,@,@1,VW,V5A2,VWW)) aAaA  !AaC%1.  Xs   "G3c           
      z    [        S[        SU R                  R                  US-  S5      5      -   5      nUS-  nU$ )a  
Given a desired precision `p` in bits, estimate the degree `m`
of the quadrature required to accomplish full accuracy for
typical integrals. By default, :func:`~mpmath.quad` will perform up
to `m` iterations. The value of `m` should be a slight
overestimate, so that "slightly bad" integrals can be dealt
with automatically using a few extra iterations. On the
other hand, it should not be too big, so :func:`~mpmath.quad` can
quit within a reasonable amount of time when it is given
an "unsolvable" integral.

The default formula used by :func:`~mpmath.guess_degree` is tuned
for both :class:`TanhSinh` and :class:`GaussLegendre`.
The output is roughly as follows:

    +---------+---------+
    | `p`     | `m`     |
    +=========+=========+
    | 50      | 6       |
    +---------+---------+
    | 100     | 7       |
    +---------+---------+
    | 500     | 10      |
    +---------+---------+
    | 3000    | 12      |
    +---------+---------+

This formula is based purely on a limited amount of
experimentation and will sometimes be wrong.
   r   g      >@r   )intmaxr
   log)r   r   gs      r   guess_degreeQuadratureRule.guess_degree   s<    B C488<<T	15667	Qr   c                    [        U5      S:X  a  [        US   US   -
  5      $  US   US   s=:X  a	  US   :X  a  O  OU R                  R                  $ U R                  R	                  [        US   US   -
  5      S5      nU R                  R	                  [        US   US   -
  5      S5      nU* n[        S[        US-  U-  SU-  U5      5      nU R                  R                  S5      [        U5      -  $ ! [
         a    Us $ f = f)a  
Given results from integrations `[I_1, I_2, \ldots, I_k]` done
with a quadrature of rule of degree `1, 2, \ldots, k`, estimate
the error of `I_k`.

For `k = 2`, we estimate  `|I_{\infty}-I_2|` as `|I_2-I_1|`.

For `k > 2`, we extrapolate `|I_{\infty}-I_k| \approx |I_{k+1}-I_k|`
from `|I_k-I_{k-1}|` and `|I_k-I_{k-2}|` under the assumption
that each degree increment roughly doubles the accuracy of
the quadrature rule (this is true for both :class:`TanhSinh`
and :class:`GaussLegendre`). The extrapolation formula is given
by Borwein, Bailey & Girgensohn. Although not very conservative,
this method seems to be very robust in practice.
r   r   r)   
   )
lenabsr
   zerorC   
ValueErrorminrB   r,   rA   )r   resultsr   epsilonD1D2D3D4s           r   estimate_errorQuadratureRule.estimate_error   s      w<1wqz'!*,--	r{gbk8WR[8xx}}$c'"+gbk"9:B?Bc'"+gbk"9:B?B UCAb!B$+,xx||B3r7**	  	N	s   .C: AC: :D	D	c                 ~  ^ U R                   nUR                  =p[        [        U5      S-
  5       GH^  n
X*   X*S-      pX:X  a  M  X4UR                  UR
                  4:X  a  UmU4S jnUR                  UR
                  p/ nUR                  n[        SUS-   5       H  nU R                  XXU5      nU(       a:  [        SUR                  U5      < SUR                  U5      < SU< SU< S3	5        U R                  UUXX5      nUR                  U5        US:  d  M  U R                  XU5      nU(       a=  [        SUR                  U5      S	UR                  U5      S
UR                  U5      5        X::  d  M    O   XS   -  nX-  n	GMa     X:  a"  U(       a  [        SUR                  U	5      5        X4$ )ab  
Main integration function. Computes the 1D integral over
the interval specified by *points*. For each subinterval,
performs quadrature of degree from 1 up to *max_degree*
until :func:`~mpmath.estimate_error` signals convergence.

:func:`~mpmath.summation` transforms each subintegration to
the standard interval and then calls :func:`~mpmath.sum_next`.
r)   c                 (   > T" U * 5      T" U 5      -   $ r	    )r4   _fs    r   <lambda>*QuadratureRule.summation.<locals>.<lambda>   s    b!fr!unr   zIntegrating from z to z	 (degree z of )zEstimated error:z	 epsilon:z	 result: rH   z/Failed to reach full accuracy. Estimated error:)r
   rN   r   rL   r.   r/   r%   printnstrsum_nextr0   rW   )r   fpointsr   rR   
max_degreer   r
   I	total_errir    r!   rQ   errr   r$   resultr\   s                     @r   	summationQuadratureRule.summation   s    hh FA&A9fqSkqv v#((CGG,,,#''1G((C JqL1qV7C!chhqk6:G Hq%wPv&A:--gWEC0#((3-chhW^N_alnqnvnvw}n~~ 2 AI7 '8 GR[I\]|r   c                 N   ^ U R                   R                  U4S jU 5       5      $ )a  
Evaluates the step sum `\sum w_k f(x_k)` where the *nodes* list
contains the `(w_k, x_k)` pairs.

:func:`~mpmath.summation` will supply the list *results* of
values computed by :func:`~mpmath.sum_next` at previous degrees, in
case the quadrature rule is able to reuse them.
c              3   <   >#    U  H  u  pUT" U5      4v   M     g 7fr	   r[   .0r4   r5   rc   s      r   	<genexpr>*QuadratureRule.sum_next.<locals>.<genexpr>  s     :E5Aa1YE   )r
   fdot)r   rc   r$   r   r   previousr   s    `     r   rb   QuadratureRule.sum_next   s     xx}}:E:::r   )r
   r   r   r   NF)__name__
__module____qualname____firstlineno____doc__r   r   r   r%   r   rE   rW   rk   rb   __static_attributes__r[   r   r   r   r      s8    !!"B:x$L+:+Z	;r   r   c                   ,    \ rS rSrSrSS jrSS jrSrg)TanhSinhi  a5  
This class implements "tanh-sinh" or "doubly exponential"
quadrature. This quadrature rule is based on the Euler-Maclaurin
integral formula. By performing a change of variables involving
nested exponentials / hyperbolic functions (hence the name), the
derivatives at the endpoints vanish rapidly. Since the error term
in the Euler-Maclaurin formula depends on the derivatives at the
endpoints, a simple step sum becomes extremely accurate. In
practice, this means that doubling the number of evaluation
points roughly doubles the number of accurate digits.

Comparison to Gauss-Legendre:
  * Initial computation of nodes is usually faster
  * Handles endpoint singularities better
  * Handles infinite integration intervals better
  * Is slower for smooth integrands once nodes have been computed

The implementation of the tanh-sinh algorithm is based on the
description given in Borwein, Bailey & Girgensohn, "Experimentation
in Mathematics - Computational Paths to Discovery", A K Peters,
2003, pages 312-313. In the present implementation, a few
improvements have been made:

  * A more efficient scheme is used to compute nodes (exploiting
    recurrence for the exponential function)
  * The nodes are computed successively instead of all at once

**References**

* [Bailey]_
* http://users.cs.dal.ca/~jborwein/tanh-sinh.pdf

c                    ^ U R                   R                  S5      U* -  nU(       a  US   US-  -  nOU R                   R                  nXR                   R                  U4S jU 5       5      -  nXx-  $ )z
Step sum for tanh-sinh quadrature of degree `m`. We exploit the
fact that half of the abscissas at degree `m` are precisely the
abscissas from degree `m-1`. Thus reusing the result from
the previous level allows a 2x speedup.
r   rH   c              3   <   >#    U  H  u  pUT" U5      4v   M     g 7fr	   r[   ro   s      r   rq   $TanhSinh.sum_next.<locals>.<genexpr>4  s     7Aad8rs   )r
   r,   rN   rt   )	r   rc   r$   r   r   ru   r   hSs	    `       r   rb   TanhSinh.sum_next'  sa     HHLLOvg&ac"AA	XX]]7777s
r   c           
      n   U R                   n/ nSnU=R                  U-  sl        UR                  SU* S-
  5      nUR                  S-  nUR                  SU* 5      n	US:X  a-  UR	                  UR
                  UR                  S-  45        U	n
OU	S-  n
UR                  U	5      nX-  nX-  nUR                  U
5      nSU-  n[        SSSU-  -  S-   5       H  nUR                  X-
  5      nSU-  nUU-   S-  nUU-
  S-  nUU-  nX-   US-  -  n[        US-
  5      nUU::  a    OvUR	                  UU45        UR	                  U* U45        X-  nX-  nU(       d  M  US-  S:X  d  M  [        S	UR                  UR                  US5      * U-  5      5        M     U=R                  U-  sl        U$ )
aW  
The abscissas and weights for tanh-sinh quadrature of degree
`m` are given by

.. math::

    x_k = \tanh(\pi/2 \sinh(t_k))

    w_k = \pi/2 \cosh(t_k) / \cosh(\pi/2 \sinh(t_k))^2

where `t_k = t_0 + hk` for a step length `h \sim 2^{-m}`. The
list of nodes is actually infinite, but the weights die off so
rapidly that only a few are needed.
r   r)   rK   r@   r   r   i,     zCalculating nodes:)r
   r   ldexppir0   rN   expr   rM   r`   ra   rC   )r   r   r   r   r
   r$   extratolpi4t0r   expt0r    r!   udeltaurdeltakcdcosir4   r5   diffs                           r   r   TanhSinh.calc_nodes7  s    hhEiiD58$ffQh YYq6'"Q; LL#((CFF1H-.A1A KKF(2ai<>*A A!AA#qBA#qBRAAAqs8Ds{LL!Q LL1"a!KALAw1s7c> *CHHcggdB6G5G$5N,OP7 +: 	Er   r[   Nrw   )rx   ry   rz   r{   r|   rb   r   r}   r[   r   r   r   r     s     D Kr   r   c                   "    \ rS rSrSrSS jrSrg)GaussLegendrei  aN  
This class implements Gauss-Legendre quadrature, which is
exceptionally efficient for polynomials and polynomial-like (i.e.
very smooth) integrands.

The abscissas and weights are given by roots and values of
Legendre polynomials, which are the orthogonal polynomials
on `[-1, 1]` with respect to the unit weight
(see :func:`~mpmath.legendre`).

In this implementation, we take the "degree" `m` of the quadrature
to denote a Gauss-Legendre rule of degree `3 \cdot 2^m` (following
Borwein, Bailey & Girgensohn). This way we get quadratic, rather
than linear, convergence as the degree is incremented.

Comparison to tanh-sinh quadrature:
  * Is faster for smooth integrands once nodes have been computed
  * Initial computation of nodes is usually slower
  * Handles endpoint singularities worse
  * Handles infinite integration intervals worse

c                    U R                   nUR                  SU* S-
  5      nUR                  n[        US-  5      Ul        US:X  af  UR	                  UR                  S5      S-  5      nUR                  S5      S-  nU* U4UR                  UR                  S5      S-  4Xx4/n	Xdl        U	$ / n	SSUS-
  -  -  n
U
S-  S-   n[        SU5       GH  nUR                  [        R                  " [        R                  US-
  -  U
S	-   -  5      5      n S
u  p[        SU
S-   5       H  nXSU-  S-
  U-  U-  US-
  U-  -
  U-  pnM!     XU-  U-
  -  US-  S-
  -  nUU-  nUU-
  n[        U5      U:  a  OMe  UnSSUS-  -
  US-  -  -  nU(       a  US-  S:X  a  [        SX4-  5        U	R                  Xx45        U	R                  U* U45        GM     Xdl        U	$ )zx
Calculates the abscissas and weights for Gauss-Legendre
quadrature of degree of given degree (actually `3 \cdot 2^m`).
r)      g      ?   r   	   r   g      ?r(   )r)   r         zComputing nodes (%i of %i))r
   r   r   rA   sqrtr,   rN   r   mathcosr   rM   r`   r0   )r   r   r   r   r
   rR   r#   r4   r5   r$   nuptojrt1t2j1t3t4r    s                       r   r   GaussLegendre.calc_nodes  s   
 hh ))AuQw' xxtCx=Q;A&A
1AbVSXXcggajl3QE:EHLa&(mO!tax4A!D&!11S5!9:;A !1Q3-B!#1R461*R-2a4)*CR)GBBB ("R[!Q$q&)rEEq6G#  AAadFBE>"AAFbL2aY>?LL! LL1"a!) !* r   r[   Nrw   )rx   ry   rz   r{   r|   r   r}   r[   r   r   r   r     s    .,r   r   c                   @    \ rS rSrS rS rS rS rS
S jrSS jr	S	r
g)QuadratureMethodsi  c                 D    [        U 5      U l        [        U 5      U l        g r	   )r   _gauss_legendrer   
_tanh_sinhr
   argskwargss      r   r   QuadratureMethods.__init__  s    +C0!#r   c                 n  ^^^
^^^ UR                  SS5      m[        T5      [        L a4  TS:X  a  U R                  mO)TS:X  a  U R                  mO[        ST-  5      eT" U 5      mUR                  S5      n[        T5      nU R                  =nmU R                  S-  m
UR                  S5      =(       d    TR                  T5      mT Vs/ s H  opR                  U5      PM     snm U =R                  S-  sl        US	:X  a  TR                  TTS
   TT
TU5      u  pOaUS:X  a%  TR                  U
UUUUU4S jTS
   TT
TU5      u  pO6US:X  a%  TR                  U
UUUUU4S jTS
   TT
TU5      u  pO[        S5      eX`l        UR                  S5      (       a  U7U	4$ U7$ s  snf ! X`l        f = f)a1!  
Computes a single, double or triple integral over a given
1D interval, 2D rectangle, or 3D cuboid. A basic example::

    >>> from mpmath import *
    >>> mp.dps = 15; mp.pretty = True
    >>> quad(sin, [0, pi])
    2.0

A basic 2D integral::

    >>> f = lambda x, y: cos(x+y/2)
    >>> quad(f, [-pi/2, pi/2], [0, pi])
    4.0

**Interval format**

The integration range for each dimension may be specified
using a list or tuple. Arguments are interpreted as follows:

``quad(f, [x1, x2])`` -- calculates
`\int_{x_1}^{x_2} f(x) \, dx`

``quad(f, [x1, x2], [y1, y2])`` -- calculates
`\int_{x_1}^{x_2} \int_{y_1}^{y_2} f(x,y) \, dy \, dx`

``quad(f, [x1, x2], [y1, y2], [z1, z2])`` -- calculates
`\int_{x_1}^{x_2} \int_{y_1}^{y_2} \int_{z_1}^{z_2} f(x,y,z)
\, dz \, dy \, dx`

Endpoints may be finite or infinite. An interval descriptor
may also contain more than two points. In this
case, the integration is split into subintervals, between
each pair of consecutive points. This is useful for
dealing with mid-interval discontinuities, or integrating
over large intervals where the function is irregular or
oscillates.

**Options**

:func:`~mpmath.quad` recognizes the following keyword arguments:

*method*
    Chooses integration algorithm (described below).
*error*
    If set to true, :func:`~mpmath.quad` returns `(v, e)` where `v` is the
    integral and `e` is the estimated error.
*maxdegree*
    Maximum degree of the quadrature rule to try before
    quitting.
*verbose*
    Print details about progress.

**Algorithms**

Mpmath presently implements two integration algorithms: tanh-sinh
quadrature and Gauss-Legendre quadrature. These can be selected
using *method='tanh-sinh'* or *method='gauss-legendre'* or by
passing the classes *method=TanhSinh*, *method=GaussLegendre*.
The functions :func:`~mpmath.quadts` and :func:`~mpmath.quadgl` are also available
as shortcuts.

Both algorithms have the property that doubling the number of
evaluation points roughly doubles the accuracy, so both are ideal
for high precision quadrature (hundreds or thousands of digits).

At high precision, computing the nodes and weights for the
integration can be expensive (more expensive than computing the
function values). To make repeated integrations fast, nodes
are automatically cached.

The advantages of the tanh-sinh algorithm are that it tends to
handle endpoint singularities well, and that the nodes are cheap
to compute on the first run. For these reasons, it is used by
:func:`~mpmath.quad` as the default algorithm.

Gauss-Legendre quadrature often requires fewer function
evaluations, and is therefore often faster for repeated use, but
the algorithm does not handle endpoint singularities as well and
the nodes are more expensive to compute. Gauss-Legendre quadrature
can be a better choice if the integrand is smooth and repeated
integrations are required (e.g. for multiple integrals).

See the documentation for :class:`TanhSinh` and
:class:`GaussLegendre` for additional details.

**Examples of 1D integrals**

Intervals may be infinite or half-infinite. The following two
examples evaluate the limits of the inverse tangent function
(`\int 1/(1+x^2) = \tan^{-1} x`), and the Gaussian integral
`\int_{\infty}^{\infty} \exp(-x^2)\,dx = \sqrt{\pi}`::

    >>> mp.dps = 15
    >>> quad(lambda x: 2/(x**2+1), [0, inf])
    3.14159265358979
    >>> quad(lambda x: exp(-x**2), [-inf, inf])**2
    3.14159265358979

Integrals can typically be resolved to high precision.
The following computes 50 digits of `\pi` by integrating the
area of the half-circle defined by `x^2 + y^2 \le 1`,
`-1 \le x \le 1`, `y \ge 0`::

    >>> mp.dps = 50
    >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1])
    3.1415926535897932384626433832795028841971693993751

One can just as well compute 1000 digits (output truncated)::

    >>> mp.dps = 1000
    >>> 2*quad(lambda x: sqrt(1-x**2), [-1, 1])  #doctest:+ELLIPSIS
    3.141592653589793238462643383279502884...216420199

Complex integrals are supported. The following computes
a residue at `z = 0` by integrating counterclockwise along the
diamond-shaped path from `1` to `+i` to `-1` to `-i` to `1`::

    >>> mp.dps = 15
    >>> chop(quad(lambda z: 1/z, [1,j,-1,-j,1]))
    (0.0 + 6.28318530717959j)

**Examples of 2D and 3D integrals**

Here are several nice examples of analytically solvable
2D integrals (taken from MathWorld [1]) that can be evaluated
to high precision fairly rapidly by :func:`~mpmath.quad`::

    >>> mp.dps = 30
    >>> f = lambda x, y: (x-1)/((1-x*y)*log(x*y))
    >>> quad(f, [0, 1], [0, 1])
    0.577215664901532860606512090082
    >>> +euler
    0.577215664901532860606512090082

    >>> f = lambda x, y: 1/sqrt(1+x**2+y**2)
    >>> quad(f, [-1, 1], [-1, 1])
    3.17343648530607134219175646705
    >>> 4*log(2+sqrt(3))-2*pi/3
    3.17343648530607134219175646705

    >>> f = lambda x, y: 1/(1-x**2 * y**2)
    >>> quad(f, [0, 1], [0, 1])
    1.23370055013616982735431137498
    >>> pi**2 / 8
    1.23370055013616982735431137498

    >>> quad(lambda x, y: 1/(1-x*y), [0, 1], [0, 1])
    1.64493406684822643647241516665
    >>> pi**2 / 6
    1.64493406684822643647241516665

Multiple integrals may be done over infinite ranges::

    >>> mp.dps = 15
    >>> print(quad(lambda x,y: exp(-x-y), [0, inf], [1, inf]))
    0.367879441171442
    >>> print(1/e)
    0.367879441171442

For nonrectangular areas, one can call :func:`~mpmath.quad` recursively.
For example, we can replicate the earlier example of calculating
`\pi` by integrating over the unit-circle, and actually use double
quadrature to actually measure the area circle::

    >>> f = lambda x: quad(lambda y: 1, [-sqrt(1-x**2), sqrt(1-x**2)])
    >>> quad(f, [-1, 1])
    3.14159265358979

Here is a simple triple integral::

    >>> mp.dps = 15
    >>> f = lambda x,y,z: x*y/(1+z)
    >>> quad(f, [0,1], [0,1], [1,2], method='gauss-legendre')
    0.101366277027041
    >>> (log(3)-log(2))/4
    0.101366277027041

**Singularities**

Both tanh-sinh and Gauss-Legendre quadrature are designed to
integrate smooth (infinitely differentiable) functions. Neither
algorithm copes well with mid-interval singularities (such as
mid-interval discontinuities in `f(x)` or `f'(x)`).
The best solution is to split the integral into parts::

    >>> mp.dps = 15
    >>> quad(lambda x: abs(sin(x)), [0, 2*pi])   # Bad
    3.99900894176779
    >>> quad(lambda x: abs(sin(x)), [0, pi, 2*pi])  # Good
    4.0

The tanh-sinh rule often works well for integrands having a
singularity at one or both endpoints::

    >>> mp.dps = 15
    >>> quad(log, [0, 1], method='tanh-sinh')  # Good
    -1.0
    >>> quad(log, [0, 1], method='gauss-legendre')  # Bad
    -0.999932197413801

However, the result may still be inaccurate for some functions::

    >>> quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh')
    1.99999999946942

This problem is not due to the quadrature rule per se, but to
numerical amplification of errors in the nodes. The problem can be
circumvented by temporarily increasing the precision::

    >>> mp.dps = 30
    >>> a = quad(lambda x: 1/sqrt(x), [0, 1], method='tanh-sinh')
    >>> mp.dps = 15
    >>> +a
    2.0

**Highly variable functions**

For functions that are smooth (in the sense of being infinitely
differentiable) but contain sharp mid-interval peaks or many
"bumps", :func:`~mpmath.quad` may fail to provide full accuracy. For
example, with default settings, :func:`~mpmath.quad` is able to integrate
`\sin(x)` accurately over an interval of length 100 but not over
length 1000::

    >>> quad(sin, [0, 100]); 1-cos(100)   # Good
    0.137681127712316
    0.137681127712316
    >>> quad(sin, [0, 1000]); 1-cos(1000)   # Bad
    -37.8587612408485
    0.437620923709297

One solution is to break the integration into 10 intervals of
length 100::

    >>> quad(sin, linspace(0, 1000, 10))   # Good
    0.437620923709297

Another is to increase the degree of the quadrature::

    >>> quad(sin, [0, 1000], maxdegree=10)   # Also good
    0.437620923709297

Whether splitting the interval or increasing the degree is
more efficient differs from case to case. Another example is the
function `1/(1+x^2)`, which has a sharp peak centered around
`x = 0`::

    >>> f = lambda x: 1/(1+x**2)
    >>> quad(f, [-100, 100])   # Bad
    3.64804647105268
    >>> quad(f, [-100, 100], maxdegree=10)   # Good
    3.12159332021646
    >>> quad(f, [-100, 0, 100])   # Also good
    3.12159332021646

**References**

1. http://mathworld.wolfram.com/DoubleIntegral.html

method	tanh-sinhgauss-legendrezunknown quadrature rule: %sr   r   	maxdegreer   r)   r   r   c                 F   >^  TR                  UU 4S jTS   TTT5      S   $ )Nc                    > T" TU 5      $ r	   r[   )yrc   r4   s    r   r]   :QuadratureMethods.quad.<locals>.<lambda>.<locals>.<lambda>  s    1Qr   r)   r   rk   r4   rR   rc   mrd   r   rules   `r   r]   (QuadratureMethods.quad.<locals>.<lambda>  s'    '7q	4!5568r   r   c           	      P   >^  TR                  UUUUUUU 4S jTS   TTT5      S   $ )Nc                 H   >^  TR                  UUU 4S jTS   TTT5      S   $ )Nc                    > T" TTU 5      $ r	   r[   )zrc   r4   r   s    r   r]   LQuadratureMethods.quad.<locals>.<lambda>.<locals>.<lambda>.<locals>.<lambda>  s    Qq1Xr   r   r   r   )r   rR   rc   r   rd   r   r   r4   s   `r   r]   r     s'     NN+="1ItWa99:<r   r)   r   r   r   s   `r   r]   r     s2     (< (< q	4!5 678r   z"quadrature must have dim 1, 2 or 3error)gettypestrr   r   rO   rL   r   epsrE   
_as_pointsrk   r   )r
   rc   rd   r   r   dimr#   pvri   rR   r   r   r   s    ``       @@@@r   quadQuadratureMethods.quad  s   L zz(K0:{"~~))** !>!EFF9D**Y'&khht''!)JJ{#>t'8'8'>-34V..#V4	HHNHax6!9dGQP3 )8 )8 1ItWa:3  )8 )8
 1ItWa:3 **NOOH::g2s7Nr	/ 5( Hs   F'+BF, ,F4c                 0    SUS'   U R                   " U0 UD6$ )a  
Performs tanh-sinh quadrature. The call

    quadts(func, *points, ...)

is simply a shortcut for:

    quad(func, *points, ..., method=TanhSinh)

For example, a single integral and a double integral:

    quadts(lambda x: exp(cos(x)), [0, 1])
    quadts(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1])

See the documentation for quad for information about how points
arguments and keyword arguments are parsed.

See documentation for TanhSinh for algorithmic information about
tanh-sinh quadrature.
r   r   r   r   s      r   quadtsQuadratureMethods.quadts  s"    * 'xxx(((r   c                 0    SUS'   U R                   " U0 UD6$ )a  
Performs Gauss-Legendre quadrature. The call

    quadgl(func, *points, ...)

is simply a shortcut for:

    quad(func, *points, ..., method=GaussLegendre)

For example, a single integral and a double integral:

    quadgl(lambda x: exp(cos(x)), [0, 1])
    quadgl(lambda x, y: exp(cos(x+y)), [0, 1], [0, 1])

See the documentation for quad for information about how points
arguments and keyword arguments are parsed.

See documentation for TanhSinh for algorithmic information about
tanh-sinh quadrature.
r   r   r   r   s      r   quadglQuadratureMethods.quadgl  s"    * ,xxx(((r   Nc                   ^ ^^^ T R                  U5      u  pgT R                  U5      nT R                  U5      nUTT/R                  S5      S:w  a  [        S5      eUT R                  :X  a>  UT R
                  :X  a.  T R                  TUS/UTTS9nT R                  TSU/UTTS9n	X-   $ UT R                  :X  a@  T(       a  T R                  U4S jU* U* /U4S j5      $ T R                  U4S jU* U* /UTS	9$ UT R
                  :w  a  [        S
5      eT(       d  U(       a  ST R                  -  U-  mU4S jmSn
T R                  TUT" U
5      /5      nU UU4S jnUT R                  XT R
                  /5      -  nU$ )aL  
Calculates

.. math ::

    I = \int_a^b f(x) dx

where at least one of `a` and `b` is infinite and where
`f(x) = g(x) \cos(\omega x  + \phi)` for some slowly
decreasing function `g(x)`. With proper input, :func:`~mpmath.quadosc`
can also handle oscillatory integrals where the oscillation
rate is different from a pure sine or cosine wave.

In the standard case when `|a| < \infty, b = \infty`,
:func:`~mpmath.quadosc` works by evaluating the infinite series

.. math ::

    I = \int_a^{x_1} f(x) dx +
    \sum_{k=1}^{\infty} \int_{x_k}^{x_{k+1}} f(x) dx

where `x_k` are consecutive zeros (alternatively
some other periodic reference point) of `f(x)`.
Accordingly, :func:`~mpmath.quadosc` requires information about the
zeros of `f(x)`. For a periodic function, you can specify
the zeros by either providing the angular frequency `\omega`
(*omega*) or the *period* `2 \pi/\omega`. In general, you can
specify the `n`-th zero by providing the *zeros* arguments.
Below is an example of each::

    >>> from mpmath import *
    >>> mp.dps = 15; mp.pretty = True
    >>> f = lambda x: sin(3*x)/(x**2+1)
    >>> quadosc(f, [0,inf], omega=3)
    0.37833007080198
    >>> quadosc(f, [0,inf], period=2*pi/3)
    0.37833007080198
    >>> quadosc(f, [0,inf], zeros=lambda n: pi*n/3)
    0.37833007080198
    >>> (ei(3)*exp(-3)-exp(3)*ei(-3))/2  # Computed by Mathematica
    0.37833007080198

Note that *zeros* was specified to multiply `n` by the
*half-period*, not the full period. In theory, it does not matter
whether each partial integral is done over a half period or a full
period. However, if done over half-periods, the infinite series
passed to :func:`~mpmath.nsum` becomes an *alternating series* and this
typically makes the extrapolation much more efficient.

Here is an example of an integration over the entire real line,
and a half-infinite integration starting at `-\infty`::

    >>> quadosc(lambda x: cos(x)/(1+x**2), [-inf, inf], omega=1)
    1.15572734979092
    >>> pi/e
    1.15572734979092
    >>> quadosc(lambda x: cos(x)/x**2, [-inf, -1], period=2*pi)
    -0.0844109505595739
    >>> cos(1)+si(1)-pi/2
    -0.0844109505595738

Of course, the integrand may contain a complex exponential just as
well as a real sine or cosine::

    >>> quadosc(lambda x: exp(3*j*x)/(1+x**2), [-inf,inf], omega=3)
    (0.156410688228254 + 0.0j)
    >>> pi/e**3
    0.156410688228254
    >>> quadosc(lambda x: exp(3*j*x)/(2+x+x**2), [-inf,inf], omega=3)
    (0.00317486988463794 - 0.0447701735209082j)
    >>> 2*pi/sqrt(7)/exp(3*(j+sqrt(7))/2)
    (0.00317486988463794 - 0.0447701735209082j)

**Non-periodic functions**

If `f(x) = g(x) h(x)` for some function `h(x)` that is not
strictly periodic, *omega* or *period* might not work, and it might
be necessary to use *zeros*.

A notable exception can be made for Bessel functions which, though not
periodic, are "asymptotically periodic" in a sufficiently strong sense
that the sum extrapolation will work out::

    >>> quadosc(j0, [0, inf], period=2*pi)
    1.0
    >>> quadosc(j1, [0, inf], period=2*pi)
    1.0

More properly, one should provide the exact Bessel function zeros::

    >>> j0zero = lambda n: findroot(j0, pi*(n-0.25))
    >>> quadosc(j0, [0, inf], zeros=j0zero)
    1.0

For an example where *zeros* becomes necessary, consider the
complete Fresnel integrals

.. math ::

    \int_0^{\infty} \cos x^2\,dx = \int_0^{\infty} \sin x^2\,dx
    = \sqrt{\frac{\pi}{8}}.

Although the integrands do not decrease in magnitude as
`x \to \infty`, the integrals are convergent since the oscillation
rate increases (causing consecutive periods to asymptotically
cancel out). These integrals are virtually impossible to calculate
to any kind of accuracy using standard quadrature rules. However,
if one provides the correct asymptotic distribution of zeros
(`x_n \sim \sqrt{n}`), :func:`~mpmath.quadosc` works::

    >>> mp.dps = 30
    >>> f = lambda x: cos(x**2)
    >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n))
    0.626657068657750125603941321203
    >>> f = lambda x: sin(x**2)
    >>> quadosc(f, [0,inf], zeros=lambda n:sqrt(pi*n))
    0.626657068657750125603941321203
    >>> sqrt(pi/8)
    0.626657068657750125603941321203

(Interestingly, these integrals can still be evaluated if one
places some other constant than `\pi` in the square root sign.)

In general, if `f(x) \sim g(x) \cos(h(x))`, the zeros follow
the inverse-function distribution `h^{-1}(x)`::

    >>> mp.dps = 15
    >>> f = lambda x: sin(exp(x))
    >>> quadosc(f, [1,inf], zeros=lambda n: log(n))
    -0.25024394235267
    >>> pi/2-si(e)
    -0.250243942352671

**Non-alternating functions**

If the integrand oscillates around a positive value, without
alternating signs, the extrapolation might fail. A simple trick
that sometimes works is to multiply or divide the frequency by 2::

    >>> f = lambda x: 1/x**2+sin(x)/x**4
    >>> quadosc(f, [1,inf], omega=1)  # Bad
    1.28642190869861
    >>> quadosc(f, [1,inf], omega=0.5)  # Perfect
    1.28652953559617
    >>> 1+(cos(1)+ci(1)+sin(1))/6
    1.28652953559617

**Fast decay**

:func:`~mpmath.quadosc` is primarily useful for slowly decaying
integrands. If the integrand decreases exponentially or faster,
:func:`~mpmath.quad` will likely handle it without trouble (and generally be
much faster than :func:`~mpmath.quadosc`)::

    >>> quadosc(lambda x: cos(x)/exp(x), [0, inf], omega=1)
    0.5
    >>> quad(lambda x: cos(x)/exp(x), [0, inf])
    0.5

Nr   z0must specify exactly one of omega, period, zerosr   )omegazerosperiodc                    > T" U * 5      $ r	   r[   r4   rc   s    r   r]   +QuadratureMethods.quadosc.<locals>.<lambda>      AqbEr   c                    > T" U * 5      $ r	   r[   )r   r   s    r   r]   r     s    eQBir   c                    > T" U * 5      $ r	   r[   r   s    r   r]   r     r   r   )r   r   z1quadosc requires an infinite integration intervalc                    > U T-  S-  $ )Nr   r[   )r   r   s    r   r]   r     s    ahqjr   r)   c                 J   > TR                  TT" U 5      T" U S-   5      /5      $ )Nr)   )r   )r   r
   rc   r   s    r   term'QuadratureMethods.quadosc.<locals>.term  s%    ::a%(E!A#J!788r   )
r   r*   countrO   r.   r/   quadoscr   r   nsum)r
   rc   intervalr   r   r   r    r!   s1s2r   sr   s   ``  ``       r   r   QuadratureMethods.quadosc/  sq   B ~~h'KKNKKN65!''-2BD D=Q#''\QAe5PBQAe5PB7N={{>QBr7<OPP{{>QBr7%PV{WW<PQQ366%(E JJq1eAh-(	9	SXXdL))r   c                 4   / n[        [        U5      S-
  5       H  nUR                  X'   X'S-      45        M     U R                  nU R                  n	Uc  SU R                  -  nSn
UR                  5       nSUS'   SUS'   Uc  U R                  7nU R                  n U =R                  S-  sl        U(       Ga/  UR                  5       u  pU R                  " XU/40 UD6u  nnUR                  S5      (       a  [        S	XUU5        UU:  d  X:  a
  X-  nU	U-  n	OU
S-  n
X:X  a!  UR                  S5      (       a  [        S
5        XR                  * :X  a  XR                  :X  a  SnOOXR                  * :X  a  [        US-
  SU-  5      nO,XR                  :X  a  [        US-   SU-  5      nO
XU-
  S-  -   nUR                  UU45        UR                  UU45        U(       a  GM/  Xl        UR                  S5      (       a  U7U	74$ U7$ ! Xl        f = f)a  
Computes the integral of *f* over the interval or path specified
by *interval*, using :func:`~mpmath.quad` together with adaptive
subdivision of the interval.

This function gives an accurate answer for some integrals where
:func:`~mpmath.quad` fails::

    >>> from mpmath import *
    >>> mp.dps = 15; mp.pretty = True
    >>> quad(lambda x: abs(sin(x)), [0, 2*pi])
    3.99900894176779
    >>> quadsubdiv(lambda x: abs(sin(x)), [0, 2*pi])
    4.0
    >>> quadsubdiv(sin, [0, 1000])
    0.437620923709297
    >>> quadsubdiv(lambda x: 1/(1+x**2), [-100, 100])
    3.12159332021646
    >>> quadsubdiv(lambda x: ceil(x), [0, 100])
    5050.0
    >>> quadsubdiv(lambda x: sin(x+exp(x)), [0,8])
    0.347400172657248

The argument *maxintervals* can be set to limit the permissible
subdivision::

    >>> quadsubdiv(lambda x: sin(x**2), [0,100], maxintervals=5, error=True)
    (-5.40487904307774, 5.011)
    >>> quadsubdiv(lambda x: sin(x**2), [0,100], maxintervals=100, error=True)
    (0.631417921866934, 1.10101120134116e-17)

Subdivision does not guarantee a correct answer since, the error
estimate on subintervals may be inaccurate::

    >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, [0,1], error=True)
    (0.210802735500549, 1.0001111101e-17)
    >>> mp.dps = 20
    >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, [0,1], error=True)
    (0.21080273550054927738, 2.200000001e-24)

The second answer is correct. We can get an accurate result at lower
precision by forcing a finer initial subdivision::

    >>> mp.dps = 15
    >>> quadsubdiv(lambda x: sech(10*x-2)**2 + sech(100*x-40)**4 + sech(1000*x-600)**6, linspace(0,1,5))
    0.210802735500549

The following integral is too oscillatory for convergence, but we can get a
reasonable estimate::

    >>> v, err = fp.quadsubdiv(lambda x: fp.sin(1/x), [0,1], error=True)
    >>> round(v, 6), round(err, 6)
    (0.504067, 1e-06)
    >>> sin(1) - ci(1)
    0.504067061906928

r)   rK   r   Fr   Tr   r   subintervalz2warning: number of intervals exceeded maxintervalsr   )rangerL   r0   rN   r   copyr   popr   r   r`   r/   rP   rB   )r
   rc   r   r   maxintervalsr   queuerh   totaltotal_errorr   	quad_argsr#   r    r!   r   ri   r   s                     r   
quadsubdivQuadratureMethods.quadsubdiv  s   t s8}Q'ALL(+x!}56 (hh=LKKM	$	)!	';77(Cxx	HHMHyy{!V9y93::i((-1c:9 4JE3&KQJE,I1F1FRSWWH}ggwwh!QqSMgg!QqSMQ!OLL!Q(LL!Q(+ %. H::g6K<''6M	 Hs   E	H Hr[   )NNN)NN)rx   ry   rz   r{   r   r   r   r   r   r   r}   r[   r   r   r   r     s%    'l\	)0)0AFer   r   __main__)r   libmp.backendr   objectr   r   r   r   rx   doctesttestmodr[   r   r   <module>r     sc     "|;V |;~~~ ~BDN DLL
 L
\ zOO r   