a
    BCCf                     @  s   d Z ddlmZ ddlm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 erddd	lmZ g d
ZdddZG dd deZG dd deZdddZG dd deZG dd deZdS )z;Interpolation algorithms using piecewise cubic polynomials.    )annotations)TYPE_CHECKINGN)solvesolve_banded   )PPoly)	_isscalar)Literal)CubicHermiteSplinePchipInterpolatorpchip_interpolateAkima1DInterpolatorCubicSplinec                 C  s  t tj| |f\} }t| jtjr,td| t} t|jtjrLt	}nt}|durt|}|j
|j
krvtdt|jtjrt	}|j|dd}|j|dd}||j }| jdkrtd| j
d d	k rtd
| j
d |j
| krtd| dtt| stdtt|s0td|durTtt|sTtdt| }t|dkrvtdt||d}|durt||d}| ||||fS )a   Prepare input for cubic spline interpolators.

    All data are converted to numpy arrays and checked for correctness.
    Axes equal to `axis` of arrays `y` and `dydx` are moved to be the 0th
    axis. The value of `axis` is converted to lie in
    [0, number of dimensions of `y`).
    z`x` must contain real values.Nz/The shapes of `y` and `dydx` must be identical.Fcopyr   z`x` must be 1-dimensional.r      z%`x` must contain at least 2 elements.zThe length of `y` along `axis`=z  doesn't match the length of `x`z$`x` must contain only finite values.z$`y` must contain only finite values.z'`dydx` must contain only finite values.z)`x` must be strictly increasing sequence.)mapnpasarray
issubdtypedtypecomplexfloating
ValueErrorastypefloatcomplexshapendimallisfinitediffanyZmoveaxis)xyaxisdydxr   dx r'   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/interpolate/_cubic.pyprepare_input   sF    	





r)   c                      s"   e Zd ZdZd fdd	Z  ZS )r
   a	  Piecewise-cubic interpolator matching values and first derivatives.

    The result is represented as a `PPoly` instance.

    Parameters
    ----------
    x : array_like, shape (n,)
        1-D array containing values of the independent variable.
        Values must be real, finite and in strictly increasing order.
    y : array_like
        Array containing values of the dependent variable. It can have
        arbitrary number of dimensions, but the length along ``axis``
        (see below) must match the length of ``x``. Values must be finite.
    dydx : array_like
        Array containing derivatives of the dependent variable. It can have
        arbitrary number of dimensions, but the length along ``axis``
        (see below) must match the length of ``x``. Values must be finite.
    axis : int, optional
        Axis along which `y` is assumed to be varying. Meaning that for
        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
        Default is 0.
    extrapolate : {bool, 'periodic', None}, optional
        If bool, determines whether to extrapolate to out-of-bounds points
        based on first and last intervals, or to return NaNs. If 'periodic',
        periodic extrapolation is used. If None (default), it is set to True.

    Attributes
    ----------
    x : ndarray, shape (n,)
        Breakpoints. The same ``x`` which was passed to the constructor.
    c : ndarray, shape (4, n-1, ...)
        Coefficients of the polynomials on each segment. The trailing
        dimensions match the dimensions of `y`, excluding ``axis``.
        For example, if `y` is 1-D, then ``c[k, i]`` is a coefficient for
        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
    axis : int
        Interpolation axis. The same axis which was passed to the
        constructor.

    Methods
    -------
    __call__
    derivative
    antiderivative
    integrate
    roots

    See Also
    --------
    Akima1DInterpolator : Akima 1D interpolator.
    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
    CubicSpline : Cubic spline data interpolator.
    PPoly : Piecewise polynomial in terms of coefficients and breakpoints

    Notes
    -----
    If you want to create a higher-order spline matching higher-order
    derivatives, use `BPoly.from_derivatives`.

    References
    ----------
    .. [1] `Cubic Hermite spline
            <https://en.wikipedia.org/wiki/Cubic_Hermite_spline>`_
            on Wikipedia.
    r   Nc                   s
  |d u rd}t ||||\}}}}}||jd gdg|jd   }tj|dd| }|d d |dd   d|  | }	tjdt|d f|jdd   |	jd}
|	| |
d< ||d d  | |	 |
d< |d d |
d< |d d |
d	< t	 j
|
||d
 || _d S )NTr   r   r$   r      r      )extrapolate)r)   reshaper   r   r   r    emptylenr   super__init__r$   )selfr"   r#   r%   r$   r/   r&   dxrslopetc	__class__r'   r(   r4      s    "$*zCubicHermiteSpline.__init__)r   N)__name__
__module____qualname____doc__r4   __classcell__r'   r'   r:   r(   r
   O   s   Br
   c                      s:   e Zd ZdZd
 fdd	Zedd Zedd	 Z  ZS )r   a0  PCHIP 1-D monotonic cubic interpolation.

    ``x`` and ``y`` are arrays of values used to approximate some function f,
    with ``y = f(x)``. The interpolant uses monotonic cubic splines
    to find the value of new points. (PCHIP stands for Piecewise Cubic
    Hermite Interpolating Polynomial).

    Parameters
    ----------
    x : ndarray, shape (npoints, )
        A 1-D array of monotonically increasing real values. ``x`` cannot
        include duplicate values (otherwise f is overspecified)
    y : ndarray, shape (..., npoints, ...)
        A N-D array of real values. ``y``'s length along the interpolation
        axis must be equal to the length of ``x``. Use the ``axis``
        parameter to select the interpolation axis.

        .. deprecated:: 1.13.0
            Complex data is deprecated and will raise an error in SciPy 1.15.0.
            If you are trying to use the real components of the passed array,
            use ``np.real`` on ``y``.

    axis : int, optional
        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
        to ``axis=0``.
    extrapolate : bool, optional
        Whether to extrapolate to out-of-bounds points based on first
        and last intervals, or to return NaNs.

    Methods
    -------
    __call__
    derivative
    antiderivative
    roots

    See Also
    --------
    CubicHermiteSpline : Piecewise-cubic interpolator.
    Akima1DInterpolator : Akima 1D interpolator.
    CubicSpline : Cubic spline data interpolator.
    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.

    Notes
    -----
    The interpolator preserves monotonicity in the interpolation data and does
    not overshoot if the data is not smooth.

    The first derivatives are guaranteed to be continuous, but the second
    derivatives may jump at :math:`x_k`.

    Determines the derivatives at the points :math:`x_k`, :math:`f'_k`,
    by using PCHIP algorithm [1]_.

    Let :math:`h_k = x_{k+1} - x_k`, and  :math:`d_k = (y_{k+1} - y_k) / h_k`
    are the slopes at internal points :math:`x_k`.
    If the signs of :math:`d_k` and :math:`d_{k-1}` are different or either of
    them equals zero, then :math:`f'_k = 0`. Otherwise, it is given by the
    weighted harmonic mean

    .. math::

        \frac{w_1 + w_2}{f'_k} = \frac{w_1}{d_{k-1}} + \frac{w_2}{d_k}

    where :math:`w_1 = 2 h_k + h_{k-1}` and :math:`w_2 = h_k + 2 h_{k-1}`.

    The end slopes are set using a one-sided scheme [2]_.


    References
    ----------
    .. [1] F. N. Fritsch and J. Butland,
           A method for constructing local
           monotone piecewise cubic interpolants,
           SIAM J. Sci. Comput., 5(2), 300-304 (1984).
           :doi:`10.1137/0905021`.
    .. [2] see, e.g., C. Moler, Numerical Computing with Matlab, 2004.
           :doi:`10.1137/1.9780898717952`

    r   Nc           	        s   t |||\}}}}}t|r4d}tj|tdd ||jd fd|jd   }| 	||}t
 j|||d|d || _d S )Na!  `PchipInterpolator` only works with real values for `y`. Passing an array with a complex dtype for `y` is deprecated and will raise an error in SciPy 1.15.0. If you are trying to use the real components of the passed array, use `np.real` on the array before passing to `PchipInterpolator`.r   
stacklevelr   )r   r   r$   r/   )r)   r   iscomplexobjwarningswarnDeprecationWarningr0   r   r   _find_derivativesr3   r4   r$   )	r5   r"   r#   r$   r/   _msgZxpdkr:   r'   r(   r4      s    
 zPchipInterpolator.__init__c                 C  s   d|  | | | |  | |  }t |t |k}t |t |kt |dt | k@ }| |@ }d||< d||  ||< |S )Nr   g      @        )r   signabs)Zh0Zh1Zm0m1dmaskZmask2Zmmmr'   r'   r(   
_edge_case  s     ,
zPchipInterpolator._edge_casec                 C  s  |j }|jdkr0| d d d f } |d d d f }| dd  | d d  }|dd  |d d  | }|j d dkrt|}||d< ||d< ||S t|}|dd  |d d k|dd  dkB |d d dkB }d|dd   |d d  }|dd  d|d d   }	tjddd8 ||d d  |	|dd    ||	  }
W d    n1 s^0    Y  t|}d|dd |< d|
|   |dd | < t|d |d |d |d |d< t|d |d	 |d |d	 |d< ||S )
Nr   r+   r   r   ignore)divideinvalidrL         ?)	r   r   r   
zeros_liker0   rM   Zerrstater   rR   )r"   r#   Zy_shapeZhkmkrK   Zsmk	conditionZw1Zw2Zwhmeanr'   r'   r(   rH     s.    



8H
$$z#PchipInterpolator._find_derivatives)r   N)	r<   r=   r>   r?   r4   staticmethodrR   rH   r@   r'   r'   r:   r(   r      s   Q
r   c                   sL   t | ||d |dkr S t|r4 |S  fdd|D S dS )a  
    Convenience function for pchip interpolation.

    xi and yi are arrays of values used to approximate some function f,
    with ``yi = f(xi)``. The interpolant uses monotonic cubic splines
    to find the value of new points x and the derivatives there.

    See `scipy.interpolate.PchipInterpolator` for details.

    Parameters
    ----------
    xi : array_like
        A sorted list of x-coordinates, of length N.
    yi : array_like
        A 1-D array of real values. `yi`'s length along the interpolation
        axis must be equal to the length of `xi`. If N-D array, use axis
        parameter to select correct axis.

        .. deprecated:: 1.13.0
            Complex data is deprecated and will raise an error in
            SciPy 1.15.0. If you are trying to use the real components of
            the passed array, use ``np.real`` on `yi`.

    x : scalar or array_like
        Of length M.
    der : int or list, optional
        Derivatives to extract. The 0th derivative can be included to
        return the function value.
    axis : int, optional
        Axis in the yi array corresponding to the x-coordinate values.

    Returns
    -------
    y : scalar or array_like
        The result, of length R or length M or M by R.

    See Also
    --------
    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.

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

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.interpolate import pchip_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 = pchip_interpolate(x_observed, y_observed, x)
    >>> plt.plot(x_observed, y_observed, "o", label="observation")
    >>> plt.plot(x, y, label="pchip interpolation")
    >>> plt.legend()
    >>> plt.show()

    r*   r   c                   s   g | ]}  |qS r'   )
derivative).0nuPr"   r'   r(   
<listcomp>      z%pchip_interpolate.<locals>.<listcomp>N)r   r   r\   )xiyir"   Zderr$   r'   r_   r(   r   G  s    :r   c                      sT   e Zd ZdZddddd fddZdd	d
ZedddZedddZ  Z	S )r   aL  
    Akima interpolator

    Fit piecewise cubic polynomials, given vectors x and y. The interpolation
    method by Akima uses a continuously differentiable sub-spline built from
    piecewise cubic polynomials. The resultant curve passes through the given
    data points and will appear smooth and natural.

    Parameters
    ----------
    x : ndarray, shape (npoints, )
        1-D array of monotonically increasing real values.
    y : ndarray, shape (..., npoints, ...)
        N-D array of real values. The length of ``y`` along the interpolation axis
        must be equal to the length of ``x``. Use the ``axis`` parameter to
        select the interpolation axis.

        .. deprecated:: 1.13.0
            Complex data is deprecated and will raise an error in SciPy 1.15.0.
            If you are trying to use the real components of the passed array,
            use ``np.real`` on ``y``.

    axis : int, optional
        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
        to ``axis=0``.
    method : {'akima', 'makima'}, optional
        If ``"makima"``, use the modified Akima interpolation [2]_.
        Defaults to ``"akima"``, use the Akima interpolation [1]_.

        .. versionadded:: 1.13.0

    Methods
    -------
    __call__
    derivative
    antiderivative
    roots

    See Also
    --------
    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
    CubicSpline : Cubic spline data interpolator.
    PPoly : Piecewise polynomial in terms of coefficients and breakpoints

    Notes
    -----
    .. versionadded:: 0.14

    Use only for precise data, as the fitted curve passes through the given
    points exactly. This routine is useful for plotting a pleasingly smooth
    curve through a few given points for purposes of plotting.

    Let :math:`\delta_i = (y_{i+1} - y_i) / (x_{i+1} - x_i)` be the slopes of
    the interval :math:`\left[x_i, x_{i+1}\right)`. Akima's derivative at
    :math:`x_i` is defined as:

    .. math::

        d_i = \frac{w_1}{w_1 + w_2}\delta_{i-1} + \frac{w_2}{w_1 + w_2}\delta_i

    In the Akima interpolation [1]_ (``method="akima"``), the weights are:

    .. math::

        \begin{aligned}
        w_1 &= |\delta_{i+1} - \delta_i| \\
        w_2 &= |\delta_{i-1} - \delta_{i-2}|
        \end{aligned}

    In the modified Akima interpolation [2]_ (``method="makima"``),
    to eliminate overshoot and avoid edge cases of both numerator and
    denominator being equal to 0, the weights are modified as follows:

    .. math::

        \begin{align*}
        w_1 &= |\delta_{i+1} - \delta_i| + |\delta_{i+1} + \delta_i| / 2 \\
        w_2 &= |\delta_{i-1} - \delta_{i-2}| + |\delta_{i-1} + \delta_{i-2}| / 2
        \end{align*}

    Examples
    --------
    Comparison of ``method="akima"`` and ``method="makima"``:

    >>> import numpy as np
    >>> from scipy.interpolate import Akima1DInterpolator
    >>> import matplotlib.pyplot as plt
    >>> x = np.linspace(1, 7, 7)
    >>> y = np.array([-1, -1, -1, 0, 1, 1, 1])
    >>> xs = np.linspace(min(x), max(x), num=100)
    >>> y_akima = Akima1DInterpolator(x, y, method="akima")(xs)
    >>> y_makima = Akima1DInterpolator(x, y, method="makima")(xs)

    >>> fig, ax = plt.subplots()
    >>> ax.plot(x, y, "o", label="data")
    >>> ax.plot(xs, y_akima, label="akima")
    >>> ax.plot(xs, y_makima, label="makima")
    >>> ax.legend()
    >>> fig.show()

    The overshoot that occured in ``"akima"`` has been avoided in ``"makima"``.

    References
    ----------
    .. [1] A new method of interpolation and smooth curve fitting based
           on local procedures. Hiroshi Akima, J. ACM, October 1970, 17(4),
           589-602. :doi:`10.1145/321607.321609`
    .. [2] Makima Piecewise Cubic Interpolation. Cleve Moler and Cosmin Ionita, 2019.
           https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/

    r   akima)methodzLiteral['akima', 'makima']c                  sJ  |dvrt d| dt|||\}}}}}t|rLd}tj|tdd t|jd f|j	dd   }|t
d fd	|jd    }tj|d
d| |dd< d|d  |d  |d< d|d  |d  |d
< d|d  |d  |d< d|d  |d  |d< d|dd  |d d   }	ttj|d
d}
|dkrt|dd  |d d  }|
dd  d|dd    }|
d d d|d d   }n|
dd  }|
d d }|| }t|dtj|tj d k}|d
 |dd   }}|| ||d f|   || ||d f|    ||  |	|< t j|||	d
dd || _d S )N>   makimare   z	`method`=z is unsupported.a%  `Akima1DInterpolator` only works with real values for `y`. Passing an array with a complex dtype for `y` is deprecated and will raise an error in SciPy 1.15.0. If you are trying to use the real components of the passed array, use `np.real` on the array before passing to `Akima1DInterpolator`.r   rA   r.   r   )Nr   r*   rW   g       @r+         ?rg   g&.>)initialFrC   )NotImplementedErrorr)   r   rD   rE   rF   rG   r1   sizer   slicer   r    rN   Znonzeromaxinfr3   r4   r$   )r5   r"   r#   r$   rf   r&   rI   rJ   mr8   dmpmf1f2Zf12indZx_indZy_indr:   r'   r(   r4     s>    
 
 zAkima1DInterpolator.__init__Tc                 C  s   t dd S )Nz9Extending a 1-D Akima interpolator is not yet implementedrl   )r5   r9   r"   rightr'   r'   r(   extend.  s    zAkima1DInterpolator.extendNc                 C  s   t dd S Nz:This method does not make sense for an Akima interpolator.rw   )clsZtckr/   r'   r'   r(   from_spline4  s    zAkima1DInterpolator.from_splinec                 C  s   t dd S rz   rw   )r{   bpr/   r'   r'   r(   from_bernstein_basis9  s    z(Akima1DInterpolator.from_bernstein_basis)r   )T)N)N)
r<   r=   r>   r?   r4   ry   classmethodr|   r~   r@   r'   r'   r:   r(   r     s   p2
r   c                      s.   e Zd ZdZd	 fdd	Zedd Z  ZS )
r   a  Cubic spline data interpolator.

    Interpolate data with a piecewise cubic polynomial which is twice
    continuously differentiable [1]_. The result is represented as a `PPoly`
    instance with breakpoints matching the given data.

    Parameters
    ----------
    x : array_like, shape (n,)
        1-D array containing values of the independent variable.
        Values must be real, finite and in strictly increasing order.
    y : array_like
        Array containing values of the dependent variable. It can have
        arbitrary number of dimensions, but the length along ``axis``
        (see below) must match the length of ``x``. Values must be finite.
    axis : int, optional
        Axis along which `y` is assumed to be varying. Meaning that for
        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
        Default is 0.
    bc_type : string or 2-tuple, optional
        Boundary condition type. Two additional equations, given by the
        boundary conditions, are required to determine all coefficients of
        polynomials on each segment [2]_.

        If `bc_type` is a string, then the specified condition will be applied
        at both ends of a spline. Available conditions are:

        * 'not-a-knot' (default): The first and second segment at a curve end
          are the same polynomial. It is a good default when there is no
          information on boundary conditions.
        * 'periodic': The interpolated functions is assumed to be periodic
          of period ``x[-1] - x[0]``. The first and last value of `y` must be
          identical: ``y[0] == y[-1]``. This boundary condition will result in
          ``y'[0] == y'[-1]`` and ``y''[0] == y''[-1]``.
        * 'clamped': The first derivative at curves ends are zero. Assuming
          a 1D `y`, ``bc_type=((1, 0.0), (1, 0.0))`` is the same condition.
        * 'natural': The second derivative at curve ends are zero. Assuming
          a 1D `y`, ``bc_type=((2, 0.0), (2, 0.0))`` is the same condition.

        If `bc_type` is a 2-tuple, the first and the second value will be
        applied at the curve start and end respectively. The tuple values can
        be one of the previously mentioned strings (except 'periodic') or a
        tuple `(order, deriv_values)` allowing to specify arbitrary
        derivatives at curve ends:

        * `order`: the derivative order, 1 or 2.
        * `deriv_value`: array_like containing derivative values, shape must
          be the same as `y`, excluding ``axis`` dimension. For example, if
          `y` is 1-D, then `deriv_value` must be a scalar. If `y` is 3-D with
          the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2-D
          and have the shape (n0, n1).
    extrapolate : {bool, 'periodic', None}, optional
        If bool, determines whether to extrapolate to out-of-bounds points
        based on first and last intervals, or to return NaNs. If 'periodic',
        periodic extrapolation is used. If None (default), ``extrapolate`` is
        set to 'periodic' for ``bc_type='periodic'`` and to True otherwise.

    Attributes
    ----------
    x : ndarray, shape (n,)
        Breakpoints. The same ``x`` which was passed to the constructor.
    c : ndarray, shape (4, n-1, ...)
        Coefficients of the polynomials on each segment. The trailing
        dimensions match the dimensions of `y`, excluding ``axis``.
        For example, if `y` is 1-d, then ``c[k, i]`` is a coefficient for
        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
    axis : int
        Interpolation axis. The same axis which was passed to the
        constructor.

    Methods
    -------
    __call__
    derivative
    antiderivative
    integrate
    roots

    See Also
    --------
    Akima1DInterpolator : Akima 1D interpolator.
    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.

    Notes
    -----
    Parameters `bc_type` and ``extrapolate`` work independently, i.e. the
    former controls only construction of a spline, and the latter only
    evaluation.

    When a boundary condition is 'not-a-knot' and n = 2, it is replaced by
    a condition that the first derivative is equal to the linear interpolant
    slope. When both boundary conditions are 'not-a-knot' and n = 3, the
    solution is sought as a parabola passing through given points.

    When 'not-a-knot' boundary conditions is applied to both ends, the
    resulting spline will be the same as returned by `splrep` (with ``s=0``)
    and `InterpolatedUnivariateSpline`, but these two methods use a
    representation in B-spline basis.

    .. versionadded:: 0.18.0

    Examples
    --------
    In this example the cubic spline is used to interpolate a sampled sinusoid.
    You can see that the spline continuity property holds for the first and
    second derivatives and violates only for the third derivative.

    >>> import numpy as np
    >>> from scipy.interpolate import CubicSpline
    >>> import matplotlib.pyplot as plt
    >>> x = np.arange(10)
    >>> y = np.sin(x)
    >>> cs = CubicSpline(x, y)
    >>> xs = np.arange(-0.5, 9.6, 0.1)
    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
    >>> ax.plot(x, y, 'o', label='data')
    >>> ax.plot(xs, np.sin(xs), label='true')
    >>> ax.plot(xs, cs(xs), label="S")
    >>> ax.plot(xs, cs(xs, 1), label="S'")
    >>> ax.plot(xs, cs(xs, 2), label="S''")
    >>> ax.plot(xs, cs(xs, 3), label="S'''")
    >>> ax.set_xlim(-0.5, 9.5)
    >>> ax.legend(loc='lower left', ncol=2)
    >>> plt.show()

    In the second example, the unit circle is interpolated with a spline. A
    periodic boundary condition is used. You can see that the first derivative
    values, ds/dx=0, ds/dy=1 at the periodic point (1, 0) are correctly
    computed. Note that a circle cannot be exactly represented by a cubic
    spline. To increase precision, more breakpoints would be required.

    >>> theta = 2 * np.pi * np.linspace(0, 1, 5)
    >>> y = np.c_[np.cos(theta), np.sin(theta)]
    >>> cs = CubicSpline(theta, y, bc_type='periodic')
    >>> print("ds/dx={:.1f} ds/dy={:.1f}".format(cs(0, 1)[0], cs(0, 1)[1]))
    ds/dx=0.0 ds/dy=1.0
    >>> xs = 2 * np.pi * np.linspace(0, 1, 100)
    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
    >>> ax.plot(y[:, 0], y[:, 1], 'o', label='data')
    >>> ax.plot(np.cos(xs), np.sin(xs), label='true')
    >>> ax.plot(cs(xs)[:, 0], cs(xs)[:, 1], label='spline')
    >>> ax.axes.set_aspect('equal')
    >>> ax.legend(loc='center')
    >>> plt.show()

    The third example is the interpolation of a polynomial y = x**3 on the
    interval 0 <= x<= 1. A cubic spline can represent this function exactly.
    To achieve that we need to specify values and first derivatives at
    endpoints of the interval. Note that y' = 3 * x**2 and thus y'(0) = 0 and
    y'(1) = 3.

    >>> cs = CubicSpline([0, 1], [0, 1], bc_type=((1, 0), (1, 3)))
    >>> x = np.linspace(0, 1)
    >>> np.allclose(x**3, cs(x))
    True

    References
    ----------
    .. [1] `Cubic Spline Interpolation
            <https://en.wikiversity.org/wiki/Cubic_Spline_Interpolation>`_
            on Wikiversity.
    .. [2] Carl de Boor, "A Practical Guide to Splines", Springer-Verlag, 1978.
    r   
not-a-knotNc                   s  t |||\}}}}}t|}| |||jdd  |\}	}|d u rZ|	d dkrVd}nd}|jdkrrt|}
n^||jd gdg|jd   }tj	|dd| }|dkr|	d dv rd|d f|	d< |	d dv rd|d f|	d< |dkr|	d d	kr|	d d	krt
d
}tjd|jdd   |jd}d|d< d|d< |d |d< d|d |d   |d< |d |d< d|d< d|d< d|d  |d< d|d |d  |d |d    |d< d|d  |d< t||dddd}
n|dkr6|	d dkr6|| dd| d }t||f|jdd   }
nt
d|f}tj|f|jdd   |jd}d|d d |dd    |dddf< |d d |ddd f< |dd  |dd df< d|dd  |d d  |d d |dd     |dd< |	\}}|dkr|d d ddf }d|d |d   |d< |d |d< |d d }|d }|d }d|d |d   }|d }|d }d|d |d  |d |d    |d< d|d |d  |d |d    |d< |d d d df }|d d }t|}| |d< | |d< td||dddd}td||dddd}|d ||d   ||d   |||d   ||d    }tj|f|jdd   |jd}
|||  |
d d< ||
d< |
d |
d< n|d	kr8|d |d< |d |d  |d< |d |d  }|d d|  |d  |d  |d d |d   | |d< n|d dkrdd|d< d|d< |d |d< nZ|d dkrd|d  |d< |d |d< d|d  |d d  d|d |d    |d< |d	kr6|d |d< |d |d  |d< |d |d  }|d d |d  d| |d  |d  |d   | |d< n|d dkrbd|d< d|d< |d |d< nZ|d dkrd|d  |d< |d |d< d|d  |d d  d|d |d    |d< td||dddd}
t j|||
d|d || _d S ) Nr   r   periodicTr*   r   r   r   r.   r   )r.   r.   )r.   r-   )r   r   )r   r   )r   r   )r   r   r   r   )r   r   )r   r   F)Zoverwrite_aoverwrite_bcheck_finiterV   r+   rW   rh   )Zoverwrite_abr   r   g      )r   r+   )r+   rW   rj   rC   )r)   r2   _validate_bcr   rm   r   rX   r0   r   r    zerosr1   r   r   sumZbroadcast_tor   r3   r4   r$   )r5   r"   r#   r$   bc_typer/   r&   rI   nbcsr6   r7   Abr8   Zbc_startZbc_endZa_m1_0Za_m1_m2Za_m1_m1Za_m2_m1Za_0_m1ZAcb1b2s1s2Zs_m1rP   r:   r'   r(   r4     s    
"&
(

  	(<

((




 

0

0
zCubicSpline.__init__c           	      C  s  t | trF| dkr<tj|d |d ddds<td| d| | f} n$t| dkrZtd	d| v rjtd
g }| D ]}t |tr|dkr|dt|f nB|dkr|dt|f n$|dv r|| ntd| dqrz|\}}W n0 ty  } ztd|W Y d}~n
d}~0 0 |dvr4tdt	|}|j
|kr\td|j
|t|jtjr||jtdd}|||f qr||fS )a(  Validate and prepare boundary conditions.

        Returns
        -------
        validated_bc : 2-tuple
            Boundary conditions for a curve start and end.
        y : ndarray
            y casted to complex dtype if one of the boundary conditions has
            complex dtype.
        r   r   r+   gV瞯<)ZrtolZatolz(The first and last `y` point along axis zF must be identical (within machine precision) when bc_type='periodic'.r   zF`bc_type` must contain 2 elements to specify start and end conditions.zf'periodic' `bc_type` is defined for both curve ends and cannot be used with other boundary conditions.Zclampedr   Znaturalr   zbc_type=z is not allowed.zFA specified derivative value must be given in the form (order, value).Nr   z.The specified derivative order must be 1 or 2.z2`deriv_value` shape {} is not the expected one {}.Fr   )
isinstancestrr   Zallcloser   r2   appendr   	Exceptionr   r   formatr   r   r   r   r   )	r   r#   Zexpected_deriv_shaper$   Zvalidated_bcr   Zderiv_orderZderiv_valueer'   r'   r(   r     sT    






zCubicSpline._validate_bc)r   r   N)r<   r=   r>   r?   r4   r[   r   r@   r'   r'   r:   r(   r   ?  s    & #r   )N)r   r   )r?   
__future__r   typingr   rE   numpyr   Zscipy.linalgr   r    r   Z_polyintr   r	   __all__r)   r
   r   r   r   r   r'   r'   r'   r(   <module>   s$   
8W "
D 5