
    (ph#                        S SK rS SKJr  S SKrS SKrS SKJr  S SK	J
r
  S SKJr  S SKJrJr  S SKJr  S SKJrJrJr  / SQrSeS jrS r\" 5       \l        SfS jrS rSgS jrS rShS	S
S.S jjrS\R>                  S\R>                  S\
\R>                  \R>                  /\R>                  4   S\R>                  4S jr S\R>                  S\R>                  S\R>                  4S jr!S\R>                  S\R>                  S\R>                  4S jr"S\RF                  S\R>                  4S jr$SS	S
SS.S jr%SiS  jr&S!S"S!S!/S
S#4S!S$/ S%QS
S&4S$S'/ S(QS)S*4S"S+/ S,QS-S.4SS// S0QS1S24S!S3/ S4QS5S64S7S8/ S9QS:S;4S<S=/ S>QS?S@4SASB/ SCQSDSE4SSF/ SGQSHSI4SJSK/ SLQSMSN4S!SO/ SPQSQSR4SSST/ SUQSVSW4S7SX/ SYQSZS[4S\.r'SjS] jr(S^ r)\" S_S`Sa/5      r*S'SbSSSc.Sd jr+g)k    N)
namedtuple)Callable)roots_legendre)gammaln	logsumexp)
_rng_spawn)_asarrayarray_namespacexp_broadcast_promote)
fixed_quadromb	trapezoidsimpsoncumulative_trapezoidnewton_cotesqmc_quadcumulative_simpson      ?c           	         [        U 5      n[        XSS9n [        U SUS9S   R                  nU R                  n[        S5      /U-  n[        S5      /U-  n[        SS5      Xs'   [        SS5      X'   Uc  Un	O[        XSS9nUR                  S:X  a-  USS USS -
  n	S/U-  n
[        S5      X'   U	[        U
5         n	O8UR                  XR                  5      nU[        U5         U[        U5         -
  n	 UR                  X[        U5         U [        U5         -   -  S-  X5S	9nU$ ! [         aV    UR                  U	5      n	UR                  U 5      n UR                  X[        U5         U [        U5         -   -  S-  X5S	9n U$ f = f)
ay  
Integrate along the given axis using the composite trapezoidal rule.

If `x` is provided, the integration happens in sequence along its
elements - they are not sorted.

Integrate `y` (`x`) along each 1d slice on the given axis, compute
:math:`\int y(x) dx`.
When `x` is specified, this integrates along the parametric curve,
computing :math:`\int_t y(t) dt =
\int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.

Parameters
----------
y : array_like
    Input array to integrate.
x : array_like, optional
    The sample points corresponding to the `y` values. If `x` is None,
    the sample points are assumed to be evenly spaced `dx` apart. The
    default is None.
dx : scalar, optional
    The spacing between sample points when `x` is None. The default is 1.
axis : int, optional
    The axis along which to integrate. The default is the last axis.

Returns
-------
trapezoid : float or ndarray
    Definite integral of `y` = n-dimensional array as approximated along
    a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
    then the result is a float. If `n` is greater than 1, then the result
    is an `n`-1 dimensional array.

See Also
--------
cumulative_trapezoid, simpson, romb

Notes
-----
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
will be taken from `y` array, by default x-axis distances between
points will be 1.0, alternatively they can be provided with `x` array
or with `dx` scalar.  Return value will be equal to combined area under
the red lines.

References
----------
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule

.. [2] Illustration image:
       https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png

Examples
--------
Use the trapezoidal rule on evenly spaced points:

>>> import numpy as np
>>> from scipy import integrate
>>> integrate.trapezoid([1, 2, 3])
4.0

The spacing between sample points can be selected by either the
``x`` or ``dx`` arguments:

>>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
8.0
>>> integrate.trapezoid([1, 2, 3], dx=2)
8.0

Using a decreasing ``x`` corresponds to integrating in reverse:

>>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
-8.0

More generally ``x`` is used to integrate along a parametric curve. We can
estimate the integral :math:`\int_0^1 x^2 = 1/3` using:

>>> x = np.linspace(0, 1, num=50)
>>> y = x**2
>>> integrate.trapezoid(y, x)
0.33340274885464394

Or estimate the area of a circle, noting we repeat the sample which closes
the curve:

>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
>>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
3.141571941375841

``trapezoid`` can be applied along a specified axis to do multiple
computations in one call:

>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> integrate.trapezoid(a, axis=0)
array([1.5, 2.5, 3.5])
>>> integrate.trapezoid(a, axis=1)
array([2.,  8.])
T)xpsubok)force_floatingr   r   N   r          @)axisdtype)r
   r	   r   r   ndimslicetuplebroadcast_toshapesum
ValueErrorasarray)yxdxr   r   result_dtypendslice1slice2dslice3rets               N/var/www/html/venv/lib/python3.13/site-packages/scipy/integrate/_quadrature.pyr   r      s   L 
	B&A ($2FqIOOL	
BDk]2FDk]2FD>FLr?FLyQT*66Q;!"#2AVb[F ;FL%- A 77+A%- 1U6]#33A
ff5=!AeFm$445;  
 J  
JJqMJJqMff5=!AeFm$445;  
 J
s   :0D, ,AFFc                     U [         R                  ;   a  [         R                  U    $ [        U 5      [         R                  U '   [         R                  U    $ )zL
Cache roots_legendre results to speed up calls of the fixed_quad
function.
)_cached_roots_legendrecacher   )ns    r0   r2   r2      sK    
 	"(((%++A..&4Q&7  #!''**       c                 :   [        U5      u  pV[        R                  " U5      n[        R                  " U5      (       d  [        R                  " U5      (       a  [	        S5      eX!-
  US-   -  S-  U-   nX!-
  S-  [        R
                  " X`" U/UQ76 -  SS9-  S4$ )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
romb : integrators for sampled data
simpson : integrators for sampled data
cumulative_trapezoid : cumulative integration for sampled data

Examples
--------
>>> from scipy import integrate
>>> import numpy as np
>>> 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   r   r   N)r2   nprealisinfr$   r#   )funcabargsr4   r'   wr&   s           r0   r   r      s    t "!$DA

A	xx{{bhhqkk * + 	+	
qsC!AC9rvvaQ.R88$>>r5   c                 6    [        U 5      nX#U'   [        U5      $ N)listr    )tivaluels       r0   tuplesetrH      s    QAaD8Or5   c                 <   [         R                  " U 5      n U R                  U   S:X  a  [        S5      eUc  UnO[         R                  " U5      nUR                  S:X  a<  [         R
                  " U5      nS/U R                  -  nSXc'   UR                  U5      nOK[        UR                  5      [        U R                  5      :w  a  [        S5      e[         R
                  " XS9nUR                  U   U R                  U   S-
  :w  a  [        S5      e[        U R                  5      n[        [        S5      4U-  U[        SS5      5      n[        [        S5      4U-  U[        SS5      5      n	[         R                  " XPU   X	   -   -  S	-  US9n
Ub  US:w  a  [        S
5      e[         R                  " U5      (       d  [        S5      e[        U
R                  5      nSXc'   [         R                  " [         R                  " XdU
R                  S9U
/US9n
U
$ )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.
    0 or None are the only values accepted. Default is None, which means
    `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
cumulative_simpson : cumulative integration using Simpson's 1/3 rule
quad : adaptive quadrature using QUADPACK
fixed_quad : fixed-order Gaussian quadrature
dblquad : double integrals
tplquad : triple integrals
romb : integrators for sampled data

Examples
--------
>>> from scipy import integrate
>>> import numpy as np
>>> 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()

r   z,At least one point is required along `axis`.Nr   r   2If given, shape of x must be 1-D or the same as y.r8   7If given, length of x along axis must be the same as y.r   z `initial` must be `None` or `0`.z'`initial` parameter should be a scalar.r   )r9   r%   r"   r$   r   diffreshapelenrH   r   cumsumisscalarrC   concatenatefullr   )r&   r'   r(   r   initialr-   r"   r*   r+   r,   ress              r0   r   r      s   f 	

1Awwt}GHHyJJqM66Q;
AC!&&LEEK		% A\S\) * + + %A774=AGGDMA-- * + + 
QWWBuT{nR'uQ~>FuT{nR'uT2?F
))A6QY./#5D
ACa<?@@{{7##FGGSYYnnbggeCIIFL"&( Jr5   c                    [        U R                  5      nUc  SnSn[        S 5      4U-  n[        X[        XU5      5      n	[        X[        US-   US-   U5      5      n
[        X[        US-   US-   U5      5      nUc-  [        R
                  " X	   SX
   -  -   X   -   US9nXS-  -  nU$ [        R                  " X5S9n[        X[        XU5      5      n[        X[        US-   US-   U5      5      nX   R                  [        SS9nX   R                  [        SS9nUU-   nUU-  n[        R                  " UU[        R                  " U5      US:g  S	9nUS
-  X	   S[        R                  " SU[        R                  " U5      US:g  S	9-
  -  X
   U[        R                  " UU[        R                  " U5      US:g  S	9-  -  -   X   SU-
  -  -   -  n[        R
                  " UUS9nU$ )Nr      r   g      @r8         @Fcopyoutwhereg      @r   r   )rO   r"   r   rH   r9   r#   rM   astypefloattrue_divide
zeros_like)r&   startstopr'   r(   r   r*   step	slice_allslice0r+   r,   resulthsl0sl1h0h1hsumhprodh0divh1tmps                         r0   _basic_simpsonrq   X  s   	QWWB}Dtr!IiuU$'?@FiuU1Wd1fd'CDFiuU1Wd1fd'CDFy	C	M1AI=DIs(, M% GGA!ye4(@AyeAgtAvt(DEV]]5u]-V]]5u]-BwR..RR]]2->bAgN3h!)W46MM'4J6=l"D DE )t')~~dE:<--:M<AQJ(H(H I	I )sW}56 7 $'Mr5   )r(   r   c          	         [         R                  " U 5      n [        U R                  5      nU R                  U   nUnSnUb  [         R                  " U5      n[        UR                  5      S:X  a@  S/U-  nUR                  S   X'   UR                  n	SnUR	                  [        U5      5      nO7[        UR                  5      [        U R                  5      :w  a  [        S5      eUR                  U   U:w  a  [        S5      eUS-  S:X  GaC  Sn
Sn[        S5      4U-  nUS:X  a8  [        XS5      n[        XS	5      nUb	  X   X   -
  nU
S
U-  X   X   -   -  -  n
GO[        U SUS-
  XU5      n[        XS5      n[        XS	5      n[        XS5      n[         R                  " X"/[         R                  S9nUb  [        X[        S	SS5      5      n[        X[        SSS5      5      n[         R                  " [         R                  " XS95      n[         R                  " UU   US9[         R                  " UU   US9/nSUS   S-  -  SUS   -  US   -  -   nSUS   US   -   -  n[         R                  " UU[         R                  " U5      US:g  S9nUS   S-  SUS   -  US   -  -   nSUS   -  n[         R                  " UU[         R                  " U5      US:g  S9nSUS   S-  -  nSUS   -  US   US   -   -  n[         R                  " UU[         R                  " U5      US:g  S9nUUX   -  UX   -  -   UX   -  -
  -  nX-  nO[        U SUS-
  XU5      nU(       a  UR	                  W	5      nU$ )ak  
Integrate y(x) using samples along the given axis and the composite
Simpson's rule. If x is None, spacing of dx is assumed.

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.

Returns
-------
float
    The estimated integral computed with the composite Simpson's rule.

See Also
--------
quad : adaptive quadrature using QUADPACK
fixed_quad : fixed-order Gaussian quadrature
dblquad : double integrals
tplquad : triple integrals
romb : integrators for sampled data
cumulative_trapezoid : cumulative integration for sampled data
cumulative_simpson : cumulative integration using Simpson's 1/3 rule

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.

References
----------
.. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
       MS Excel and Irregularly-spaced Data. Journal of Mathematical
       Sciences and Mathematics Education. 12 (2): 1-9

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

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

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

r   Nr   rJ   rK   rW   g        r         ?   rL   r8      r[   rX   )r9   r%   rO   r"   rN   r    r$   r   rH   rq   float64rM   squeezer`   ra   )r&   r'   r(   r   r*   Nlast_dxreturnshapeshapex	saveshapevalrg   re   r+   r,   r.   rh   hm2hm1diffsnumdenalphabetaetas                            r0   r   r   }  s   | 	

1A	QWWB	AGK}JJqMqww<1S2XF771:FLIK		%-(A\S\) * + +774=A * + + 	1uz4[NR'	6 ir2Fir2F})ai/3=AI	$9::C $Aq!A#qd;Fir2Fir2Fir2F

B82::6A}yb"a0@Ayb$0BC

2771#89ZZc
6ZZc
68 adai-!ad(QqT/1Cqtad{#CNNMM#&Qh	E A$!)cAaDj1Q4//Cad(C>>MM#&Qh	D adai-Cad(adQqTk*C..MM#&Qh	C eAIoQY6QYFFF1ac1$7IIi Mr5   r&   r(   integration_funcreturnc                 J   U" X5      nU" U SSSS24   USSSS24   5      SSSS24   n[        UR                  5      nUS==   S-  ss'   [        R                  " U5      nUSSSS24   USSSS24'   USSSS24   USSSS24'   US   US'   [        R                  " USS9nU$ )zCalculate cumulative sum of Simpson integrals.
Takes as input the integration function to be used. 
The integration_func is assumed to return the cumulative sum using
composite Simpson's rule. Assumes the axis of summation is -1.
.Nr   r   rW   ).r   r8   )rC   r"   r9   emptyrP   )r&   r(   r   sub_integrals_h1sub_integrals_h2r"   sub_integralsrU   s           r0   #_cumulatively_sum_simpson_integralsr     s     (.'#tt)bddmDS$B$YO!''(E	"INIHHUOM 0cc :M#u1u*/SqS9M#qt!t) .g6M'
))M
+CJr5   c                 ~    USSS24   nU SSS24   nU SSS24   nU SSS24   nUS-  SU-  S	-  SU-  -   US	-  -
  -  $ )
zCalculate the Simpson integrals for all h1 intervals assuming equal interval
widths. The function can also be used to calculate the integral for all
h2 intervals by reversing the inputs, `y` and `dx`.
.Nr   rs   r   rW   ru   r6       )r&   r(   r-   f1f2f3s         r0   #_cumulative_simpson_equal_intervalsr   7  sq    
 	38A	
38B	
3"9B	
37B q5AFQJR'"q&011r5   c                     USSS24   nUSSS24   nU SSS24   nU SSS24   nU SSS24   nX#-   nX'-  nX#-  n	X-  n
SU-
  nSU
-   U-   nU
* nUS-  X-  X-  -   X-  -   -  $ )	zCalculate the Simpson integrals for all h1 intervals assuming unequal interval
widths. The function can also be used to calculate the integral for all
h2 intervals by reversing the inputs, `y` and `dx`.
.Nr   r   rs   rW   ru   rw   r   )r&   r(   x21x32r   r   r   x31x21_x31x21_x32x21x21_x31x32coeff1coeff2coeff3s                 r0   %_cumulative_simpson_unequal_intervalsr   E  s    
 S#2#X,C
S!"W+C	
38B	
3"9B	
37B
)CgGgG%M [F(F^Fq5FI	)FI566r5   arrc                     [         R                  " U 5      n [         R                  " U R                  [         R                  5      (       a  U R                  [        SS9n U $ )NFrY   )r9   r%   
issubdtyper   integerr^   r_   )r   s    r0   _ensure_float_arrayr   ]  s?    
**S/C	}}SYY

++jjUj+Jr5   )r'   r(   r   rT   c                l   [        U 5      n U nU R                  n [        R                  " XS5      n U R                  S   S:  a$  [        XQX#SS9n	[        R                  " XS5      n	GOtUb  [        U5      nSnUR                  U:X  d,  UR
                  S	:X  a  [        U5      Xc   :X  d  [        U5      eUR
                  S	:X  a   [        R                  " XR                  5      O[        R                  " XS5      n[        R                  " USS
9n[        R                  " US:*  5      (       a  [        S5      e[        X[        5      n	O[        U5      n[        XcXc   S	-
  5      n
[        XcS	5      nSnUR
                  S:X  d  UR                  U:X  d  [        U5      e[        R                  " X*5      n[        R                  " X#S5      n[        X[        5      n	Ub  [        U5      n[        XcS	5      nSnUR
                  S:X  d  UR                  U:X  d  [        U5      e[        R                  " XL5      n[        R                  " XCS5      nX-  n	[        R                   " XI4SS
9n	[        R                  " U	SU5      n	U	$ ! [         a$  nSU SU R
                   S3n[        U5      UeSnAff = f)a  
Cumulatively integrate y(x) using the composite Simpson's 1/3 rule.
The integral of the samples at every point is calculated by assuming a 
quadratic relationship between each point and the two adjacent points.

Parameters
----------
y : array_like
    Values to integrate. Requires at least one point along `axis`. If two or fewer
    points are provided along `axis`, Simpson's integration is not possible and the
    result is calculated with `cumulative_trapezoid`.
x : array_like, optional
    The coordinate to integrate along. Must have the same shape as `y` or
    must be 1D with the same length as `y` along `axis`. `x` must also be
    strictly increasing along `axis`.
    If `x` is None (default), integration is performed using spacing `dx`
    between consecutive elements in `y`.
dx : scalar or array_like, optional
    Spacing between elements of `y`. Only used if `x` is None. Can either 
    be a float, or an array with the same shape as `y`, but of length one along
    `axis`. Default is 1.0.
axis : int, optional
    Specifies the axis to integrate along. Default is -1 (last axis).
initial : scalar or array_like, optional
    If given, insert this value at the beginning of the returned result,
    and add it to the rest of the result. 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. Can either be a float, or an array with
    the same shape as `y`, but of length one along `axis`.

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
cumulative_trapezoid : cumulative integration using the composite 
    trapezoidal rule
simpson : integrator for sampled data using the Composite Simpson's Rule

Notes
-----

.. versionadded:: 1.12.0

The composite Simpson's 1/3 method can be used to approximate the definite 
integral of a sampled input function :math:`y(x)` [1]_. The method assumes 
a quadratic relationship over the interval containing any three consecutive
sampled points.

Consider three consecutive points: 
:math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`.

Assuming a quadratic relationship over the three points, the integral over
the subinterval between :math:`x_1` and :math:`x_2` is given by formula
(8) of [2]_:

.. math::
    \int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\
    \left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \
    \left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \
    \frac{x_2-x_1}{x_3-x_1}\right\} y_2\\
    - \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right]

The integral between :math:`x_2` and :math:`x_3` is given by swapping
appearances of :math:`x_1` and :math:`x_3`. The integral is estimated
separately for each subinterval and then cumulatively summed to obtain
the final result.

For samples that are equally spaced, the result is exact if the function
is a polynomial of order three or less [1]_ and the number of subintervals
is even. Otherwise, the integral is exact for polynomials of order two or
less. 

References
----------
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule
.. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
        MS Excel and Irregularly-spaced Data. Journal of Mathematical
        Sciences and Mathematics Education. 12 (2): 1-9

Examples
--------
>>> from scipy import integrate
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-2, 2, num=20)
>>> y = x**2
>>> y_int = integrate.cumulative_simpson(y, x=x, initial=0)
>>> fig, ax = plt.subplots()
>>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-')
>>> ax.grid()
>>> plt.show()

The output of `cumulative_simpson` is similar to that of iteratively
calling `simpson` with successively higher upper limits of integration, but
not identical.

>>> def cumulative_simpson_reference(y, x):
...     return np.asarray([integrate.simpson(y[:i], x=x[:i])
...                        for i in range(2, len(y) + 1)])
>>>
>>> rng = np.random.default_rng(354673834679465)
>>> x, y = rng.random(size=(2, 10))
>>> x.sort()
>>>
>>> res = integrate.cumulative_simpson(y, x=x)
>>> ref = cumulative_simpson_reference(y, x)
>>> equal = np.abs(res - ref) < 1e-15
>>> equal  # not equal when `simpson` has even number of subintervals
array([False,  True, False,  True, False,  True, False,  True,  True])

This is expected: because `cumulative_simpson` has access to more
information than `simpson`, it can typically produce more accurate
estimates of the underlying integral over subintervals.

r   z`axis=z$` is not valid for `y` with `y.ndim=z`.Nru   )r(   r   rT   z_If given, shape of `x` must be the same as `y` or 1-D with the same length as `y` along `axis`.r   r8   r   z$Input x must be strictly increasing.zkIf provided, `dx` must either be a scalar or have the same shape as `y` but with only 1 point along `axis`.zpIf provided, `initial` must either be a scalar or have the same shape as `y` but with only 1 point along `axis`.)r   r"   r9   swapaxes
IndexErrorr   r$   r   rO   r!   rM   anyr   r   rH   r   rR   )r&   r'   r(   r   rT   
original_yoriginal_shapeemessagerU   final_dx_shapealt_input_dx_shapealt_initial_input_shapes                r0   r   r   d  sf   v 	AA JWWN)KK$ 	wwr{Q":RDQkk#R(	
":>)FFaKCFn.B$BW%%+,66Q;BOOAww'BKKQS<TWWQR 66"'??CDD18

 !$!.8Lq8PQ%nA>F1,> >W%%__R0[[2&16
 %g."*>"CK!W]]6M%MW%%//'C++gR0nng^"5
++c2t
$CJg  )4& DQVVHBO!q()s   J 
J3J..J3Fc           
         [         R                  " U 5      n [        U R                  5      nU R                  U   nUS-
  nSnSnXv:  a  US-  nUS-  nXv:  a  M  Xv:w  a  [	        S5      e0 n	[        S5      4U-  n
[        XS5      n[        XS5      nU[         R                  " U[        S9-  nX   X   -   S-  U-  U	S'   U
nU=n=nn[        SUS-   5       H  nUS-  n[        X[        UUU5      5      nUS-  nS	U	US-
  S4   XU   R                  US
9-  -   -  U	US4'   [        SUS-   5       H1  nU	UUS-
  4   nUUU	US-
  US-
  4   -
  SSU-  -  S-
  -  -   U	UU4'   M3     US-  nM     U(       a  [         R                  " U	S   5      (       d  [        S5        O US   n US   nSUU4-  nSn[        US[        U5      -  SSS9  [        US-   5       H4  n[        US-   5       H  n[        UU	UU4   -  SS9  M     [        5         M6     [        S[        U5      -  5        XU4   $ ! [        [        4 a    Sn Nf = f! [        [        4 a    Sn Nf = f)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
fixed_quad : fixed-order Gaussian quadrature
dblquad : double integrals
tplquad : triple integrals
simpson : integrators for sampled data
cumulative_trapezoid : cumulative integration for sampled data

Examples
--------
>>> from scipy import integrate
>>> import numpy as np
>>> 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  # may vary

r   r   z=Number of samples must be one plus a non-negative power of 2.Nr   rL   r   )r   r   rt   r8   rW   zE*** Printing table only supported for integrals of a single data set.r6      z%%%d.%dfz6Richardson Extrapolation Table for Romberg Integration=
)sepend )r   )r9   r%   rO   r"   r$   r   rH   r_   ranger#   rQ   print	TypeErrorr   )r&   r(   r   showr*   NsampsNintervr4   kRre   rf   slicem1rh   slice_Rrb   rc   rd   rE   jprevpreciswidthformstrtitles                            r0   r   r     s   r 	

1A	QWWBWWT]FQhG	A	A
+	a	Q + 	| 4 5 	5 	At#Iiq)Fy+G"**Ru--AQZ',Q.AfIG!!E!D41ac]!7%tT*BC
AaC8q7T)B'BBC1a&	q!A#Aa1X;DQ!QqSz] 2ac
A~FFAq!fI  	
S  {{1V9%% + ,aQ !E6?2GLE%s5z)t>1Q3ZqsA'Aq!fI-37 $   #E
"#V9! z*  z* s$   "H1 (I	 1II	IIr   rW      ru   )r   r   r   Z   r   )r   ru   ru   r   rv   P   -   )       r   r   r   ii  i   )   K   2   r   r   r   ii@/     ))         i  r   r   r   iix  r   iC  )    +    r   r   r   r   i	i  r   i_7  )	     ` )  iDr   r   r   r   ii?# 	   i ^ )
)  }=  8  K    r   r   r   r   r   ii  ip )>  < sB( :ih r   r   r   r   r   iii0	   i 0)I"!  jmi r   r   r   r   r   r   l&	 l    7 iR0P ) @ 7@!!Nd7ipRr   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 LR l   @` r  r  r  r  r   r   r   lx= l   7-)r   rW   ru   r   r6   rw   r   r   r   
   r   r   r      c                     [        U 5      S-
  nU(       a  [        R                  " US-   5      n O4[        R                  " [        R                  " U 5      S:H  5      (       a  SnU(       aF  U[        ;   a<  [        U   u  p4pVnU[        R                  " U[        S9-  U-  nU[        U5      U-  4$ U S   S:w  d	  U S   U:w  a  [        S5      eU [        U5      -  n	SU	-  S-
  n
[        R                  " US-   5      nXSS2[        R                  4   -  n[        R                  R                  U5      n[        S5       H)  nSU-  UR                  U5      R                  U5      -
  nM+     SUSSS2   S-   -  nUSS2SSS24   R                  U5      US-  -  nUS-  S:X  a  U(       a  X"S	-   -  nUS-   nOX"S-   -  nUS-   nU[        R                  " U	U-  U5      -
  nUS-   nU[        R                   " U5      -  [#        U5      -
  n[        R$                  " U5      nUUU-  4$ ! [
         a!    U n[        R                  " US-   5      n Sn GNf = f)
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.

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

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

>>> from scipy.integrate import newton_cotes
>>> import numpy as np
>>> 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

r   rL   r   r   z1The sample positions must start at 0 and end at NrW   Nr   rX   )rO   r9   arangeallrM   	Exception_builtincoeffsarrayr_   r$   newaxislinalginvr   dotmathlogr   exp)rnequalrz   nadavinbdbanyitinvecCCinvrE   vecaiBNpowerp1facs                        r0   r   r     s/   B	GAI1Q3BVVBGGBK1$%%E n$+A."((2U++b059R<
1
2! ) * 	*	eAhB	
R!B99QqS>D
1bjj=!!A99==D1Xv-- 
cc1
C	a1f		#	!b&	)B	A
"X!"X!	bffRY#	#B	qB

gbk
)C
((3-Cr#v:G  YYqs^s   .H* 4H* *'IIc           	        ^  [        [        S5      (       d  SSKJn  U[        l        O[        R                  n[	        T 5      (       d  Sn[        U5      e[        R                  " U5      R                  5       n[        R                  " U5      R                  5       n[        R                  " X5      u  pUR                  S   n	 T " X-   S-  5         T " [        R                  " X/5      R                  5        T n[        R"                  " U5      nX<:w  a  Sn[        U5      e[        R"                  " U5      nXM:w  a  Sn[        U5      eUc  UR$                  R'                  U	5      nO1[)        XWR$                  R*                  5      (       d  Sn[        U5      eUR,                  UR                  S   :w  a  Sn[        U5      e[/        USS 5      nUR0                  R3                  U5      nUS;  a  Sn[        U5      eXX,XXU4	$ ! [         a  n
Sn[        U5      U
eS n
A
ff = f! [         a,  n
SU
 S3n[        R                   " US	S
9  U 4S jn S n
A
GN]S n
A
ff = f)Nqmcr   )statsz`func` must be callable.rW   z`func` must evaluate the integrand at points within the integration range; e.g. `func( (a + b) / 2)` must return the integrand at the centroid of the integration volume.zAException encountered when attempting vectorized call to `func`: z. For better performance, `func` should accept two-dimensional array `x` with shape `(len(a), n_points)` and return an array of the integrand value at each of the `n_points.ru   
stacklevelc                 0   > [         R                  " TSU S9$ )Nr   )r   r   )r9   apply_along_axis)r'   r<   s    r0   vfunc_qmc_quad_iv.<locals>.vfunc`  s    &&t"!<<r5   z`n_points` must be an integer.z!`n_estimates` must be an integer.z8`qrng` must be an instance of scipy.stats.qmc.QMCEngine.z`qrng` must be initialized with dimensionality equal to the number of variables in `a`, i.e., `qrng.random().shape[-1]` must equal `a.shape[0]`.rng_seed>   FTz*`log` must be boolean (`True` or `False`).)hasattrr   scipyr)  callabler   r9   
atleast_1drZ   broadcast_arraysr"   r
  r$   r  Twarningswarnint64r(  Halton
isinstance	QMCEnginer-   getattr_qmccheck_random_state)r<   r=   r>   n_pointsn_estimatesqrngr  r)  r   dimr   r.  n_points_intn_estimates_intr0  rngs   `               r0   _qmc_quad_ivrG  9  s)    8U##D>>,   	aA
aAq$DA
''!*C)aeq[=RXXqf  88H%L2  hh{+O%5  |yy$ii1122L  vvH !!tZ.H
**
'
'
1C
->  acNNe  )) !q()  	=S !,,
 	g!,	= 	=	=s0   H	 )H) 	
H&H!!H&)
I3!IIQMCQuadResultintegralstandard_errori   )rA  r@  rB  r  c          	        ^^^ [        XX$TXV5      nUu	  pp$mpXpiSS jn
SU4S jjmSUU4S jjmSUUU4S jjn[        R                  " X:H  5      (       a@  Sn[        R                  " USS9  [        U(       a  [        R                  * S5      $ SS5      $ X!:  nS	UR                  S	S
9-  nX-   X   sX'   X-'   [        R                  " X!-
  5      nX-  n[        R                  " T5      n[        UR                  T5      n[        T5       Ho  nUR                  U5      nU	R                  R                  UX5      R                   nU " U5      nU
" UUU5      UU'   [#        U5      " SSUU   0UR$                  D6nMq     T" UU5      nU" UUUS9nU(       a  US:  a  U[        R&                  S-  -   OUU-  n[        UU5      $ )a  
Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature.

Parameters
----------
func : callable
    The integrand. Must accept a single argument ``x``, an array which
    specifies the point(s) at which to evaluate the scalar-valued
    integrand, and return the value(s) of the integrand.
    For efficiency, the function should be vectorized to accept an array of
    shape ``(d, n_points)``, where ``d`` is the number of variables (i.e.
    the dimensionality of the function domain) and `n_points` is the number
    of quadrature points, and return an array of shape ``(n_points,)``,
    the integrand at each quadrature point.
a, b : array-like
    One-dimensional arrays specifying the lower and upper integration
    limits, respectively, of each of the ``d`` variables.
n_estimates, n_points : int, optional
    `n_estimates` (default: 8) statistically independent QMC samples, each
    of `n_points` (default: 1024) points, will be generated by `qrng`.
    The total number of points at which the integrand `func` will be
    evaluated is ``n_points * n_estimates``. See Notes for details.
qrng : `~scipy.stats.qmc.QMCEngine`, optional
    An instance of the QMCEngine from which to sample QMC points.
    The QMCEngine must be initialized to a number of dimensions ``d``
    corresponding with the number of variables ``x1, ..., xd`` passed to
    `func`.
    The provided QMCEngine is used to produce the first integral estimate.
    If `n_estimates` is greater than one, additional QMCEngines are
    spawned from the first (with scrambling enabled, if it is an option.)
    If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton`
    will be initialized with the number of dimensions determine from
    the length of `a`.
log : boolean, default: False
    When set to True, `func` returns the log of the integrand, and
    the result object contains the log of the integral.

Returns
-------
result : object
    A result object with attributes:

    integral : float
        The estimate of the integral.
    standard_error :
        The error estimate. See Notes for interpretation.

Notes
-----
Values of the integrand at each of the `n_points` points of a QMC sample
are used to produce an estimate of the integral. This estimate is drawn
from a population of possible estimates of the integral, the value of
which we obtain depends on the particular points at which the integral
was evaluated. We perform this process `n_estimates` times, each time
evaluating the integrand at different scrambled QMC points, effectively
drawing i.i.d. random samples from the population of integral estimates.
The sample mean :math:`m` of these integral estimates is an
unbiased estimator of the true value of the integral, and the standard
error of the mean :math:`s` of these estimates may be used to generate
confidence intervals using the t distribution with ``n_estimates - 1``
degrees of freedom. Perhaps counter-intuitively, increasing `n_points`
while keeping the total number of function evaluation points
``n_points * n_estimates`` fixed tends to reduce the actual error, whereas
increasing `n_estimates` tends to decrease the error estimate.

Examples
--------
QMC quadrature is particularly useful for computing integrals in higher
dimensions. An example integrand is the probability density function
of a multivariate normal distribution.

>>> import numpy as np
>>> from scipy import stats
>>> dim = 8
>>> mean = np.zeros(dim)
>>> cov = np.eye(dim)
>>> def func(x):
...     # `multivariate_normal` expects the _last_ axis to correspond with
...     # the dimensionality of the space, so `x` must be transposed
...     return stats.multivariate_normal.pdf(x.T, mean, cov)

To compute the integral over the unit hypercube:

>>> from scipy.integrate import qmc_quad
>>> a = np.zeros(dim)
>>> b = np.ones(dim)
>>> rng = np.random.default_rng()
>>> qrng = stats.qmc.Halton(d=dim, seed=rng)
>>> n_estimates = 8
>>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng)
>>> res.integral, res.standard_error
(0.00018429555666024108, 1.0389431116001344e-07)

A two-sided, 99% confidence interval for the integral may be estimated
as:

>>> t = stats.t(df=n_estimates-1, loc=res.integral,
...             scale=res.standard_error)
>>> t.interval(0.99)
(0.0001839319802536469, 0.00018465913306683527)

Indeed, the value reported by `scipy.stats.multivariate_normal` is
within this range.

>>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
0.00018430867675187443

c                     U(       a"  [        U 5      [        R                  " U5      -   $ [        R                  " X-  5      $ rB   )r   r9   r  r#   )
integrandsdAr  s      r0   sum_productqmc_quad.<locals>.sum_product  s.    Z(266":5566*/**r5   c                    > U(       a"  [        U 5      [        R                  " T5      -
  $ [        R                  " U 5      $ rB   )r   r9   r  mean)	estimatesr  rA  s     r0   rR  qmc_quad.<locals>.mean  s.    Y'"&&*===779%%r5   r   c                 t  > U=(       d    T" X5      nU(       a  [         R                  " X5      u  p[         R                  " X[         R                  S-  -   45      n[	        USS9n[         R
                  " S[	        SU-  5      [         R                  " TU-
  5      -
  -  5      $ [         R                  " XS9$ )N              ?r   r8   rt   rW   )ddof)r9   r5  vstackpir   r:   r  std)rS  mrW  r  temprM   rR  rA  s         r0   rZ  qmc_quad.<locals>.std  s    %i%..y<LI99iRUURZ89DT*D773)AH"5$&FF;+=$>#? @ A A 66)//r5   c                    > U=(       d    T" X5      nU=(       d    T" XSUS9nU(       a  US[         R                  " T5      -  -
  $ U[         R                  " T5      -  $ )Nr   )rW  r  rt   )r9   r  sqrt)rS  r[  sr  rR  rA  rZ  s       r0   semqmc_quad.<locals>.sem  sU    %i%3Ys3s266+....rww{+++r5   z^A lower limit was equal to an upper limit, so the value of the integral is zero by definition.rW   r*  r   r8   seed)r[  r  rV  )F)Nr   F)NNFr   )rG  r9   r   r7  r8  rH  infr#   prodzerosr   rF  r   randomr(  scaler6  type
_init_quadrY  )r<   r=   r>   rA  r@  rB  r  r?   rF  r)  rO  ra  r   i_swapsignArN  rS  rngsrE   sampler'   rM  rI  rJ  rR  rZ  s      `                     @@r0   r   r     s   \ k4ED?C<DQ+t#+&	0 	0, , 
vvaf~~<g!,bffWA66A66UF&**"*%&D9aiAIqy
A	
B%Idhh,D;X& IIOOFA)++!W
":r37	! Dz:tAw:$//:   Is#HhC8N'*taxx"%%("htmH>22r5   )Nr   r   )r   r6   )Nr   r   NrB   )r   r   F)r   ),numpyr9   numpy.typingtypingnptr  r7  collectionsr   collections.abcr   scipy.specialr   r   r   scipy._lib._utilr   scipy._lib._array_apir	   r
   r   __all__r   r2   dictr3   r   rH   r   rq   r   ndarrayr   r   r   	ArrayLiker   r   r   r  r   rG  rH  r   r   r5   r0   <module>r}     s       " $ ( , ' Q Q-L^	+  $v  @?FZz"J^Sr ^B	zz


 

BJJ7CD ZZ	222:: 22:: 2"** 27RZZ 7RZZ 7BJJ 70S]] rzz   $"d upo\ 	
!QqE"R	!GBr	!Ib	"^Bs#	#!$u-	#'40	%7fE	%?f	% #V-	
6 7	)	 
H ()4l	D 
G 016	@ 
\ 3 5@		 
J 8 :E			7 FjZGOT ?Z9I,JK )*Dtr3r5   