Ë
    âQ(hF  ã                   óŠ   — d dl mZmZ d dlmZ  G d„ d«      Z G d„ de«      Z G d„ de«      Z G d	„ d
e«      Zd„ Z	dd„Z
d„ Zy)é    )Úarray_namespaceÚxp_size)Úcached_propertyc                   ó    — e Zd ZdZdd„Zdd„Zy)ÚRulea†	  
    Base class for numerical integration algorithms (cubatures).

    Finds an estimate for the integral of ``f`` over the region described by two arrays
    ``a`` and ``b`` via `estimate`, and find an estimate for the error of this
    approximation via `estimate_error`.

    If a subclass does not implement its own `estimate_error`, then it will use a
    default error estimate based on the difference between the estimate over the whole
    region and the sum of estimates over that region divided into ``2^ndim`` subregions.

    See Also
    --------
    FixedRule

    Examples
    --------
    In the following, a custom rule is created which uses 3D Genz-Malik cubature for
    the estimate of the integral, and the difference between this estimate and a less
    accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the
    error.

    >>> import numpy as np
    >>> from scipy.integrate import cubature
    >>> from scipy.integrate._rules import (
    ...     Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature
    ... )
    >>> def f(x, r, alphas):
    ...     # f(x) = cos(2*pi*r + alpha @ x)
    ...     # Need to allow r and alphas to be arbitrary shape
    ...     npoints, ndim = x.shape[0], x.shape[-1]
    ...     alphas_reshaped = alphas[np.newaxis, :]
    ...     x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
    ...     return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1))
    >>> genz = GenzMalikCubature(ndim=3)
    >>> gauss = GaussKronrodQuadrature(npoints=21)
    >>> # Gauss-Kronrod is 1D, so we find the 3D product rule:
    >>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss])
    >>> class CustomRule(Rule):
    ...     def estimate(self, f, a, b, args=()):
    ...         return genz.estimate(f, a, b, args)
    ...     def estimate_error(self, f, a, b, args=()):
    ...         return np.abs(
    ...             genz.estimate(f, a, b, args)
    ...             - gauss_3d.estimate(f, a, b, args)
    ...         )
    >>> rng = np.random.default_rng()
    >>> res = cubature(
    ...     f=f,
    ...     a=np.array([0, 0, 0]),
    ...     b=np.array([1, 1, 1]),
    ...     rule=CustomRule(),
    ...     args=(rng.random((2,)), rng.random((3, 2, 3)))
    ... )
    >>> res.estimate
     array([[-0.95179502,  0.12444608],
            [-0.96247411,  0.60866385],
            [-0.97360014,  0.25515587]])
    c                 ó   — t         ‚)a«  
        Calculate estimate of integral of `f` in rectangular region described by
        corners `a` and ``b``.

        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, `estimate` will return arrays of shape::
                (output_dim_1, ..., output_dim_n)
        a, b : ndarray
            Lower and upper limits of integration as rank-1 arrays specifying the left
            and right endpoints of the intervals being integrated over. Infinite limits
            are currently not supported.
        args : tuple, optional
            Additional positional args passed to ``f``, if any.

        Returns
        -------
        est : ndarray
            Result of estimation. If `f` returns arrays of shape ``(npoints,
            output_dim_1, ..., output_dim_n)``, then `est` will be of shape
            ``(output_dim_1, ..., output_dim_n)``.
        ©ÚNotImplementedError)ÚselfÚfÚaÚbÚargss        úZ/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/scipy/integrate/_rules/_base.pyÚestimatezRule.estimateC   s   € ôB "Ð!ó    c                 óÀ   — | j                  ||||«      }d}t        ||«      D ]  \  }}|| j                  ||||«      z  }Œ | j                  j                  ||z
  «      S )a-  
        Estimate the error of the approximation for the integral of `f` in rectangular
        region described by corners `a` and `b`.

        If a subclass does not override this method, then a default error estimator is
        used. This estimates the error as ``|est - refined_est|`` where ``est`` is
        ``estimate(f, a, b)`` and ``refined_est`` is the sum of
        ``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each
        subregion of the region described by ``a`` and ``b``. In the 1D case, this
        is equivalent to comparing the integral over an entire interval ``[a, b]`` to
        the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]``
        and ``[(a+b)/2, b]``.

        Parameters
        ----------
        f : callable
            Function to estimate error for. `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, `estimate` will return arrays of shape::
                (output_dim_1, ..., output_dim_n)
        a, b : ndarray
            Lower and upper limits of integration as rank-1 arrays specifying the left
            and right endpoints of the intervals being integrated over. Infinite limits
            are currently not supported.
        args : tuple, optional
            Additional positional args passed to `f`, if any.

        Returns
        -------
        err_est : ndarray
            Result of error estimation. If `f` returns arrays of shape
            ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
            of shape ``(output_dim_1, ..., output_dim_n)``.
        r   )r   Ú_split_subregionÚxpÚabs)	r   r   r   r   r   ÚestÚrefined_estÚa_kÚb_ks	            r   Úestimate_errorzRule.estimate_errorf   sk   € ðV �m‰m˜A˜q ! TÓ*ˆØˆä(¨¨AÓ.ò 	<‰HˆC�Ø˜4Ÿ=™=¨¨C°°dÓ;Ñ;‰Kð	<ð �w‰w�{‰{˜3 Ñ,Ó-Ð-r   N©© )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r      s   „ ñ:óx!"ôF1.r   r   c                   ó.   — e Zd ZdZd„ Zed„ «       Zdd„Zy)Ú	FixedRuleaÞ  
    A rule implemented as the weighted sum of function evaluations at fixed nodes.

    Attributes
    ----------
    nodes_and_weights : (ndarray, ndarray)
        A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the
        corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D
        cubature rules (quadratures) and more generally for N-D cubature rules, it
        should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape
        ``(num_nodes,)``. The nodes and weights should be for integrals over
        :math:`[-1, 1]^n`.

    See Also
    --------
    GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature

    Examples
    --------

    Implementing Simpson's 1/3 rule:

    >>> import numpy as np
    >>> from scipy.integrate._rules import FixedRule
    >>> class SimpsonsQuad(FixedRule):
    ...     @property
    ...     def nodes_and_weights(self):
    ...         nodes = np.array([-1, 0, 1])
    ...         weights = np.array([1/3, 4/3, 1/3])
    ...         return (nodes, weights)
    >>> rule = SimpsonsQuad()
    >>> rule.estimate(
    ...     f=lambda x: x**2,
    ...     a=np.array([0]),
    ...     b=np.array([1]),
    ... )
     [0.3333333]
    c                 ó   — d | _         y ©N)r   ©r   s    r   Ú__init__zFixedRule.__init__Â   s	   € Øˆ�r   c                 ó   — t         ‚r%   r	   r&   s    r   Únodes_and_weightszFixedRule.nodes_and_weightsÅ   s   € ä!Ð!r   c           	      óŽ   — | j                   \  }}| j                  €t        |«      | _        t        ||||||| j                  «      S )aM  
        Calculate estimate of integral of `f` in rectangular region described by
        corners `a` and `b` as ``sum(weights * f(nodes))``.

        Nodes and weights will automatically be adjusted from calculating integrals over
        :math:`[-1, 1]^n` to :math:`[a, b]^n`.

        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, `estimate` will return arrays of shape::
                (output_dim_1, ..., output_dim_n)
        a, b : ndarray
            Lower and upper limits of integration as rank-1 arrays specifying the left
            and right endpoints of the intervals being integrated over. Infinite limits
            are currently not supported.
        args : tuple, optional
            Additional positional args passed to `f`, if any.

        Returns
        -------
        est : ndarray
            Result of estimation. If `f` returns arrays of shape ``(npoints,
            output_dim_1, ..., output_dim_n)``, then `est` will be of shape
            ``(output_dim_1, ..., output_dim_n)``.
        )r)   r   r   Ú_apply_fixed_rule)r   r   r   r   r   ÚnodesÚweightss          r   r   zFixedRule.estimateÉ   sD   € ðH ×/Ñ/‰ˆˆwà�7‰7ˆ?Ü% eÓ,ˆDŒGä   A q¨%°¸$ÀÇÁÓHÐHr   Nr   )r   r   r    r!   r'   Úpropertyr)   r   r   r   r   r#   r#   š   s'   „ ñ%òNð ñ"ó ð"ô)Ir   r#   c                   ó>   — e Zd ZdZd„ Zed„ «       Zed„ «       Zdd„Zy)ÚNestedFixedRuleaÖ  
    A cubature rule with error estimate given by the difference between two underlying
    fixed rules.

    If constructed as ``NestedFixedRule(higher, lower)``, this will use::

        estimate(f, a, b) := higher.estimate(f, a, b)
        estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)|

    (where the absolute value is taken elementwise).

    Attributes
    ----------
    higher : Rule
        Higher accuracy rule.

    lower : Rule
        Lower accuracy rule.

    See Also
    --------
    GaussKronrodQuadrature

    Examples
    --------

    >>> from scipy.integrate import cubature
    >>> from scipy.integrate._rules import (
    ...     GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed
    ... )
    >>> higher = GaussLegendreQuadrature(10)
    >>> lower = GaussLegendreQuadrature(5)
    >>> rule = NestedFixedRule(
    ...     higher,
    ...     lower
    ... )
    >>> rule_2d = ProductNestedFixed([rule, rule])
    c                 ó.   — || _         || _        d | _        y r%   )ÚhigherÚlowerr   )r   r2   r3   s      r   r'   zNestedFixedRule.__init__  s   € ØˆŒØˆŒ
Øˆ�r   c                 óR   — | j                   �| j                   j                  S t        ‚r%   )r2   r)   r
   r&   s    r   r)   z!NestedFixedRule.nodes_and_weights"  s"   € à�;‰;Ð"Ø—;‘;×0Ñ0Ð0ä%Ð%r   c                 óR   — | j                   �| j                   j                  S t        ‚r%   )r3   r)   r
   r&   s    r   Úlower_nodes_and_weightsz'NestedFixedRule.lower_nodes_and_weights)  s"   € à�:‰:Ð!Ø—:‘:×/Ñ/Ð/ä%Ð%r   c                 ó\  — | j                   \  }}| j                  \  }}| j                  €t        |«      | _        | j                  j	                  ||gd¬«      }	| j                  j	                  || gd¬«      }
| j                  j                  t        ||||	|
|| j                  «      «      S )aÒ  
        Estimate the error of the approximation for the integral of `f` in rectangular
        region described by corners `a` and `b`.

        Parameters
        ----------
        f : callable
            Function to estimate error for. `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, `estimate` will return arrays of shape::
                (output_dim_1, ..., output_dim_n)
        a, b : ndarray
            Lower and upper limits of integration as rank-1 arrays specifying the left
            and right endpoints of the intervals being integrated over. Infinite limits
            are currently not supported.
        args : tuple, optional
            Additional positional args passed to `f`, if any.

        Returns
        -------
        err_est : ndarray
            Result of error estimation. If `f` returns arrays of shape
            ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
            of shape ``(output_dim_1, ..., output_dim_n)``.
        r   ©Úaxis)r)   r6   r   r   Úconcatr   r+   )r   r   r   r   r   r,   r-   Úlower_nodesÚlower_weightsÚerror_nodesÚerror_weightss              r   r   zNestedFixedRule.estimate_error0  sž   € ðD ×/Ñ/‰ˆˆwØ%)×%AÑ%AÑ"ˆ�]à�7‰7ˆ?Ü% eÓ,ˆDŒGà—g‘g—n‘n e¨[Ð%9À�nÓBˆØŸ™Ÿ™¨°-°Ð'@Àq˜ÓIˆà�w‰w�{‰{Ü˜a  A {°MÀ4ÈÏÉÓQó
ð 	
r   Nr   )	r   r   r    r!   r'   r.   r)   r6   r   r   r   r   r0   r0   õ   s:   „ ñ%òNð
 ñ&ó ð&ð ñ&ó ð&ô-
r   r0   c                   ó6   — e Zd ZdZd„ Zed„ «       Zed„ «       Zy)ÚProductNestedFixeda`  
    Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D
    `NestedFixedRule` quadrature rules.

    Given a list of N 1-dimensional quadrature rules which support error estimation
    using NestedFixedRule, this will find the N-dimensional cubature rule obtained by
    taking the Cartesian product of their nodes, and estimating the error by taking the
    difference with a lower-accuracy N-dimensional cubature rule obtained using the
    ``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules.

    Parameters
    ----------
    base_rules : list of NestedFixedRule
        List of base 1-dimensional `NestedFixedRule` quadrature rules.

    Attributes
    ----------
    base_rules : list of NestedFixedRule
        List of base 1-dimensional `NestedFixedRule` qudarature rules.

    Examples
    --------

    Evaluate a 2D integral by taking the product of two 1D rules:

    >>> import numpy as np
    >>> from scipy.integrate import cubature
    >>> from scipy.integrate._rules import (
    ...  ProductNestedFixed, GaussKronrodQuadrature
    ... )
    >>> def f(x):
    ...     # f(x) = cos(x_1) + cos(x_2)
    ...     return np.sum(np.cos(x), axis=-1)
    >>> rule = ProductNestedFixed(
    ...     [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
    ... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule
    >>> a, b = np.array([0, 0]), np.array([1, 1])
    >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
     np.float64(1.682941969615793)
    >>> rule.estimate_error(f, a, b)
     np.float64(2.220446049250313e-16)
    c                 ód   — |D ]  }t        |t        «      rŒt        d«      ‚ || _        d | _        y )Nz<base rules for product need to be instance ofNestedFixedRule)Ú
isinstancer0   Ú
ValueErrorÚ
base_rulesr   )r   rD   Úrules      r   r'   zProductNestedFixed.__init__Œ  s=   € Øò 	4ˆDÜ˜d¤OÕ4Ü ð "3ó 4ð 4ð	4ð
 %ˆŒØˆ�r   c           	      óL  — t        | j                  D �cg c]  }|j                  d   ‘Œ c}«      }| j                  €t	        |«      | _        | j                  j                  t        | j                  D �cg c]  }|j                  d   ‘Œ c}«      d¬«      }||fS c c}w c c}w ©Nr   é   éÿÿÿÿr8   )Ú_cartesian_productrD   r)   r   r   Úprod)r   rE   r,   r-   s       r   r)   z$ProductNestedFixed.nodes_and_weights•  s™   € ä"Ø37·?±?ÖC¨4ˆT×#Ñ# AÓ&ÒCó
ˆð �7‰7ˆ?Ü% eÓ,ˆDŒGà—'‘'—,‘,ÜØ7;·±ÖG¨t�×'Ñ'¨Ó*ÒGóð ð	 ó 
ˆð �gˆ~Ðùò Dùò Hó   ”BÁ5B!c           	      óL  — t        | j                  D �cg c]  }|j                  d   ‘Œ c}«      }| j                  €t	        |«      | _        | j                  j                  t        | j                  D �cg c]  }|j                  d   ‘Œ c}«      d¬«      }||fS c c}w c c}w rG   )rJ   rD   r6   r   r   rK   )r   Úcubaturer,   r-   s       r   r6   z*ProductNestedFixed.lower_nodes_and_weights§  s™   € ä"ØAEÇÁÖQ°XˆX×-Ñ-¨aÓ0ÒQó
ˆð �7‰7ˆ?Ü% eÓ,ˆDŒGà—'‘'—,‘,ÜØEIÇ_Á_ÖU¸�×1Ñ1°!Ó4ÒUóð ð	 ó 
ˆð �gˆ~Ðùò Rùò VrL   N)r   r   r    r!   r'   r   r)   r6   r   r   r   r@   r@   `  s5   „ ñ)òVð ñó ðð" ñó ñr   r@   c                 ó–   — t        | Ž } |j                  | ddiŽ}|j                  |j                  |d¬«      dt	        | «      f«      }|S )NÚindexingÚijrI   r8   )r   ÚmeshgridÚreshapeÚstackÚlen)Úarraysr   Ú	arrays_ixÚresults       r   rJ   rJ   º  sL   € Ü	˜&Ð	!€Bà�—‘˜VÐ3¨dÑ3€IØ�Z‰Z˜Ÿ™ °˜Ó4°r¼3¸v»;Ð6GÓH€Fà€Mr   Nc              #   óÂ  K  — t        | |«      }|€| |z   dz  }t        | j                  d   «      D �cg c]  }|j                  | |   ||   g«      ‘Œ }}t        |j                  d   «      D �cg c]  }|j                  ||   ||   g«      ‘Œ }}t	        |«      }t	        |«      }t        |j                  d   «      D ]  }||df   ||df   f–— Œ yc c}w c c}w ­w)a
  
    Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates
    of all subregions, which in this case would be::

        ([0, 0], [1/2, 1/2]),
        ([0, 1/2], [1/2, 1]),
        ([1/2, 0], [1, 1/2]),
        ([1/2, 1/2], [1, 1])
    Né   r   .)r   ÚrangeÚshapeÚasarrayrJ   )	r   r   r   Úsplit_atÚiÚleftÚrightÚa_subÚb_subs	            r   r   r   Ã  sç   è ø€ ô 
˜˜AÓ	€BàÐØ˜‘E˜Q‘;ˆä5:¸1¿7¹7À1¹:Ó5FÖG°ˆB�J‰J˜˜!™˜h q™kÐ*Õ+ÐG€DÐGÜ6;¸A¿G¹GÀA¹JÓ6GÖH°ˆR�Z‰Z˜ !™ a¨¡dÐ+Õ,ÐH€EÐHä˜tÓ$€EÜ˜uÓ%€Eä�5—;‘;˜q‘>Ó"ò +ˆØ�A�s�F‰m˜U 1 c 6™]Ð*Ó*ñ+ùò HùÚHùs   ‚1C³ CÁCÁ/ CÂACc                 ó  — |j                   }|j                  ||«      }|j                  ||«      }|j                  dk(  r	|d d …d f   }|j                  d   }t	        |«      }	t	        |«      }
||	k7  s||
k7  rt        d|› d|	› d|
› �«      ‚||z
  }|dz   |dz  z  |z   }|j                  ||¬«      d|z  z  }||z  } | |g|¢­Ž }|j                  |dgdg|j                  dz
  z  ¢­«      }|j                  ||z  d	|¬
«      }|S )NrH   rI   z@rule and function are of incompatible dimension, nodes havendim z,, while limit of integration has ndima_ndim=z	, b_ndim=g      à?)ÚdtyperZ   r   )r9   re   )	re   ÚastypeÚndimr\   r   rC   rK   rS   Úsum)r   r   r   Ú
orig_nodesÚorig_weightsr   r   Úresult_dtypeÚ	rule_ndimÚa_ndimÚb_ndimÚlengthsr,   Úweight_scale_factorr-   Úf_nodesÚweights_reshapedr   s                     r   r+   r+   Ü  sH  € à—7‘7€LØ—‘˜: |Ó4€JØ—9‘9˜\¨<Ó8€Lð ‡�˜!ÒØ¢ 4 Ñ(ˆ
à× Ñ  Ñ$€Iä�Q‹Z€FÜ�Q‹Z€Fà�FÒ˜i¨6Ò1Üð !Ø!* ð ,#Ø#) (¨)°F°8ð=ó >ð 	>ð �!‰e€Gð ˜!‰^ ¨#¡Ñ.°Ñ2€Eð Ÿ'™' '°˜'Ó>ÀÀIÁÑMÐØÐ0Ñ0€Gá�ˆo˜Šo€GØ—z‘z '¨BÐ+L°1°#¸¿¹ÈÑ9IÑ2JÑ+LÓMÐð
 �&‰&Ð! GÑ+°!¸<ˆ&Ó
H€Cà€Jr   r%   )Úscipy._lib._array_apir   r   Ú	functoolsr   r   r#   r0   r@   rJ   r   r+   r   r   r   ú<module>ru      sV   ðß :å %÷Q.ñ Q.ôhXI�ô XIôvh
�iô h
ôVW˜ô Wòtó+ó2*r   