a
    ¬ˆc„  ã                   @  s€  d dl mZ d dlmZmZmZmZmZmZ d dl	Z	d dl
Zd dlZd dlZd dlZd dl
mZ d dlmZ d dlmZ g d¢Zdd	„ ZeeƒZejr¦ej d
d¡e_d~dd„ZG dd„ deƒZerâd dlmZ G dd„ deƒZneZdddœdd„Zedd„ ƒZeƒ e_ ddd„Z!d€d d!„Z"d�d&d'„Z#d(d)„ Z$d‚d*d+„Z%dƒd,d-„Z&d.d/„ Z'd„d1d2„Z(d…d3d4„Z)d†d5d6„Z*d7d8„ Z+d9d:„ Z,d;d<„ Z-d‡d?d@„Z.d%dAd%d%gddBfd%dCg dD¢ddEfdCdFg dG¢dHdIfdAdJg dK¢dLdMfddNg dO¢dPdQfd%dRg dS¢dTdUfdVdWg dX¢dYdZfd[d\g d]¢d^d_fd`dag db¢dcddfddeg df¢dgdhfdidjg dk¢dldmfd%dng do¢dpdqfdrdsg dt¢dudvfdVdwg dx¢dydzfd{œZ/dˆd|d}„Z0dS )‰é    )Úannotations)ÚTYPE_CHECKINGÚCallableÚDictÚTupleÚAnyÚcastN)Útrapz)Úroots_legendre)Úgammaln)Ú
fixed_quadÚ
quadratureÚrombergÚrombÚ	trapezoidr	   ÚsimpsÚsimpsonÚcumulative_trapezoidÚcumtrapzÚnewton_cotesÚAccuracyWarningc                 C  s6   t j| j| j| j| j| jd�}t || ¡}| j	|_	|S )zBBased on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard))ÚnameZargdefsÚclosure)
ÚtypesÚFunctionTypeÚ__code__Ú__globals__Ú__name__Ú__defaults__Ú__closure__Ú	functoolsÚupdate_wrapperÚ__kwdefaults__)ÚfÚg© r%   ú^/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/scipy/integrate/_quadrature.pyÚ
_copy_func   s    ÿr'   zsum, cumsumznumpy.cumsumç      ð?éÿÿÿÿc                 C  s   t | |||d�S )z}An alias of `trapezoid`.

    `trapz` is kept for backwards compatibility. For new code, prefer
    `trapezoid` instead.
    )ÚxÚdxÚaxis)r   )Úyr*   r+   r,   r%   r%   r&   r	   '   s    r	   c                   @  s   e Zd ZdS )r   N)r   Ú
__module__Ú__qualname__r%   r%   r%   r&   r   0   s   r   )ÚProtocolc                   @  s   e Zd ZU ded< dS )ÚCacheAttributeszDict[int, Tuple[Any, Any]]ÚcacheN)r   r.   r/   Ú__annotations__r%   r%   r%   r&   r1   9   s   
r1   r   )ÚfuncÚreturnc                 C  s
   t t| ƒS ©N)r   r1   )r4   r%   r%   r&   Úcache_decorator?   s    r7   c                 C  s,   | t jv rt j|  S t| ƒt j| < t j|  S )zX
    Cache roots_legendre results to speed up calls of the fixed_quad
    function.
    )Ú_cached_roots_legendrer2   r
   )Únr%   r%   r&   r8   C   s    

r8   r%   é   c                 C  sx   t |ƒ\}}t |¡}t |¡s*t |¡r2tdƒ‚|| |d  d | }|| d tj|| |g|¢R Ž  dd� dfS )aü  
    Compute a definite integral using fixed-order Gaussian quadrature.

    Integrate `func` from `a` to `b` using Gaussian quadrature of
    order `n`.

    Parameters
    ----------
    func : callable
        A Python function or method to integrate (must accept vector inputs).
        If integrating a vector-valued function, the returned array must have
        shape ``(..., len(x))``.
    a : float
        Lower limit of integration.
    b : float
        Upper limit of integration.
    args : tuple, optional
        Extra arguments to pass to function, if any.
    n : int, optional
        Order of quadrature integration. Default is 5.

    Returns
    -------
    val : float
        Gaussian quadrature approximation to the integral
    none : None
        Statically returned value of None

    See Also
    --------
    quad : adaptive quadrature using QUADPACK
    dblquad : double integrals
    tplquad : triple integrals
    romberg : adaptive Romberg quadrature
    quadrature : adaptive Gaussian quadrature
    romb : integrators for sampled data
    simpson : integrators for sampled data
    cumulative_trapezoid : cumulative integration for sampled data
    ode : ODE integrator
    odeint : ODE integrator

    Examples
    --------
    >>> from scipy import integrate
    >>> f = lambda x: x**8
    >>> integrate.fixed_quad(f, 0.0, 1.0, n=4)
    (0.1110884353741496, None)
    >>> integrate.fixed_quad(f, 0.0, 1.0, n=5)
    (0.11111111111111102, None)
    >>> print(1/9.0)  # analytical result
    0.1111111111111111

    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)
    (0.9999999771971152, None)
    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)
    (1.000000000039565, None)
    >>> np.sin(np.pi/2)-np.sin(0)  # analytical result
    1.0

    z8Gaussian quadrature is only available for finite limits.é   ç       @r)   ©r,   N)r8   ÚnpÚrealÚisinfÚ
ValueErrorÚsum)r4   ÚaÚbÚargsr9   r*   Úwr-   r%   r%   r&   r   S   s    =
r   Fc                   s&   |r‡ ‡fdd„}n‡ ‡fdd„}|S )ao  Vectorize the call to a function.

    This is an internal utility function used by `romberg` and
    `quadrature` to create a vectorized version of a function.

    If `vec_func` is True, the function `func` is assumed to take vector
    arguments.

    Parameters
    ----------
    func : callable
        User defined function.
    args : tuple, optional
        Extra arguments for the function.
    vec_func : bool, optional
        True if the function func takes vector arguments.

    Returns
    -------
    vfunc : callable
        A function that will take a vector argument and return the
        result.

    c                   s   ˆ| gˆ ¢R Ž S r6   r%   )r*   ©rE   r4   r%   r&   Úvfunc³   s    zvectorize1.<locals>.vfuncc                   s”   t  | ¡rˆ| gˆ ¢R Ž S t  | ¡} ˆ| d gˆ ¢R Ž }t| ƒ}t|dt|ƒƒ}t j|f|d�}||d< td|ƒD ]}ˆ| | gˆ ¢R Ž ||< qr|S )Nr   Údtype©rI   r;   )r>   ÚisscalarÚasarrayÚlenÚgetattrÚtypeÚemptyÚrange)r*   Zy0r9   rI   ÚoutputÚirG   r%   r&   rH   ¶   s    

r%   )r4   rE   Úvec_funcrH   r%   rG   r&   Ú
vectorize1™   s    rU   çÛ"•“\ÿO>é2   Tr;   c	                 C  s¨   t |tƒs|f}t| ||d�}	tj}
tj}t|d |ƒ}t||d ƒD ]D}t|	||d|ƒd }t||
 ƒ}|}
||k s†||t|
ƒ k rF q qFt	 
d||f t¡ |
|fS )a�  
    Compute a definite integral using fixed-tolerance Gaussian quadrature.

    Integrate `func` from `a` to `b` using Gaussian quadrature
    with absolute tolerance `tol`.

    Parameters
    ----------
    func : function
        A Python function or method to integrate.
    a : float
        Lower limit of integration.
    b : float
        Upper limit of integration.
    args : tuple, optional
        Extra arguments to pass to function.
    tol, rtol : float, optional
        Iteration stops when error between last two iterates is less than
        `tol` OR the relative change is less than `rtol`.
    maxiter : int, optional
        Maximum order of Gaussian quadrature.
    vec_func : bool, optional
        True or False if func handles arrays as arguments (is
        a "vector" function). Default is True.
    miniter : int, optional
        Minimum order of Gaussian quadrature.

    Returns
    -------
    val : float
        Gaussian quadrature approximation (within tolerance) to integral.
    err : float
        Difference between last two estimates of the integral.

    See Also
    --------
    romberg : adaptive Romberg quadrature
    fixed_quad : fixed-order Gaussian quadrature
    quad : adaptive quadrature using QUADPACK
    dblquad : double integrals
    tplquad : triple integrals
    romb : integrator for sampled data
    simpson : integrator for sampled data
    cumulative_trapezoid : cumulative integration for sampled data
    ode : ODE integrator
    odeint : ODE integrator

    Examples
    --------
    >>> from scipy import integrate
    >>> f = lambda x: x**8
    >>> integrate.quadrature(f, 0.0, 1.0)
    (0.11111111111111106, 4.163336342344337e-17)
    >>> print(1/9.0)  # analytical result
    0.1111111111111111

    >>> integrate.quadrature(np.cos, 0.0, np.pi/2)
    (0.9999999999999536, 3.9611425250996035e-11)
    >>> np.sin(np.pi/2)-np.sin(0)  # analytical result
    1.0

    ©rT   r;   r%   r   z-maxiter (%d) exceeded. Latest difference = %e)Ú
isinstanceÚtuplerU   r>   ÚinfÚmaxrQ   r   ÚabsÚwarningsÚwarnr   )r4   rC   rD   rE   ÚtolÚrtolÚmaxiterrT   ZminiterrH   ÚvalÚerrr9   Znewvalr%   r%   r&   r   Æ   s"    @

þr   c                 C  s   t | ƒ}|||< t|ƒS r6   )ÚlistrZ   )ÚtrS   ÚvalueÚlr%   r%   r&   Útupleset  s    ri   c                 C  s   t | ||||d�S )z–An alias of `cumulative_trapezoid`.

    `cumtrapz` is kept for backwards compatibility. For new code, prefer
    `cumulative_trapezoid` instead.
    )r*   r+   r,   Úinitial)r   )r-   r*   r+   r,   rj   r%   r%   r&   r   "  s    r   c                 C  sZ  t  | ¡} |du r|}nŠt  |¡}|jdkrVt  |¡}dg| j }d||< | |¡}n,t|jƒt| jƒkrttdƒ‚nt j||d�}|j| | j| d kr¢tdƒ‚t| jƒ}tt	dƒf| |t	ddƒƒ}tt	dƒf| |t	ddƒƒ}	t j
|| | | |	   d |d�}
|du�rVt  |¡�s$tdƒ‚t|
jƒ}d||< t jt j|||
jd	�|
g|d�}
|
S )
aô  
    Cumulatively integrate y(x) using the composite trapezoidal rule.

    Parameters
    ----------
    y : array_like
        Values to integrate.
    x : array_like, optional
        The coordinate to integrate along. If None (default), use spacing `dx`
        between consecutive elements in `y`.
    dx : float, optional
        Spacing between elements of `y`. Only used if `x` is None.
    axis : int, optional
        Specifies the axis to cumulate. Default is -1 (last axis).
    initial : scalar, optional
        If given, insert this value at the beginning of the returned result.
        Typically this value should be 0. Default is None, which means no
        value at ``x[0]`` is returned and `res` has one element less than `y`
        along the axis of integration.

    Returns
    -------
    res : ndarray
        The result of cumulative integration of `y` along `axis`.
        If `initial` is None, the shape is such that the axis of integration
        has one less value than `y`. If `initial` is given, the shape is equal
        to that of `y`.

    See Also
    --------
    numpy.cumsum, numpy.cumprod
    quad : adaptive quadrature using QUADPACK
    romberg : adaptive Romberg quadrature
    quadrature : adaptive Gaussian quadrature
    fixed_quad : fixed-order Gaussian quadrature
    dblquad : double integrals
    tplquad : triple integrals
    romb : integrators for sampled data
    ode : ODE integrators
    odeint : ODE integrators

    Examples
    --------
    >>> from scipy import integrate
    >>> import matplotlib.pyplot as plt

    >>> x = np.linspace(-2, 2, num=20)
    >>> y = x
    >>> y_int = integrate.cumulative_trapezoid(y, x, initial=0)
    >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
    >>> plt.show()

    Nr;   r)   ú2If given, shape of x must be 1-D or the same as y.r=   ú7If given, length of x along axis must be the same as y.r<   z'`initial` parameter should be a scalar.rJ   )r>   rL   ÚndimÚdiffÚreshaperM   ÚshaperA   ri   ÚsliceZcumsumrK   re   ZconcatenateÚfullrI   )r-   r*   r+   r,   rj   Údrp   ÚndÚslice1Úslice2Úresr%   r%   r&   r   +  s6    6





"

ÿr   c              
   C  s°  t | jƒ}|d u rd}d}td ƒf| }t||t|||ƒƒ}	t||t|d |d |ƒƒ}
t||t|d |d |ƒƒ}|d u r°tj| |	 d| |
   | |  |d�}||d 9 }nütj||d�}t||t|||ƒƒ}t||t|d |d |ƒƒ}t || ¡}t || ¡}|| }|| }tj||t 	|¡|dkd�}|d | |	 d	tjd
|t 	|¡|dkd�  | |
 |tj||t 	|¡|dkd�   | | d	|    }tj||d�}|S )Nr   é   r;   é   r=   ç      @)ÚoutÚwhereg      @r<   r(   )
rM   rp   rq   ri   r>   rB   rn   Úfloat64Ztrue_divideZ
zeros_like)r-   ÚstartÚstopr*   r+   r,   rt   ÚstepÚ	slice_allÚslice0ru   rv   ÚresultÚhZsl0Zsl1Zh0Úh1ZhsumZhprodZh0divh1Útmpr%   r%   r&   Ú_basic_simpson‡  sH    
&
þÿþÿüø	r‡   Úavgc                 C  s   t | ||||d�S )zyAn alias of `simpson`.

    `simps` is kept for backwards compatibility. For new code, prefer
    `simpson` instead.
    )r*   r+   r,   Úeven)r   )r-   r*   r+   r,   r‰   r%   r%   r&   r   ®  s    r   c                 C  s&  t  | ¡} t| jƒ}| j| }|}|}d}	|dur®t  |¡}t|jƒdkr|dg| }
|jd |
|< |j}d}	| t|
ƒ¡}nt|jƒt| jƒkr˜tdƒ‚|j| |kr®tdƒ‚|d dk�rüd}d}tdƒf| }tdƒf| }|dvrðtd	ƒ‚|d
v �r^t||dƒ}t||dƒ}|du�r,|| ||  }|d| | | | |   7 }t	| d|d |||ƒ}|dv �rØt||dƒ}t||dƒ}|du�r¢|t|ƒ |t|ƒ  }|d| | | | |   7 }|t	| d|d |||ƒ7 }|dk�rò|d }|d }|| }nt	| d|d |||ƒ}|	�r"| |¡}|S )a$	  
    Integrate y(x) using samples along the given axis and the composite
    Simpson's rule. If x is None, spacing of dx is assumed.

    If there are an even number of samples, N, then there are an odd
    number of intervals (N-1), but Simpson's rule requires an even number
    of intervals. The parameter 'even' controls how this is handled.

    Parameters
    ----------
    y : array_like
        Array to be integrated.
    x : array_like, optional
        If given, the points at which `y` is sampled.
    dx : float, optional
        Spacing of integration points along axis of `x`. Only used when
        `x` is None. Default is 1.
    axis : int, optional
        Axis along which to integrate. Default is the last axis.
    even : str {'avg', 'first', 'last'}, optional
        'avg' : Average two results:1) use the first N-2 intervals with
                  a trapezoidal rule on the last interval and 2) use the last
                  N-2 intervals with a trapezoidal rule on the first interval.

        'first' : Use Simpson's rule for the first N-2 intervals with
                a trapezoidal rule on the last interval.

        'last' : Use Simpson's rule for the last N-2 intervals with a
               trapezoidal rule on the first interval.

    See Also
    --------
    quad : adaptive quadrature using QUADPACK
    romberg : adaptive Romberg quadrature
    quadrature : adaptive Gaussian quadrature
    fixed_quad : fixed-order Gaussian quadrature
    dblquad : double integrals
    tplquad : triple integrals
    romb : integrators for sampled data
    cumulative_trapezoid : cumulative integration for sampled data
    ode : ODE integrators
    odeint : ODE integrators

    Notes
    -----
    For an odd number of samples that are equally spaced the result is
    exact if the function is a polynomial of order 3 or less. If
    the samples are not equally spaced, then the result is exact only
    if the function is a polynomial of order 2 or less.

    Examples
    --------
    >>> from scipy import integrate
    >>> x = np.arange(0, 10)
    >>> y = np.arange(0, 10)

    >>> integrate.simpson(y, x)
    40.5

    >>> y = np.power(x, 3)
    >>> integrate.simpson(y, x)
    1642.5
    >>> integrate.quad(lambda x: x**3, 0, 9)[0]
    1640.25

    >>> integrate.simpson(y, x, even='first')
    1644.5

    r   Nr;   rk   rl   rx   g        )rˆ   ÚlastÚfirstz3Parameter 'even' must be 'avg', 'last', or 'first'.)rˆ   r‹   r)   éþÿÿÿç      à?é   )rˆ   rŠ   rˆ   r<   )
r>   rL   rM   rp   ro   rZ   rA   rq   ri   r‡   )r-   r*   r+   r,   r‰   rt   ÚNZlast_dxZfirst_dxZreturnshapeZshapexZ	saveshaperc   rƒ   ru   rv   r%   r%   r&   r   ·  s^    F











r   c              	   C  s†  t  | ¡} t| jƒ}| j| }|d }d}d}||k rH|dK }|d7 }q.||krXtdƒ‚i }	tdƒf| }
t|
|dƒ}t|
|dƒ}|t j|td� }| | | |  d | |	d< |
}| } }}td|d ƒD ]º}|dL }t||t|||ƒƒ}|dL }d	|	|d df || | j	|d
�   |	|df< td|d ƒD ]J}|	||d f }|||	|d |d f  dd| > d   |	||f< �q4|d }qÎ|�rzt  
|	d ¡�sªtdƒ nÐz|d }W n ttf�yÒ   d}Y n0 z|d }W n ttf�yü   d}Y n0 d||f }d}td| d¡dddd� t|d ƒD ]8}t|d ƒD ]}t||	||f  dd� �qBtƒ  �q2tdƒ tƒ  |	||f S )aÇ  
    Romberg integration using samples of a function.

    Parameters
    ----------
    y : array_like
        A vector of ``2**k + 1`` equally-spaced samples of a function.
    dx : float, optional
        The sample spacing. Default is 1.
    axis : int, optional
        The axis along which to integrate. Default is -1 (last axis).
    show : bool, optional
        When `y` is a single 1-D array, then if this argument is True
        print the table showing Richardson extrapolation from the
        samples. Default is False.

    Returns
    -------
    romb : ndarray
        The integrated result for `axis`.

    See Also
    --------
    quad : adaptive quadrature using QUADPACK
    romberg : adaptive Romberg quadrature
    quadrature : adaptive Gaussian quadrature
    fixed_quad : fixed-order Gaussian quadrature
    dblquad : double integrals
    tplquad : triple integrals
    simpson : integrators for sampled data
    cumulative_trapezoid : cumulative integration for sampled data
    ode : ODE integrators
    odeint : ODE integrators

    Examples
    --------
    >>> from scipy import integrate
    >>> x = np.arange(10, 14.25, 0.25)
    >>> y = np.arange(3, 12)

    >>> integrate.romb(y)
    56.0

    >>> y = np.sin(np.power(x, 2.5))
    >>> integrate.romb(y)
    -0.742561336672229

    >>> integrate.romb(y, show=True)
    Richardson Extrapolation Table for Romberg Integration
    ====================================================================
    -0.81576
    4.63862  6.45674
    -1.10581 -3.02062 -3.65245
    -2.57379 -3.06311 -3.06595 -3.05664
    -1.34093 -0.92997 -0.78776 -0.75160 -0.74256
    ====================================================================
    -0.742561336672229
    r;   r   z=Number of samples must be one plus a non-negative power of 2.Nr)   rJ   r<   )r   r   r�   r=   rx   zE*** Printing table only supported for integrals of a single data set.r:   é   z%%%d.%dfz6Richardson Extrapolation Table for Romberg IntegrationÚ éD   zD====================================================================Ú
)ÚsepÚendú ©r•   )r>   rL   rM   rp   rA   rq   ri   ÚfloatrQ   rB   rK   ÚprintÚ	TypeErrorÚ
IndexErrorÚcenter)r-   r+   r,   Úshowrt   ZNsampsZNintervr9   ÚkÚRr�   r‚   Zslicem1r„   Zslice_Rr~   r   r€   rS   ÚjÚprevZprecisÚwidthZformstrÚtitler%   r%   r&   r   4  sb    ;



08




r   c                 C  s’   |dkrt dƒ‚n||dkr6d| |d ƒ| |d ƒ  S |d }t|d |d  ƒ| }|d d|  }||t |¡  }tj| |ƒdd�}|S dS )aU  
    Perform part of the trapezoidal rule to integrate a function.
    Assume that we had called difftrap with all lower powers-of-2
    starting with 1. Calling difftrap only returns the summation
    of the new ordinates. It does _not_ multiply by the width
    of the trapezoids. This must be performed by the caller.
        'function' is the function to evaluate (must accept vector arguments).
        'interval' is a sequence with lower and upper limits
                   of integration.
        'numtraps' is the number of trapezoids to use (must be a
                   power-of-2).
    r   z#numtraps must be > 0 in difftrap().r;   r�   rx   r=   N)rA   r˜   r>   ÚarangerB   )ÚfunctionÚintervalZnumtrapsZnumtosumr„   ZloxZpointsÚsr%   r%   r&   Ú	_difftrap´  s    
r¨   c                 C  s   d| }|| |  |d  S )zƒ
    Compute the differences for the Romberg quadrature corrections.
    See Forman Acton's "Real Computing Made Real," p 143.
    g      @r(   r%   )rD   Úcrž   r†   r%   r%   r&   Ú_romberg_diffÎ  s    rª   c                 C  sæ   d }}t dt| ƒdd� t d|ƒ t dƒ t dd ƒ tt|ƒƒD ]b}t d	d
| |d |d  d|  f dd� t|d ƒD ]}t d|| |  dd� q€t dƒ qDt dƒ t d|| | dd� t dd
t|ƒd  d dƒ d S )Nr   zRomberg integration ofr–   r—   Úfromr‘   z%6s %9s %9s)ZStepsZStepSizeZResultsz%6d %9frx   r;   r<   z%9fzThe final result isÚafterzfunction evaluations.)r™   ÚreprrQ   rM   )r¥   r¦   ÚresmatrS   r    r%   r%   r&   Ú_printresmat×  s    
,
r¯   ç`sáÓbÈO>é
   c	              	   C  sL  t  |¡st  |¡rtdƒ‚t| ||d�}	d}
||g}|| }t|	||
ƒ}|| }|gg}t j}|d }td|d ƒD ]ª}|
d9 }
|t|	||
ƒ7 }|| |
 g}t|ƒD ]"}| t|| || |d ƒ¡ q¨|| }||d  }|rî| |¡ t	|| ƒ}||k �s||t	|ƒ k �r �q6|}qvt
 d||f t¡ |�rHt|	||ƒ |S )a~
  
    Romberg integration of a callable function or method.

    Returns the integral of `function` (a function of one variable)
    over the interval (`a`, `b`).

    If `show` is 1, the triangular array of the intermediate results
    will be printed. If `vec_func` is True (default is False), then
    `function` is assumed to support vector arguments.

    Parameters
    ----------
    function : callable
        Function to be integrated.
    a : float
        Lower limit of integration.
    b : float
        Upper limit of integration.

    Returns
    -------
    results : float
        Result of the integration.

    Other Parameters
    ----------------
    args : tuple, optional
        Extra arguments to pass to function. Each element of `args` will
        be passed as a single argument to `func`. Default is to pass no
        extra arguments.
    tol, rtol : float, optional
        The desired absolute and relative tolerances. Defaults are 1.48e-8.
    show : bool, optional
        Whether to print the results. Default is False.
    divmax : int, optional
        Maximum order of extrapolation. Default is 10.
    vec_func : bool, optional
        Whether `func` handles arrays as arguments (i.e., whether it is a
        "vector" function). Default is False.

    See Also
    --------
    fixed_quad : Fixed-order Gaussian quadrature.
    quad : Adaptive quadrature using QUADPACK.
    dblquad : Double integrals.
    tplquad : Triple integrals.
    romb : Integrators for sampled data.
    simpson : Integrators for sampled data.
    cumulative_trapezoid : Cumulative integration for sampled data.
    ode : ODE integrator.
    odeint : ODE integrator.

    References
    ----------
    .. [1] 'Romberg's method' https://en.wikipedia.org/wiki/Romberg%27s_method

    Examples
    --------
    Integrate a gaussian from 0 to 1 and compare to the error function.

    >>> from scipy import integrate
    >>> from scipy.special import erf
    >>> gaussian = lambda x: 1/np.sqrt(np.pi) * np.exp(-x**2)
    >>> result = integrate.romberg(gaussian, 0, 1, show=True)
    Romberg integration of <function vfunc at ...> from [0, 1]

    ::

       Steps  StepSize  Results
           1  1.000000  0.385872
           2  0.500000  0.412631  0.421551
           4  0.250000  0.419184  0.421368  0.421356
           8  0.125000  0.420810  0.421352  0.421350  0.421350
          16  0.062500  0.421215  0.421350  0.421350  0.421350  0.421350
          32  0.031250  0.421317  0.421350  0.421350  0.421350  0.421350  0.421350

    The final result is 0.421350396475 after 33 function evaluations.

    >>> print("%g %g" % (2*result, erf(1)))
    0.842701 0.842701

    z5Romberg integration only available for finite limits.rX   r;   r   rx   z,divmax (%d) exceeded. Latest difference = %e)r>   r@   rA   rU   r¨   r[   rQ   Úappendrª   r]   r^   r_   r   r¯   )r¥   rC   rD   rE   r`   ra   r�   ZdivmaxrT   rH   r9   r¦   ZintrangeZordsumrƒ   r®   rd   Zlast_rowrS   Úrowrž   Z
lastresultr%   r%   r&   r   è  s@    T 

þr   rx   é   rŽ   )r;   ry   r;   éZ   r�   )r;   rŽ   rŽ   r;   éýÿÿÿéP   é-   )é   é    r´   rº   r¹   iøÿÿÿi±  i   )é   éK   rW   rW   r¼   r»   iíþÿÿi@/  éŒ   )é)   éØ   é   i  rÀ   r¿   r¾   i÷ÿÿÿix  r¹   i€C  )éï  éù  é+  é­  rÄ   rÃ   rÂ   rÁ   i	àÿÿi é ry   i_7  )	éÝ  é   é`üÿÿé )  iDîÿÿrÈ   rÇ   rÆ   rÅ   iÀöÿÿi?# é	   i ^ )
é)  é}=  é8  é�K  é’  rÎ   rÍ   rÌ   rË   rÊ   iÁíÿÿi  ip‘ )éÃ>  é<Ÿ ésBÿÿé( é:üÿih… rÓ   rÒ   rÑ   rÐ   rÏ   iiºõÿià0¾	é   i è0)éI"! éËÉÍ é›Îÿé½í€éj•mÿé¾iì rÚ   rÙ   rØ   r×   rÖ   rÕ   lýÿÿÿß&	 l    7Ý iR0P )é«Ò é@— éè7Œÿé@!é!Nîüé€d7ipRÄúrà   rß   rÞ   rÝ   rÜ   rÛ   i<ôÿÿic] é   l    `5]v)ì   v[O ì   =H/54 ìýÿÿÿž+w ì   "…-‘ ìýÿÿÿMp:� ì   £{•>À ìýÿÿÿ$MY( rè   rç   ræ   rå   rä   rã   râ   lýÿÿÿí`«: l    @	Al   @d@* )éiû`épÌ`*éo¼Òì   àFg! ìýÿÿÿófÅ ì   �\ a ìýÿÿÿ¥LüR l   @`¯ rï   rî   rí   rì   rë   rê   ré   lýÿÿÿ±xí= l   €7-¤)r;   rx   rŽ   ry   r:   é   r¹   r�   rÉ   r±   rÔ   r´   rá   é   c                 C  sú  z<t | ƒd }|r"t |d ¡} nt t | ¡dk¡r:d}W n( tyd   | }t |d ¡} d}Y n0 |rª|tv rªt| \}}}}}|tj|td� | }|t|ƒ| fS | d dksÂ| d |krÊt	dƒ‚| t|ƒ }	d|	 d }
t |d ¡}|
|dd…tj
f  }tj |¡}tdƒD ]}d| | |¡ |¡ }�qd|ddd… d  }|dd…ddd…f  |¡|d  }|d dk�rž|�rž||d	  }|d }n||d  }|d }|t |	| |¡ }|d }|t |¡ t|ƒ }t |¡}||| fS )
aÇ  
    Return weights and error coefficient for Newton-Cotes integration.

    Suppose we have (N+1) samples of f at the positions
    x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the
    integral between x_0 and x_N is:

    :math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i)
    + B_N (\Delta x)^{N+2} f^{N+1} (\xi)`

    where :math:`\xi \in [x_0,x_N]`
    and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing.

    If the samples are equally-spaced and N is even, then the error
    term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`.

    Parameters
    ----------
    rn : int
        The integer order for equally-spaced data or the relative positions of
        the samples with the first sample at 0 and the last at N, where N+1 is
        the length of `rn`. N is the order of the Newton-Cotes integration.
    equal : int, optional
        Set to 1 to enforce equally spaced data.

    Returns
    -------
    an : ndarray
        1-D array of weights to apply to the function at the provided sample
        positions.
    B : float
        Error coefficient.

    Examples
    --------
    Compute the integral of sin(x) in [0, :math:`\pi`]:

    >>> from scipy.integrate import newton_cotes
    >>> def f(x):
    ...     return np.sin(x)
    >>> a = 0
    >>> b = np.pi
    >>> exact = 2
    >>> for N in [2, 4, 6, 8, 10]:
    ...     x = np.linspace(a, b, N + 1)
    ...     an, B = newton_cotes(N, 1)
    ...     dx = (b - a) / N
    ...     quad = dx * np.sum(an * f(x))
    ...     error = abs(quad - exact)
    ...     print('{:2d}  {:10.9f}  {:.5e}'.format(N, quad, error))
    ...
     2   2.094395102   9.43951e-02
     4   1.998570732   1.42927e-03
     6   2.000017814   1.78136e-05
     8   1.999999835   1.64725e-07
    10   2.000000001   1.14677e-09

    Notes
    -----
    Normally, the Newton-Cotes rules are used on smaller integration
    regions and a composite rule is used to return the total integral.

    r;   rJ   r   r)   z1The sample positions must start at 0 and end at Nrx   Nr<   rz   )rM   r>   r¤   Úallrn   Ú	ExceptionÚ_builtincoeffsÚarrayr˜   rA   ZnewaxisZlinalgÚinvrQ   ÚdotÚmathÚlogr   Úexp)ZrnÚequalr�   ÚnaÚdaÚviÚnbÚdbZanÚyiZtiZnvecÚCZCinvrS   ZvecZaiÚBNÚpowerÚp1Zfacr%   r%   r&   r   �  sF    @
$

r   )Nr(   r)   )r%   r:   )r%   F)r%   rV   rV   rW   Tr;   )Nr(   r)   N)Nr(   r)   N)Nr(   r)   rˆ   )Nr(   r)   rˆ   )r(   r)   F)r%   r°   r°   Fr±   F)r   )1Ú
__future__r   Útypingr   r   r   r   r   r   r    Únumpyr>   rø   r   r^   r	   r   Zscipy.specialr
   r   Ú__all__r'   Ú__doc__ÚreplaceÚWarningr   Ztyping_extensionsr0   r1   r7   r8   Údictr2   r   rU   r   ri   r   r   r‡   r   r   r   r¨   rª   r¯   r   rô   r   r%   r%   r%   r&   Ú<module>   sœ    	ÿ
	

F
-  ÿ
T
	
\'
	
}
 	  ÿ
 
ÿ
ÿ
þ
þ
þ
û
üå#