
    ^MhGd                     X   U d dl Z d dlZd dlZd dlmZmZ d dlmZ d dlm	Z	m
Z
 d dlmZmZmZmZ d dlmZ d dlmZmZmZ d dlmZ d	gZe	Ze
ed
<   e G d d                      Ze G d d                      Zddd ddddddZd Zd Zd Z  G d d          Z! G d de!          Z"dS )    N)	dataclassfield)
ModuleType)Any	TypeAlias)array_namespacexp_sizexp_copyxp_broadcast_promote)
MapWrapper)ProductNestedFixedGaussKronrodQuadratureGenzMalikCubature)_split_subregioncubatureArrayc                   `    e Zd ZU eed<   eed<   eed<   eed<    ed          Zeed<   d Zd	S )
CubatureRegionestimateerrorabF)repr_xpc                     | j                             | j                             | j                            }| j                             | j                             |j                            }||k    S N)r   maxabsr   )selfotherthis_err	other_errs       Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/integrate/_cubature.py__lt__zCubatureRegion.__lt__%   sU    
 8<<TZ 8 899HLLek!:!:;;	)##    N)	__name__
__module____qualname__r   __annotations__r   r   r   r$    r%   r#   r   r      sf         OOOLLLHHHHHHe'''C'''$ $ $ $ $r%   r   c                   b    e Zd ZU eed<   eed<   eed<   ee         ed<   eed<   e	ed<   e	ed<   dS )	CubatureResultr   r   statusregionssubdivisionsatolrtolN)
r&   r'   r(   r   r)   strlistr   intfloatr*   r%   r#   r,   r,   0   sZ         OOOLLLKKK.!!!!
KKK
KKKKKr%   r,   gk21g:0yE>i'  r*      )ruler1   r0   max_subdivisionsargsworkerspointsc                	   % t          ||          %|t          d          n|}|	g n|	}	t          ||g|	R ddi^}}}	|j        }
t	          |          dk    st	          |          dk    rt          d          |j        dk    s|j        dk    rt          d          t          |t                    rt	          |          }|d	k    rt          |%
          }not          d%
          t          d%
          t          d%
          d}|                    |          }|t          d|           t          |g|z            }d%                    %                    ||k    %j                  |
          z  }%                    %                    ||g          d          }%                    %                    ||g          d          }||}}%                    %                    |                    s(%                    %                    |                    rat+           ||%
            j        \  }}%fd|	D             }	 fd|	D             }	%fd|	D             }	|	                     j                   t3          |	          dk    r||fg}nt5          |||	%          }g }d}d}|D ]e\  }}|                     |||          }|                     |||          }|                    t=          ||||%                     ||z  }||z  }fd}d}t?          |          5 }%                    |||%                     |          z  z   k              rtC          j"        |          }|j        }|j#        }|j$        |j%        }}||z  }||z  }tM          tO          j(                   tO          j(        |          tO          j(        |          tS          ||%                    } |tT          |          D ];}|\  }} }!}"||!z  }||"z  }t=          |!|"|| %          }#tC          j+        ||#           <|dz  }||k    rd}n3%                    |||%                     |          z  z   k              |rdnd}$||z  }tY          |||$||||          cddd           S # 1 swxY w Y   dS )a(  
    Adaptive cubature of multidimensional array-valued function.

    Given an arbitrary integration rule, this function returns an estimate of the
    integral to the requested tolerance over the region defined by the arrays `a` and
    `b` specifying the corners of a hypercube.

    Convergence is not guaranteed for all integrals.

    Parameters
    ----------
    f : callable
        Function to integrate. `f` must have the signature::

            f(x : ndarray, *args) -> ndarray

        `f` should accept arrays ``x`` of shape::

            (npoints, ndim)

        and output arrays of shape::

            (npoints, output_dim_1, ..., output_dim_n)

        In this case, `cubature` will return arrays of shape::

            (output_dim_1, ..., output_dim_n)
    a, b : array_like
        Lower and upper limits of integration as 1D arrays specifying the left and right
        endpoints of the intervals being integrated over. Limits can be infinite.
    rule : str, optional
        Rule used to estimate the integral. If passing a string, the options are
        "gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
        "gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
        Cartesian product rule is used. "gk21", "gk15" are also supported for
        compatibility with `quad_vec`. See Notes.
    rtol, atol : float, optional
        Relative and absolute tolerances. Iterations are performed until the error is
        estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
        relative accuracy (number of correct digits), while `atol` controls absolute
        accuracy (number of correct decimal places). To achieve the desired `rtol`, set
        `atol` to be smaller than the smallest value that can be expected from
        ``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
        larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
        Conversely, to achieve the desired `atol`, set `rtol` such that
        ``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
        `rtol` and 0 for `atol`.
    max_subdivisions : int, optional
        Upper bound on the number of subdivisions to perform. Default is 10,000.
    args : tuple, optional
        Additional positional args passed to `f`, if any.
    workers : int or map-like callable, optional
        If `workers` is an integer, part of the computation is done in parallel
        subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
        Supply `-1` to use all cores available to the Process. Alternatively, supply a
        map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
        evaluating the population in parallel. This evaluation is carried out as
        ``workers(func, iterable)``.
    points : list of array_like, optional
        List of points to avoid evaluating `f` at, under the condition that the rule
        being used does not evaluate `f` on the boundary of a region (which is the
        case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
        a singularity at the specified point. This should be a list of array-likes where
        each element has length ``ndim``. Default is empty. See Examples.

    Returns
    -------
    res : object
        Object containing the results of the estimation. It has the following
        attributes:

        estimate : ndarray
            Estimate of the value of the integral over the overall region specified.
        error : ndarray
            Estimate of the error of the approximation over the overall region
            specified.
        status : str
            Whether the estimation was successful. Can be either: "converged",
            "not_converged".
        subdivisions : int
            Number of subdivisions performed.
        atol, rtol : float
            Requested tolerances for the approximation.
        regions: list of object
            List of objects containing the estimates of the integral over smaller
            regions of the domain.

        Each object in ``regions`` has the following attributes:

        a, b : ndarray
            Points describing the corners of the region. If the original integral
            contained infinite limits or was over a region described by `region`,
            then `a` and `b` are in the transformed coordinates.
        estimate : ndarray
            Estimate of the value of the integral over this region.
        error : ndarray
            Estimate of the error of the approximation over this region.

    Notes
    -----
    The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
    implementation of QUADPACK's DQAG* algorithms, implementing global error control and
    adaptive subdivision.

    The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
    in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
    cubature can be found in [2]_.

    The rules currently supported via the `rule` argument are:

    - ``"gauss-kronrod"``, 21-node Gauss-Kronrod
    - ``"genz-malik"``, n-node Genz-Malik

    If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
    corresponding Cartesian product rule will be found by taking the Cartesian product
    of the nodes in the 1D case. This means that the number of nodes scales
    exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
    moderate number of dimensions.

    Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
    so in this situation using "genz-malik" might be preferable.

    Infinite limits are handled with an appropriate variable transformation. Assuming
    ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:

    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.

    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
    :math:`t \in (0, 1)`.

    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
    :math:`t \in (0, 1)`.

    References
    ----------
    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
        Integration, files: dqk21.f, dqk15.f (1983).

    .. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
        numerical integration over an N-dimensional rectangular region, Journal of
        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
        ISSN 0377-0427
        :doi:`10.1016/0771-050X(80)90039-X`

    Examples
    --------
    **1D integral with vector output**:

    .. math::

        \int^1_0 \mathbf f(x) \text dx

    Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
    specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
    integration with 21 nodes.

    >>> import numpy as np
    >>> from scipy.integrate import cubature
    >>> def f(x, n):
    ...    # Make sure x and n are broadcastable
    ...    return x[:, np.newaxis]**n[np.newaxis, :]
    >>> res = cubature(
    ...     f,
    ...     a=[0],
    ...     b=[1],
    ...     args=(np.arange(10),),
    ... )
    >>> res.estimate
     array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
            0.16666667, 0.14285714, 0.125     , 0.11111111, 0.1       ])

    **7D integral with arbitrary-shaped array output**::

        f(x) = cos(2*pi*r + alphas @ x)

    for some ``r`` and ``alphas``, and the integral is performed over the unit
    hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
    dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
    avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.

    >>> import numpy as np
    >>> from scipy.integrate import cubature
    >>> def f(x, r, alphas):
    ...     # f(x) = cos(2*pi*r + alphas @ x)
    ...     # Need to allow r and alphas to be arbitrary shape
    ...     npoints, ndim = x.shape[0], x.shape[-1]
    ...     alphas = alphas[np.newaxis, ...]
    ...     x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
    ...     return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
    >>> rng = np.random.default_rng()
    >>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
    >>> res = cubature(
    ...     f=f,
    ...     a=np.array([0, 0, 0, 0, 0, 0, 0]),
    ...     b=np.array([1, 1, 1, 1, 1, 1, 1]),
    ...     rtol=1e-5,
    ...     rule="genz-malik",
    ...     args=(r, alphas),
    ... )
    >>> res.estimate
     array([[-0.79812452,  0.35246913, -0.52273628],
            [ 0.88392779,  0.59139899,  0.41895111]])

    **Parallel computation with** `workers`:

    >>> from concurrent.futures import ThreadPoolExecutor
    >>> with ThreadPoolExecutor() as executor:
    ...     res = cubature(
    ...         f=f,
    ...         a=np.array([0, 0, 0, 0, 0, 0, 0]),
    ...         b=np.array([1, 1, 1, 1, 1, 1, 1]),
    ...         rtol=1e-5,
    ...         rule="genz-malik",
    ...         args=(r, alphas),
    ...         workers=executor.map,
    ...      )
    >>> res.estimate
     array([[-0.79812452,  0.35246913, -0.52273628],
            [ 0.88392779,  0.59139899,  0.41895111]])

    **2D integral with infinite limits**:

    .. math::

        \int^{ \infty }_{ -\infty }
        \int^{ \infty }_{ -\infty }
            e^{-x^2-y^2}
        \text dy
        \text dx

    >>> def gaussian(x):
    ...     return np.exp(-np.sum(x**2, axis=-1))
    >>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
    >>> res.estimate
     3.1415926

    **1D integral with singularities avoided using** `points`:

    .. math::

        \int^{ 1 }_{ -1 }
          \frac{\sin(x)}{x}
        \text dx

    It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.

    >>> def sinc(x):
    ...     return np.sin(x)/x
    >>> res = cubature(sinc, [-1], [1], points=[[0]])
    >>> res.estimate
     1.8921661
    Ninfforce_floatingTr   z`a` and `b` must be nonemptyr7   z`a` and `b` must be 1D arraysz
genz-malik)xp      )zgauss-kronrodr6   gk15zunknown rule )dtypeaxisc                 <    g | ]}                     |d           S ))r7   rD   reshape.0pointr@   s     r#   
<listcomp>zcubature.<locals>.<listcomp>|  s'    AAA"**UG,,AAAr%   c                 :    g | ]}                     |          S r*   )inv)rL   rM   fs     r#   rN   zcubature.<locals>.<listcomp>}  s#    3335!%%,,333r%   c                 <    g | ]}                     |d           S ))rD   rI   rK   s     r#   rN   zcubature.<locals>.<listcomp>~  s'    ???u"**UE**???r%   g        F	convergednot_converged)r   r   r-   r/   r.   r0   r1   )-r   r5   r   rE   r	   
ValueErrorndim
isinstancer2   r   r   getr   sumastypeint8minstackr   anyisinf_InfiniteLimitsTransformtransformed_limitsextendr<   len_split_region_at_pointsr   estimate_errorappendr   r   r   heapqheappopr   r   r   zip	itertoolsrepeatr   _process_subregionheappushr,   )&rQ   r   r   r8   r1   r0   r9   r:   r;   r<   result_dtyperV   
quadratues	base_rulesign	a_flipped	b_flippedinitial_regionsr.   esterra_kb_kest_kerr_kr/   success
mapwrapperregion_kexecutor_argssubdivision_resulta_k_subb_k_subest_suberr_sub
new_regionr-   r@   s&   `                                    @r#   r   r   ;   s   J 
A		B'7'?uU|||EU>RRvF )ALLLLtLLMAq67LqzzQ'!**//7888v{{afkk8999 $ :qzz<$Tb111DD "8r!B!B!B /rb999.rb999 J #t,,I  !7!7!7888%ykD&899D 266"))AE2733<6HHHDrxxA''a00IrxxA''a00IiqA 
vvbhhqkk  bffRXXa[[11  $Q1444#1 BAAA&AAA3333F333??????? 	ah 6{{aq6(1!QCCG
C
C#  Sac400##AsC66~eUCbAABBBuuLG	G		 =

ffS4$"44455 -	}W--H%ENEz8:C
 5LC5LC   ## && && c2..	 M '1j1C]&S&S 4 4"5G2'7ww+GWgwPRSS
w
3333AL///[ ffS4$"44455 -	^ !(<_ Sj%
 
 
k=
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
 =
s   <E3R<<S S c                     | \  }}}}|\  }}|                     ||||          }|                    ||||          }||||fS r   )r   re   )	datarQ   r8   r:   coordr   r   r   r   s	            r#   rl   rl     sY    AtT5GWmmAw66G!!!Wgt<<GGWg--r%   c                     |                     || k              s|                     ||k              rdS |                     | |k              o|                     ||k              S )NF)all)r   r   rM   r@   s       r#   _is_strictly_in_regionr     sa    	vveqj RVVEQJ// u66!u*4"&&!"4"44r%   c                    | |fg}|D ]}|                     |                    |                    r+g }|D ]\  }}t          ||||          rat          ||||          }	|	D ]6\  }
}|                     |
|k              r|                    |
|f           7|                    |	           x|                    ||f           |}|S )a$  
    Given the integration limits `a` and `b` describing a rectangular region and a list
    of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
    initial region into smaller subregion such that no `points` lie strictly inside
    any of the subregions.
    )r^   r_   r   r   rf   rb   )r   r   r<   r@   r.   rM   new_subregionsrw   rx   
subregionsleftrights               r#   rd   rd     s    1vhG ! !66"((5//"" 	
  	2 	2HC%c3r:: 2-c3EBB
#- = =KD%vvdem,, = &--tUm<<<<%%j1111 %%sCj1111 Nr%   c                   J    e Zd ZdZed             Zed             Zd Zd ZdS )_VariableTransformz>
    A transformation that can be applied to an integral.
    c                     t           )zN
        New limits of integration after applying the transformation.
        NotImplementedErrorr   s    r#   ra   z%_VariableTransform.transformed_limits  s
     "!r%   c                     g S )a_  
        Any problematic points introduced by the transformation.

        These should be specified as points where ``_VariableTransform(f)(self, point)``
        would be problematic.

        For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
        univariate integral, then points should return ``[ [1], [-1] ]``.
        r*   r   s    r#   r<   z_VariableTransform.points#  s	     	r%   c                     t           )z
        Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
        is the function after the transformation is applied, then::

            f(x) = g(self.inv(x))
        r   )r   xs     r#   rP   z_VariableTransform.inv1  s
     "!r%   c                     t           )a  
        Apply the transformation to ``f`` and multiply by the Jacobian determinant.
        This should be the new integrand after the transformation has been applied so
        that the following is satisfied::

            f_transformed = _VariableTransform(f)

            cubature(f, a, b) == cubature(
                f_transformed,
                *f_transformed.transformed_limits(a, b),
            )
        r   )r   tr:   kwargss       r#   __call__z_VariableTransform.__call__;  s
     "!r%   N)	r&   r'   r(   __doc__propertyra   r<   rP   r   r*   r%   r#   r   r     sr          " " X"   X" " "" " " " "r%   r   c                   P    e Zd ZdZd Zed             Zed             Zd Zd Z	dS )r`   a  
    Transformation for handling infinite limits.

    Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:

    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.

    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
    :math:`t \in (0, 1)`.

    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
    :math:`t \in (0, 1)`.
    c                 .   || _         || _        || _        || _        |t          j         k    |t          j        k    z  | _        |t          j         k    |t          j        k    z  }|t          j         k    |t          j        k    z  }||z  | _        ||          | j        |<   ||          | j        |<   | j                             | j         	                    | j        | j        z  | j         j
                                                            | _        d S r   )r   _f_orig_a_orig_bmathr>   _double_inf_pos_semi_inf_posrY   rZ   int64__int___num_inf)r   rQ   r   r   r@   start_inf_maskinf_end_masks          r#   __init__z!_InfiniteLimitsTransform.__init__^  s     !"dhY1=A y.Q$(]; dhY1=9 ,l: '(o%5\"&'o%5\"HOOD043EEtx~VV
 

')) 	r%   c                     t          | j                  }t          | j                  }d|| j        <   d|| j        <   d|| j        <   d|| j        <   ||fS )NrD   r7   r   )r
   r   r   r   r   )r   r   r   s      r#   ra   z+_InfiniteLimitsTransform.transformed_limits{  s]    DL!!DL!!"$$
"#$
 !$
 !$
!tr%   c                 f    | j         dk    r%| j                            | j        j                  gS g S )Nr   )r   r   zerosr   shaper   s    r#   r<   z_InfiniteLimitsTransform.points  s2     =AHNN4<#56677Ir%   c                 6   t          |          }|j        d         }| j                            | j        | j        j        d d f         |df          }| j                            | j        | j        j        d d f         |df          }||         dk    }|| z  }t          j        ||<   d||         | j        	                    ||                   z   z  ||<   | j                            | j
        | j                 |f          }d||         |z
  dz   z  ||<   |S )Nr   r7   )r
   r   r   tiler   newaxisr   r   r>   rq   r   )	r   r   r   npointsdouble_inf_masksemi_inf_mask	zero_masknon_zero_maskstarts	            r#   rP   z_InfiniteLimitsTransform.inv  s   AJJ'!*(-- !1111!45aL
 

 tx/23aL
 
 o&!+	'9*4x)a.q?O1P1PPQ-dl4+=>
KKa.6:;-r%   c                 .   t          |          }|j        d         }| j                            | j        | j        j        d d f         |df          }| j                            | j        | j        j        d d f         |df          }d| j                            ||                   z
  ||         z  ||<   | j                            | j        | j                 |f          }|d||         z
  ||         z  z   ||<   d| j        	                    | j        
                    |||z           dz  d| j        f          d          z  }	 | j        |g|R i |}
| j        
                    |	dgdgt          |
j                  dz
  z  R           }	|
|	z  S )Nr   r7      rD   rF   )r
   r   r   r   r   r   r   r   r   prodrJ   r   r   rc   )r   r   r:   r   r   r   r   r   r   jacobian_detf_xs              r#   r   z!_InfiniteLimitsTransform.__call__  s   AJJ'!*(-- !1111!45aL
 

 tx/23aL
 
 a0111Q5GG 	
/ dl4+=>
KK !A-(8$8Am<L#LL-H-/12A5T]#   ' 
 
 
 dga)$)))&))x''r6WaS#ci..STBT=U6W6WXX\!!r%   N)
r&   r'   r(   r   r   r   ra   r<   rP   r   r*   r%   r#   r`   r`   L  s         "  : 
 
 X
   X  :#" #" #" #" #"r%   r`   )#r   rg   rj   dataclassesr   r   typesr   typingr   r   scipy._lib._array_apir   r	   r
   r   scipy._lib._utilr   scipy.integrate._rulesr   r   r   scipy.integrate._rules._baser   __all__r   r)   r   r,   r   rl   r   rd   r   r`   r*   r%   r#   <module>r      sC         ( ( ( ( ( ( ( (       ! ! ! ! ! ! ! !            ( ' ' ' ' '         
 : 9 9 9 9 9,y    $ $ $ $ $ $ $ $$         %4a%a^
 ^
 ^
 ^
 ^
B. . .5 5 5& & &R3" 3" 3" 3" 3" 3" 3" 3"lL" L" L" L" L"1 L" L" L" L" L"r%   