a
    BCCf                     @   s   d dl Z d dlZd dlmZ d dlmZmZmZ g dZ	dd Z
G dd dZG d	d
 d
eZG dd deZdddZdddZG dd deZdd dddZdS )    N)	factorial)_asarray_validatedfloat_factorialcheck_random_state)KroghInterpolatorkrogh_interpolateBarycentricInterpolatorbarycentric_interpolateapproximate_taylor_polynomialc                 C   s   t | pt| do| jdkS )z-Check whether x is if a scalar type, or 0-dimshape )npZisscalarhasattrr   )xr   r   V/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/interpolate/_polyint.py	_isscalar   s    r   c                   @   s\   e Zd ZdZdZdddZdd Zdd	 Zd
d Zdd Z	dddZ
dddZdddZdS )_Interpolator1Da	  
    Common features in univariate interpolation

    Deal with input data type and interpolation axis rolling. The
    actual interpolator can assume the y-data is of shape (n, r) where
    `n` is the number of x-points, and `r` the number of variables,
    and use self.dtype as the y-data type.

    Attributes
    ----------
    _y_axis
        Axis along which the interpolation goes in the original array
    _y_extra_shape
        Additional trailing shape of the input arrays, excluding
        the interpolation axis.
    dtype
        Dtype of the y-data arrays. Can be set via _set_dtype, which
        forces it to be float or complex.

    Methods
    -------
    __call__
    _prepare_x
    _finish_y
    _reshape_yi
    _set_yi
    _set_dtype
    _evaluate

    )_y_axis_y_extra_shapedtypeNc                 C   s.   || _ d | _d | _|d ur*| j|||d d S )Nxiaxis)r   r   r   _set_yi)selfr   yir   r   r   r   __init__4   s
    z_Interpolator1D.__init__c                 C   s$   |  |\}}| |}| ||S )a  
        Evaluate the interpolant

        Parameters
        ----------
        x : array_like
            Point or points at which to evaluate the interpolant.

        Returns
        -------
        y : array_like
            Interpolated values. Shape is determined by replacing
            the interpolation axis in the original array with the shape of `x`.

        Notes
        -----
        Input values `x` must be convertible to `float` values like `int`
        or `float`.

        )
_prepare_x	_evaluate	_finish_y)r   r   x_shapeyr   r   r   __call__;   s    
z_Interpolator1D.__call__c                 C   s
   t  dS )zB
        Actually evaluate the value of the interpolator.
        NNotImplementedErrorr   r   r   r   r   r   T   s    z_Interpolator1D._evaluatec                 C   s    t |ddd}|j}| |fS )zReshape input x array to 1-DFT)Zcheck_finiteZ
as_inexact)r   r   Zravel)r   r   r    r   r   r   r   Z   s    z_Interpolator1D._prepare_xc                 C   sz   | || j }| jdkrv|dkrvt|}t| j}tt||| j tt| tt|| j ||  }||}|S )z@Reshape interpolated y back to an N-D array similar to initial yr   r   )reshaper   r   lenlistrange	transpose)r   r!   r    nxnysr   r   r   r   `   s    


z_Interpolator1D._finish_yFc                 C   sv   t t || jd}|rb|jdd  | jkrbd| j| j d  | jd | j  }td| ||jd dfS )Nr      z{!r} + (N,) + {!r}zData must be of shape %s)	r   Zmoveaxisasarrayr   r   r   format
ValueErrorr&   )r   r   checkZok_shaper   r   r   _reshape_yik   s    z_Interpolator1D._reshape_yic                 C   s   |d u r| j }|d u rtdt|}|j}|dkr:d}|d urZ|| t|krZtd||j | _ |jd | j  |j| j d d   | _d | _| 	|j d S )Nzno interpolation axis specifiedr   )r.   z@x and y arrays must be equal in length along interpolation axis.r.   )
r   r2   r   r0   r   r'   ndimr   r   
_set_dtype)r   r   r   r   r   r   r   r   r   s   s    
&z_Interpolator1D._set_yic                 C   sD   t |t jst | jt jr(t j| _n|r8| jt jkr@t j| _d S )N)r   Z
issubdtypeZcomplexfloatingr   Z
complex128float64)r   r   unionr   r   r   r6      s    
z_Interpolator1D._set_dtype)NNN)F)NN)F)__name__
__module____qualname____doc__	__slots__r   r"   r   r   r   r4   r   r6   r   r   r   r   r      s   


r   c                   @   s*   e Zd Zd	ddZd
ddZdddZdS )_Interpolator1DWithDerivativesNc                 C   s   |  |\}}| ||}||jd f| | j }| jdkr|dkrt|}t| j}dgtt|d || j d  ttd|d  tt|d | j || d  }|	|}|S )a  
        Evaluate several derivatives of the polynomial at the point `x`

        Produce an array of derivatives evaluated at the point `x`.

        Parameters
        ----------
        x : array_like
            Point or points at which to evaluate the derivatives
        der : int or list or None, optional
            How many derivatives to evaluate, or None for all potentially
            nonzero derivatives (that is, a number equal to the number
            of points), or a list of derivatives to evaluate. This number
            includes the function value as the '0th' derivative.

        Returns
        -------
        d : ndarray
            Array with derivatives; ``d[j]`` contains the jth derivative.
            Shape of ``d[j]`` is determined by replacing the interpolation
            axis in the original array with the shape of `x`.

        Examples
        --------
        >>> from scipy.interpolate import KroghInterpolator
        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives(0)
        array([1.0,2.0,3.0])
        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives([0,0])
        array([[1.0,1.0],
               [2.0,2.0],
               [3.0,3.0]])

        r   r   r.   )
r   _evaluate_derivativesr&   r   r   r   r'   r(   r)   r*   )r   r   derr    r!   r+   r,   r-   r   r   r   derivatives   s    "
 
z*_Interpolator1DWithDerivatives.derivativesr.   c                 C   s.   |  |\}}| ||d }| || |S )a  
        Evaluate a single derivative of the polynomial at the point `x`.

        Parameters
        ----------
        x : array_like
            Point or points at which to evaluate the derivatives

        der : integer, optional
            Which derivative to evaluate (default: first derivative).
            This number includes the function value as 0th derivative.

        Returns
        -------
        d : ndarray
            Derivative interpolated at the x-points. Shape of `d` is
            determined by replacing the interpolation axis in the
            original array with the shape of `x`.

        Notes
        -----
        This may be computed by evaluating all derivatives up to the desired
        one (using self.derivatives()) and then discarding the rest.

        r.   r   r?   r   r   r   r@   r    r!   r   r   r   
derivative   s    z)_Interpolator1DWithDerivatives.derivativec                 C   s
   t  dS )a=  
        Actually evaluate the derivatives.

        Parameters
        ----------
        x : array_like
            1D array of points at which to evaluate the derivatives
        der : integer, optional
            The number of derivatives to evaluate, from 'order 0' (der=1)
            to order der-1.  If omitted, return all possibly-non-zero
            derivatives, ie 0 to order n-1.

        Returns
        -------
        d : ndarray
            Array of shape ``(der, x.size, self.yi.shape[1])`` containing
            the derivatives from 0 to der-1
        Nr#   )r   r   r@   r   r   r   r?      s    z4_Interpolator1DWithDerivatives._evaluate_derivatives)N)r.   )N)r9   r:   r;   rA   rD   r?   r   r   r   r   r>      s   
/
r>   c                       s4   e Zd ZdZd
 fdd	Zdd Zddd	Z  ZS )r   a@  
    Interpolating polynomial for a set of points.

    The polynomial passes through all the pairs ``(xi, yi)``. One may
    additionally specify a number of derivatives at each point `xi`;
    this is done by repeating the value `xi` and specifying the
    derivatives as successive `yi` values.

    Allows evaluation of the polynomial and all its derivatives.
    For reasons of numerical stability, this function does not compute
    the coefficients of the polynomial, although they can be obtained
    by evaluating all the derivatives.

    Parameters
    ----------
    xi : array_like, shape (npoints, )
        Known x-coordinates. Must be sorted in increasing order.
    yi : array_like, shape (..., npoints, ...)
        Known y-coordinates. When an xi occurs two or more times in
        a row, the corresponding yi's represent derivative values. The length of `yi`
        along the interpolation axis must be equal to the length of `xi`. Use the
        `axis` parameter to select the correct axis.
    axis : int, optional
        Axis in the `yi` array corresponding to the x-coordinate values. Defaults to
        ``axis=0``.

    Notes
    -----
    Be aware that the algorithms implemented here are not necessarily
    the most numerically stable known. Moreover, even in a world of
    exact computation, unless the x coordinates are chosen very
    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
    polynomial interpolation itself is a very ill-conditioned process
    due to the Runge phenomenon. In general, even with well-chosen
    x values, degrees higher than about thirty cause problems with
    numerical instability in this code.

    Based on [1]_.

    References
    ----------
    .. [1] Krogh, "Efficient Algorithms for Polynomial Interpolation
        and Numerical Differentiation", 1970.

    Examples
    --------
    To produce a polynomial that is zero at 0 and 1 and has
    derivative 2 at 0, call

    >>> from scipy.interpolate import KroghInterpolator
    >>> KroghInterpolator([0,0,1],[0,2,0])

    This constructs the quadratic :math:`2x^2-2x`. The derivative condition
    is indicated by the repeated zero in the `xi` array; the corresponding
    yi values are 0, the function value, and 2, the derivative value.

    For another example, given `xi`, `yi`, and a derivative `ypi` for each
    point, appropriate arrays can be constructed as:

    >>> import numpy as np
    >>> rng = np.random.default_rng()
    >>> xi = np.linspace(0, 1, 5)
    >>> yi, ypi = rng.random((2, 5))
    >>> xi_k, yi_k = np.repeat(xi, 2), np.ravel(np.dstack((yi,ypi)))
    >>> KroghInterpolator(xi_k, yi_k)

    To produce a vector-valued polynomial, supply a higher-dimensional
    array for `yi`:

    >>> KroghInterpolator([0,1],[[2,3],[4,5]])

    This constructs a linear polynomial giving (2,3) at 0 and (4,5) at 1.

    r   c           
         s  t  ||| t|| _| || _| jj\| _| _	| jj
 }dkr\tj| ddd tj| jd | j	f| jd}| jd |d< tj| j| j	f| jd}td| jD ]}d}||kr|||  || kr|d7 }q|d8 }| j| t| |d< t|| D ]}	||	 || kr td|dkrT||	 ||	  ||	 ||   ||	d < n,||	d  ||	  ||	 ||   ||	d < q|||  ||< q|| _d S )	N   zv degrees provided, degrees higher than about thirty cause problems with numerical instability with 'KroghInterpolator'   )
stacklevelr.   r   r   z Elements of `xi` can't be equal.)superr   r   r0   r   r4   r   r   nrsizewarningswarnzerosr   r)   r   r2   c)
r   r   r   r   degrP   ZVkkr-   i	__class__r   r   r   @  s2    

*0zKroghInterpolator.__init__c                 C   s   d}t jt|| jf| jd}|| jdt jd d f 7 }td| jD ]>}|| j	|d   }|| }||d d t jf | j|  7 }qD|S )Nr.   rH   r   )
r   rO   r'   rK   r   rP   newaxisr)   rJ   r   )r   r   piprR   wr   r   r   r   _  s    "zKroghInterpolator._evaluateNc                 C   s  | j }| j}|d u r| j }t|t|f}t|t|f}d|d< tjt|| jf| jd}|| jdtjd d f 7 }td|D ]\}|| j	|d   ||d < ||d  ||d   ||< |||d d tjf | j|  7 }qtjt
||d t||f| jd}	|	d |d d d d d f  | jd |d tjd d f 7  < ||	d< td|D ]}td|| d D ]Z}
|||
 d  ||
d   ||
  ||
< |	| ||
d d tjf |	||
    |	|< qn|	|  t|9  < qXd|	|d d d d f< |	d | S )Nr.   r   rH   )rJ   rK   r   rO   r'   r   rP   rV   r)   r   maxr   )r   r   r@   rJ   rK   rW   rY   rX   rR   cnrS   r   r   r   r?   i  s.    $$@(0z'KroghInterpolator._evaluate_derivatives)r   )N)r9   r:   r;   r<   r   r   r?   __classcell__r   r   rT   r   r      s   K
r   c                 C   sT   t | ||d}|dkr||S t|r4|j||dS |j|t|d d| S dS )a  
    Convenience function for polynomial interpolation.

    See `KroghInterpolator` for more details.

    Parameters
    ----------
    xi : array_like
        Interpolation points (known x-coordinates).
    yi : array_like
        Known y-coordinates, of shape ``(xi.size, R)``. Interpreted as
        vectors of length R, or scalars if R=1.
    x : array_like
        Point or points at which to evaluate the derivatives.
    der : int or list or None, optional
        How many derivatives to evaluate, or None for all potentially
        nonzero derivatives (that is, a number equal to the number
        of points), or a list of derivatives to evaluate. This number
        includes the function value as the '0th' derivative.
    axis : int, optional
        Axis in the `yi` array corresponding to the x-coordinate values.

    Returns
    -------
    d : ndarray
        If the interpolator's values are R-D then the
        returned array will be the number of derivatives by N by R.
        If `x` is a scalar, the middle dimension will be dropped; if
        the `yi` are scalars then the last dimension will be dropped.

    See Also
    --------
    KroghInterpolator : Krogh interpolator

    Notes
    -----
    Construction of the interpolating polynomial is a relatively expensive
    process. If you want to evaluate it repeatedly consider using the class
    KroghInterpolator (which is what this function uses).

    Examples
    --------
    We can interpolate 2D observed data using Krogh interpolation:

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.interpolate import krogh_interpolate
    >>> x_observed = np.linspace(0.0, 10.0, 11)
    >>> y_observed = np.sin(x_observed)
    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
    >>> y = krogh_interpolate(x_observed, y_observed, x)
    >>> plt.plot(x_observed, y_observed, "o", label="observation")
    >>> plt.plot(x, y, label="krogh interpolation")
    >>> plt.legend()
    >>> plt.show()
    r   r   r@   r.   N)r   r   rD   rA   r   amax)r   r   r   r@   r   Pr   r   r   r     s    :r   c           	   	   C   s   |du r|}|d }|t t jdt j||d d | }t|| |}|j||d d}t |tt |d  ddd S )a\  
    Estimate the Taylor polynomial of f at x by polynomial fitting.

    Parameters
    ----------
    f : callable
        The function whose Taylor polynomial is sought. Should accept
        a vector of `x` values.
    x : scalar
        The point at which the polynomial is to be evaluated.
    degree : int
        The degree of the Taylor polynomial
    scale : scalar
        The width of the interval to use to evaluate the Taylor polynomial.
        Function values spread over a range this wide are used to fit the
        polynomial. Must be chosen carefully.
    order : int or None, optional
        The order of the polynomial to be used in the fitting; `f` will be
        evaluated ``order+1`` times. If None, use `degree`.

    Returns
    -------
    p : poly1d instance
        The Taylor polynomial (translated to the origin, so that
        for example p(0)=f(x)).

    Notes
    -----
    The appropriate choice of "scale" is a trade-off; too large and the
    function differs from its Taylor polynomial too much to get a good
    answer, too small and round-off errors overwhelm the higher-order terms.
    The algorithm used becomes numerically unstable around order 30 even
    under ideal circumstances.

    Choosing order somewhat larger than degree may improve the higher-order
    terms.

    Examples
    --------
    We can calculate Taylor approximation polynomials of sin function with
    various degrees:

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.interpolate import approximate_taylor_polynomial
    >>> x = np.linspace(-10.0, 10.0, num=100)
    >>> plt.plot(x, np.sin(x), label="sin curve")
    >>> for degree in np.arange(1, 15, step=2):
    ...     sin_taylor = approximate_taylor_polynomial(np.sin, 0, degree, 1,
    ...                                                order=degree + 2)
    ...     plt.plot(x, sin_taylor(x), label=f"degree={degree}")
    >>> plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left',
    ...            borderaxespad=0.0, shadow=True)
    >>> plt.tight_layout()
    >>> plt.axis([-10, 10, -10, 10])
    >>> plt.show()

    Nr.   r   )Zendpointr^   r/   )	r   cosZlinspacerW   r   rA   Zpoly1dr   arange)	fr   ZdegreescaleorderrJ   Zxsr`   dr   r   r   r
     s    ;&r
   c                       sb   e Zd ZdZdddd fddZdddZdd	d
Zdd Zdd ZdddZ	dddZ
  ZS )r   a%  Interpolating polynomial for a set of points.

    Constructs a polynomial that passes through a given set of points.
    Allows evaluation of the polynomial and all its derivatives,
    efficient changing of the y-values to be interpolated,
    and updating by adding more x- and y-values.

    For reasons of numerical stability, this function does not compute
    the coefficients of the polynomial.

    The values `yi` need to be provided before the function is
    evaluated, but none of the preprocessing depends on them, so rapid
    updates are possible.

    Parameters
    ----------
    xi : array_like, shape (npoints, )
        1-D array of x coordinates of the points the polynomial
        should pass through
    yi : array_like, shape (..., npoints, ...), optional
        N-D array of y coordinates of the points the polynomial should pass through.
        If None, the y values will be supplied later via the `set_y` method.
        The length of `yi` along the interpolation axis must be equal to the length
        of `xi`. Use the ``axis`` parameter to select correct axis.
    axis : int, optional
        Axis in the yi array corresponding to the x-coordinate values. Defaults
        to ``axis=0``.
    wi : array_like, optional
        The barycentric weights for the chosen interpolation points `xi`.
        If absent or None, the weights will be computed from `xi` (default).
        This allows for the reuse of the weights `wi` if several interpolants
        are being calculated using the same nodes `xi`, without re-computation.
    random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Notes
    -----
    This class uses a "barycentric interpolation" method that treats
    the problem as a special case of rational function interpolation.
    This algorithm is quite stable, numerically, but even in a world of
    exact computation, unless the x coordinates are chosen very
    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
    polynomial interpolation itself is a very ill-conditioned process
    due to the Runge phenomenon.

    Based on Berrut and Trefethen 2004, "Barycentric Lagrange Interpolation".

    Examples
    --------
    To produce a quintic barycentric interpolant approximating the function
    :math:`\sin x`, and its first four derivatives, using six randomly-spaced
    nodes in :math:`(0, \frac{\pi}{2})`:

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.interpolate import BarycentricInterpolator
    >>> rng = np.random.default_rng()
    >>> xi = rng.random(6) * np.pi/2
    >>> f, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin
    >>> P = BarycentricInterpolator(xi, f(xi), random_state=rng)
    >>> fig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10))
    >>> x = np.linspace(0, np.pi, 100)
    >>> axs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk')
    >>> axs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk')
    >>> axs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk')
    >>> axs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk')
    >>> axs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk')
    >>> axs[0].set_xlim(0, np.pi)
    >>> axs[4].set_xlabel(r"$x$")
    >>> axs[4].set_xticks([i * np.pi / 4 for i in range(5)],
    ...                   ["0", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$"])
    >>> axs[0].set_ylabel("$f(x)$")
    >>> axs[1].set_ylabel("$f'(x)$")
    >>> axs[2].set_ylabel("$f''(x)$")
    >>> axs[3].set_ylabel("$f^{(3)}(x)$")
    >>> axs[4].set_ylabel("$f^{(4)}(x)$")
    >>> labels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation']
    >>> axs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102),
    ...               loc='lower left', ncols=3, mode="expand", borderaxespad=0., frameon=False)
    >>> plt.show()
    Nr   )wirandom_statec                   s  t  ||| t|}tj|tjd| _| | t| j| _	d | _
|d urV|| _ndt| jt| j  | _|| j	}tj| j	tjd}t| j	||< t| j	| _t| j	D ]R}| j| j| | j|   }	d|	|| < t|	}
|
dkrtdd|
 | j|< qd S )NrH   g      @g      ?g        z)Interpolation points xi must be distinct.)rI   r   r   r   r0   r7   r   set_yir'   rJ   	_diff_cijrg   rZ   min_inv_capacityZpermutationrO   Zint32rb   r)   prodr2   )r   r   r   r   rg   rh   ZpermuteZinv_permuterS   distrm   rT   r   r   r   n  s(    


z BarycentricInterpolator.__init__c                 C   sJ   |du rd| _ dS | j|| j|d | || _ | j j\| _| _d| _dS )a  
        Update the y values to be interpolated

        The barycentric interpolation algorithm requires the calculation
        of weights, but these depend only on the `xi`. The `yi` can be changed
        at any time.

        Parameters
        ----------
        yi : array_like
            The y-coordinates of the points the polynomial will pass through.
            If None, the y values must be supplied later.
        axis : int, optional
            Axis in the `yi` array corresponding to the x-coordinate values.

        Nr   )r   r   r   r4   r   rJ   rK   _diff_baryint)r   r   r   r   r   r   ri     s    zBarycentricInterpolator.set_yic              	   C   s.  |dur<| j du rtd| j|dd}t| j |f| _ n| j durNtd| j}t| j|f| _t| j| _|  j	dC  _	| j	}t
| j| _	|| j	d|< t|| jD ]`}| j	d|  | j| j| | jd|   9  < tj| j| jd| | j|   | j	|< q|  j	dC  _	d| _d| _dS )a  
        Add more x values to the set to be interpolated

        The barycentric interpolation algorithm allows easy updating by
        adding more points for the polynomial to pass through.

        Parameters
        ----------
        xi : array_like
            The x coordinates of the points that the polynomial should pass
            through.
        yi : array_like, optional
            The y coordinates of the points the polynomial should pass through.
            Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is
            vector-valued.
            If `yi` is not given, the y values will be supplied later. `yi`
            should be given if and only if the interpolator has y values
            specified.

        Notes
        -----
        The new points added by `add_xi` are not randomly permuted
        so there is potential for numerical instability,
        especially for a large number of points. If this
        happens, please reconstruct interpolation from scratch instead.
        NzNo previous yi value to update!T)r3   zNo update to yi provided!r/   )r   r2   r4   r   ZvstackrJ   Zconcatenater   r'   rg   rO   r)   rl   multiplyreducerj   ro   )r   r   r   Zold_nZold_wijr   r   r   add_xi  s,    

0zBarycentricInterpolator.add_xic                 C   s   t | |S )av  Evaluate the interpolating polynomial at the points x

        Parameters
        ----------
        x : array_like
            Point or points at which to evaluate the interpolant.

        Returns
        -------
        y : array_like
            Interpolated values. Shape is determined by replacing
            the interpolation axis in the original array with the shape of `x`.

        Notes
        -----
        Currently the code computes an outer product between `x` and the
        weights, that is, it constructs an intermediate array of size
        ``(N, len(x))``, where N is the degree of the polynomial.
        )r   r"   r%   r   r   r   r"     s    z BarycentricInterpolator.__call__c                 C   s   |j dkr"tjd| jf| jd}n|dtjf | j }|dk}d||< | j| }tjdd6 t	|| j
tj|dddtjf  }W d    n1 s0    Y  t|}t|dkrt|d dkr| j
|d d  }n| j
|d  ||d d < |S )	Nr   rH   .r.   ignore)divider/   r]   )rL   r   rO   rK   r   rV   r   rg   Zerrstatedotr   sumZnonzeror'   )r   r   rX   rP   zrK   r   r   r   r     s    

D
z!BarycentricInterpolator._evaluater.   c                 C   s.   |  |\}}| j||d dd}| ||S )aj  
        Evaluate a single derivative of the polynomial at the point x.

        Parameters
        ----------
        x : array_like
            Point or points at which to evaluate the derivatives
        der : integer, optional
            Which derivative to evaluate (default: first derivative).
            This number includes the function value as 0th derivative.

        Returns
        -------
        d : ndarray
            Derivative interpolated at the x-points. Shape of `d` is
            determined by replacing the interpolation axis in the
            original array with the shape of `x`.
        r.   F	all_lowerrB   rC   r   r   r   rD   	  s    z"BarycentricInterpolator.derivativeTc                 C   s  |s.|j dks| jdkr.tjd| jf| jdS |sD|dkrD| |S |sl|| jkrltjt|| jf| jdS |d u rz| j}|r|j dks| jdkrtj|t|| jf| jdS | jd u r&| j	d d tj
f | j	 }t|d | j|| jdtj
f   }t|d |jdd }t|| || _| jd u rXt| j	| j| j | jd| _| j| j_|rtj|t|| jf| jd}t|D ],}| j||d dd||d d d d f< q|S | jj||d ddS )	Nr   rH   r.   .r]   )r   r   rg   Fry   )rL   rK   r   rO   r   r   rJ   r'   rj   r   rV   Zfill_diagonalrg   rw   ro   r   r   r)   r?   )r   r   r@   rz   rP   rf   r[   r   r   r   r?      s<    


*z-BarycentricInterpolator._evaluate_derivatives)Nr   )N)N)r.   )NT)r9   r:   r;   r<   r   ri   rs   r"   r   rD   r?   r\   r   r   rT   r   r     s   W&

3
r   r^   c                C   sT   t | ||d}|dkr||S t|r4|j||dS |j|t|d d| S dS )aS
  
    Convenience function for polynomial interpolation.

    Constructs a polynomial that passes through a given set of points,
    then evaluates the polynomial. For reasons of numerical stability,
    this function does not compute the coefficients of the polynomial.

    This function uses a "barycentric interpolation" method that treats
    the problem as a special case of rational function interpolation.
    This algorithm is quite stable, numerically, but even in a world of
    exact computation, unless the `x` coordinates are chosen very
    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
    polynomial interpolation itself is a very ill-conditioned process
    due to the Runge phenomenon.

    Parameters
    ----------
    xi : array_like
        1-D array of x coordinates of the points the polynomial should
        pass through
    yi : array_like
        The y coordinates of the points the polynomial should pass through.
    x : scalar or array_like
        Point or points at which to evaluate the interpolant.
    der : int or list or None, optional
        How many derivatives to evaluate, or None for all potentially
        nonzero derivatives (that is, a number equal to the number
        of points), or a list of derivatives to evaluate. This number
        includes the function value as the '0th' derivative.
    axis : int, optional
        Axis in the `yi` array corresponding to the x-coordinate values.

    Returns
    -------
    y : scalar or array_like
        Interpolated values. Shape is determined by replacing
        the interpolation axis in the original array with the shape of `x`.

    See Also
    --------
    BarycentricInterpolator : Barycentric interpolator

    Notes
    -----
    Construction of the interpolation weights is a relatively slow process.
    If you want to call this many times with the same xi (but possibly
    varying yi or x) you should use the class `BarycentricInterpolator`.
    This is what this function uses internally.

    Examples
    --------
    We can interpolate 2D observed data using barycentric interpolation:

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.interpolate import barycentric_interpolate
    >>> x_observed = np.linspace(0.0, 10.0, 11)
    >>> y_observed = np.sin(x_observed)
    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
    >>> y = barycentric_interpolate(x_observed, y_observed, x)
    >>> plt.plot(x_observed, y_observed, "o", label="observation")
    >>> plt.plot(x, y, label="barycentric interpolation")
    >>> plt.legend()
    >>> plt.show()

    r]   r   r^   r.   N)r   r   rD   rA   r   r_   )r   r   r   r   r@   r`   r   r   r   r	   a  s    Cr	   )r   r   )N)r   )rM   numpyr   Zscipy.specialr   Zscipy._lib._utilr   r   r   __all__r   r   r>   r   r   r
   r   r	   r   r   r   r   <module>   s   ~d 
C
K  M