a
    BCCf{                     @   s   d dgZ ddlZddlZddlZddlm  mZ ddl	m
Z
 ddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ dd Zdd ZG dd  d ZddejfddZdS )RegularGridInterpolatorinterpn    N   )_ndim_coords_from_arraysPchipInterpolator)evaluate_linear_2dfind_indicesmake_interp_spline)RectBivariateSpline)make_ndbsplc                 C   s   g }g }t | D ]\}}tj|td}t|dd  |d d kst|dd  |d d k rx|| t|}ntd| t|}|| qt	|t	|fS )Ndtyper   zCThe points in dimension %d must be strictly ascending or descending)
	enumeratenpasarrayfloatallappendflip
ValueErrorZascontiguousarraytuple)pointsdescending_dimensionsgridip r   R/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/interpolate/_rgi.py_check_points   s     

r!   c                 C   s   t | |jkr$tdt | |jf t| D ]R\}}t|jdksPtd| |j| t |ks,tdt ||j| |f q,d S )N7There are %d point arrays, but values has %d dimensionsr   z0The points in dimension %d must be 1-dimensionalz1There are %d points and %d values in dimension %d)lenndimr   r   r   r   shape)r   valuesr   r   r   r   r    _check_dimensionality(   s    r'   c                   @   s   e Zd ZdZddddddddZh dZh dZee Z	dd	ge	 Z
dd
ejfdddddZd.ddZdd Zdd Zdd Zdd Zd/ddddZdd Zdd Zd d! Zd"d# Zd$d% Zed&d' Zed(d) Zd*d+ Zd,d- ZdS )0r   a  
    Interpolator on a regular or rectilinear grid in arbitrary dimensions.

    The data must be defined on a rectilinear grid; that is, a rectangular
    grid with even or uneven spacing. Linear, nearest-neighbor, spline
    interpolations are supported. After setting up the interpolator object,
    the interpolation method may be chosen at each evaluation.

    Parameters
    ----------
    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
        The points defining the regular grid in n dimensions. The points in
        each dimension (i.e. every elements of the points tuple) must be
        strictly ascending or descending.

    values : array_like, shape (m1, ..., mn, ...)
        The data on the regular grid in n dimensions. Complex data is
        accepted.

        .. deprecated:: 1.13.0
            Complex data is deprecated with ``method="pchip"`` and will raise an
            error in SciPy 1.15.0. This is because ``PchipInterpolator`` only
            works with real values. If you are trying to use the real components of
            the passed array, use ``np.real`` on ``values``.

    method : str, optional
        The method of interpolation to perform. Supported are "linear",
        "nearest", "slinear", "cubic", "quintic" and "pchip". This
        parameter will become the default for the object's ``__call__``
        method. Default is "linear".

    bounds_error : bool, optional
        If True, when interpolated values are requested outside of the
        domain of the input data, a ValueError is raised.
        If False, then `fill_value` is used.
        Default is True.

    fill_value : float or None, optional
        The value to use for points outside of the interpolation domain.
        If None, values outside the domain are extrapolated.
        Default is ``np.nan``.

    solver : callable, optional
        Only used for methods "slinear", "cubic" and "quintic".
        Sparse linear algebra solver for construction of the NdBSpline instance.
        Default is the iterative solver `scipy.sparse.linalg.gcrotmk`.

        .. versionadded:: 1.13

    solver_args: dict, optional
        Additional arguments to pass to `solver`, if any.

        .. versionadded:: 1.13

    Methods
    -------
    __call__

    Attributes
    ----------
    grid : tuple of ndarrays
        The points defining the regular grid in n dimensions.
        This tuple defines the full grid via
        ``np.meshgrid(*grid, indexing='ij')``
    values : ndarray
        Data values at the grid.
    method : str
        Interpolation method.
    fill_value : float or ``None``
        Use this value for out-of-bounds arguments to `__call__`.
    bounds_error : bool
        If ``True``, out-of-bounds argument raise a ``ValueError``.

    Notes
    -----
    Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class
    avoids expensive triangulation of the input data by taking advantage of the
    regular grid structure.

    In other words, this class assumes that the data is defined on a
    *rectilinear* grid.

    .. versionadded:: 0.14

    The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are
    tensor-product spline interpolators, where `k` is the spline degree,
    If any dimension has fewer points than `k` + 1, an error will be raised.

    .. versionadded:: 1.9

    If the input data is such that dimensions have incommensurate
    units and differ by many orders of magnitude, the interpolant may have
    numerical artifacts. Consider rescaling the data before interpolating.

    **Choosing a solver for spline methods**

    Spline methods, "slinear", "cubic" and "quintic" involve solving a
    large sparse linear system at instantiation time. Depending on data,
    the default solver may or may not be adequate. When it is not, you may
    need to experiment with an optional `solver` argument, where you may
    choose between the direct solver (`scipy.sparse.linalg.spsolve`) or
    iterative solvers from `scipy.sparse.linalg`. You may need to supply
    additional parameters via the optional `solver_args` parameter (for instance,
    you may supply the starting value or target tolerance). See the
    `scipy.sparse.linalg` documentation for the full list of available options.

    Alternatively, you may instead use the legacy methods, "slinear_legacy",
    "cubic_legacy" and "quintic_legacy". These methods allow faster construction
    but evaluations will be much slower.

    Examples
    --------
    **Evaluate a function on the points of a 3-D grid**

    As a first example, we evaluate a simple example function on the points of
    a 3-D grid:

    >>> from scipy.interpolate import RegularGridInterpolator
    >>> import numpy as np
    >>> def f(x, y, z):
    ...     return 2 * x**3 + 3 * y**2 - z
    >>> x = np.linspace(1, 4, 11)
    >>> y = np.linspace(4, 7, 22)
    >>> z = np.linspace(7, 9, 33)
    >>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True)
    >>> data = f(xg, yg, zg)

    ``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``.
    Next, define an interpolating function from this data:

    >>> interp = RegularGridInterpolator((x, y, z), data)

    Evaluate the interpolating function at the two points
    ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``:

    >>> pts = np.array([[2.1, 6.2, 8.3],
    ...                 [3.3, 5.2, 7.1]])
    >>> interp(pts)
    array([ 125.80469388,  146.30069388])

    which is indeed a close approximation to

    >>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)
    (125.54200000000002, 145.894)

    **Interpolate and extrapolate a 2D dataset**

    As a second example, we interpolate and extrapolate a 2D data set:

    >>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5])
    >>> def ff(x, y):
    ...     return x**2 + y**2

    >>> xg, yg = np.meshgrid(x, y, indexing='ij')
    >>> data = ff(xg, yg)
    >>> interp = RegularGridInterpolator((x, y), data,
    ...                                  bounds_error=False, fill_value=None)

    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(projection='3d')
    >>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(),
    ...            s=60, c='k', label='data')

    Evaluate and plot the interpolator on a finer grid

    >>> xx = np.linspace(-4, 9, 31)
    >>> yy = np.linspace(-4, 9, 31)
    >>> X, Y = np.meshgrid(xx, yy, indexing='ij')

    >>> # interpolator
    >>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3,
    ...                   alpha=0.4, color='m', label='linear interp')

    >>> # ground truth
    >>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3,
    ...                   alpha=0.4, label='ground truth')
    >>> plt.legend()
    >>> plt.show()

    Other examples are given
    :ref:`in the tutorial <tutorial-interpolate_regular_grid_interpolator>`.

    See Also
    --------
    NearestNDInterpolator : Nearest neighbor interpolator on *unstructured*
                            data in N dimensions

    LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data
                           in N dimensions

    interpn : a convenience function which wraps `RegularGridInterpolator`

    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
                                    (suitable for e.g., N-D image resampling)

    References
    ----------
    .. [1] Python package *regulargrid* by Johannes Buchner, see
           https://pypi.python.org/pypi/regulargrid/
    .. [2] Wikipedia, "Trilinear interpolation",
           https://en.wikipedia.org/wiki/Trilinear_interpolation
    .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear
           and multilinear table interpolation in many dimensions." MATH.
           COMPUT. 50.181 (1988): 189-196.
           https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf
           :doi:`10.1090/S0025-5718-1988-0917826-0`

    r         )slinearcubicquinticpchipslinear_legacycubic_legacyquintic_legacy>   r.   r-   r/   r0   >   r,   r+   r*   linearnearestTN)solversolver_argsc          	      C   s  || j vrtd| n|| jv r.| || || _|| _t|\| _| _| 	|| _
| | j| j
 | | j
|| _| jrtj|| jd| _
| jdkrt| j
rd}tj|tdd || jv r|d u ri }| j||fi || _n*|d us|rtd|d|d	| d
d S )NMethod '%s' is not definedaxisr-   a'  `PchipInterpolator` only works with real values. Passing complex-dtyped `values` with `method='pchip'` 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 `RegularGridInterpolator`.   )
stacklevelzmethod =z6 does not accept the 'solver' argument. Got  solver = z and with arguments .)_ALL_METHODSr   _SPLINE_METHODS_validate_grid_dimensionsmethodbounds_errorr!   r   Z_descending_dimensions_check_valuesr&   r'   _check_fill_value
fill_valuer   r   ZiscomplexobjwarningswarnDeprecationWarning_SPLINE_METHODS_ndbspl_construct_spline_spline)	selfr   r&   r>   r?   rB   r3   r4   msgr   r   r    __init__  s6    


z RegularGridInterpolator.__init__c                 K   s4   |d u rt j}t| j| j| j| fd|i|}|S )Nr3   )sslZgcrotmkr   r   r&   _SPLINE_DEGREE_MAP)rI   r>   r3   r4   Zsplr   r   r    rG   2  s    z)RegularGridInterpolator._construct_splinec                 C   s   t || d S N)r'   )rI   r   r&   r   r   r    r'   ;  s    z-RegularGridInterpolator._check_dimensionalityc                 C   s   t |S rN   )r!   )rI   r   r   r   r    r!   >  s    z%RegularGridInterpolator._check_pointsc                 C   sF   t |dst|}t |drBt |drBt|jtjsB|t}|S )Nr$   r   astype)hasattrr   r   Z
issubdtyper   ZinexactrO   r   )rI   r&   r   r   r    r@   A  s    


z%RegularGridInterpolator._check_valuesc                 C   s<   |d ur8t |j}t|dr8t j||jdds8td|S )Nr   Z	same_kind)ZcastingzDfill_value must be either 'None' or of a type compatible with values)r   r   r   rP   Zcan_castr   )rI   r&   rB   Zfill_value_dtyper   r   r    rA   L  s    

z)RegularGridInterpolator._check_fill_valuenuc                C   s  |du r| j n|}| j |k}|| jvr2td| |rL|| jv rL| || _|durv|| jvrvtd| j d|d| |\}}}}}|dkr8| |j\}	}
|dkr*t	| j
dr*| j
jdkr*| j
jjr*| j
jtjtjfv r*| j
jjd	kr*tj|	jd
 | j
jd}t| j
|	|
| j|}n| |	|
}np|dkr`| |j\}	}
| |	|
}nH|| jv r|r| | j| || jv r| ||}n| j||d}| js| jdur| j||< t|rtj ||< |!|dd | j
j|d  S )a  
        Interpolation at coordinates.

        Parameters
        ----------
        xi : ndarray of shape (..., ndim)
            The coordinates to evaluate the interpolator at.

        method : str, optional
            The method of interpolation to perform. Supported are "linear",
            "nearest", "slinear", "cubic", "quintic" and "pchip". Default is
            the method chosen when the interpolator was created.

        nu : sequence of ints, length ndim, optional
            If not None, the orders of the derivatives to evaluate.
            Each entry must be non-negative.
            Only allowed for methods "slinear", "cubic" and "quintic".

            .. versionadded:: 1.13

        Returns
        -------
        values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
            Interpolated values at `xi`. See notes for behaviour when
            ``xi.ndim == 1``.

        Notes
        -----
        In the case that ``xi.ndim == 1`` a new axis is inserted into
        the 0 position of the returned array, values_x, so its shape is
        instead ``(1,) + values.shape[ndim:]``.

        Examples
        --------
        Here we define a nearest-neighbor interpolator of a simple function

        >>> import numpy as np
        >>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7])
        >>> def f(x, y):
        ...     return x**2 + y**2
        >>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
        >>> from scipy.interpolate import RegularGridInterpolator
        >>> interp = RegularGridInterpolator((x, y), data, method='nearest')

        By construction, the interpolator uses the nearest-neighbor
        interpolation

        >>> interp([[1.5, 1.3], [0.3, 4.5]])
        array([2., 9.])

        We can however evaluate the linear interpolant by overriding the
        `method` parameter

        >>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear')
        array([ 4.7, 24.3])
        Nr5   z)Can only compute derivatives for methods z, got method =r:   r1   r8   r   =r   r   r2   rQ   r   )"r>   r;   r   rF   rG   rH   _prepare_xi_find_indicesTrP   r&   r$   flagsZ	writeabler   r   Zfloat64Z
complex128	byteorderemptyr%   r   r   _evaluate_linear_evaluate_nearestr<   r=   _SPLINE_METHODS_recursive_evaluate_spliner?   rB   anynanreshape)rI   xir>   rR   Zis_method_changedxi_shaper$   nansout_of_boundsindicesnorm_distancesoutresultr   r   r    __call__V  s`    9






z RegularGridInterpolator.__call__c              	   C   s   t | j}t||d}|jd t | jkrDtd|jd  d| |j}|d|d }tj|td}tj	t
|dd}| jrt|jD ]H\}}tt| j| d |kt|| j| d kstd| qd }n| |j}|||||fS )	Nr$   r   z.The requested sample points xi have dimension z0 but this RegularGridInterpolator has dimension r   r6   r   8One of the requested xi is out of bounds in dimension %d)r#   r   r   r%   r   r`   r   r   r   r^   isnanr?   r   rV   logical_andr   _find_out_of_bounds)rI   ra   r$   rb   rc   r   r   rd   r   r   r    rT     s.    
z#RegularGridInterpolator._prepare_xic                 C   s   t d fd| jjt|   }dd |D }dd |D }t||}t||}tjt|| }tdg}	|D ]N}
t|
 \}}tdg}|D ]}|| }qt	| j| ||  }|	| }	qn|	S )NrN   c                 S   s   g | ]}d | qS r   r   ).0yir   r   r    
<listcomp>      z<RegularGridInterpolator._evaluate_linear.<locals>.<listcomp>c                 S   s   g | ]}|d  qS ro   r   )rp   r   r   r   r    rr     rs   g        g      ?)
slicer&   r$   r#   zip	itertoolsproductr   arrayr   )rI   re   rf   ZvsliceZshift_norm_distancesZshift_indicesZzipped1Zzipped2Z	hypercubevaluehZedge_indicesweightsweightwtermr   r   r    rZ     s    



z(RegularGridInterpolator._evaluate_linearc                 C   s"   dd t ||D }| jt| S )Nc                 S   s&   g | ]\}}t |d k||d qS )g      ?r   )r   where)rp   r   rq   r   r   r    rr     s   z=RegularGridInterpolator._evaluate_nearest.<locals>.<listcomp>)ru   r&   r   )rI   re   rf   Zidx_resr   r   r    r[     s    z)RegularGridInterpolator._evaluate_nearestc                 C   s\   | j | }t|D ]D\}}tt|}||krtd| d| d| d|d  d	qd S )Nz
There are z points in dimension z, but method z requires at least  r   z points per dimension.)rM   r   r#   r   Z
atleast_1dr   )rI   r   r>   kr   pointr$   r   r   r    r=     s    
z1RegularGridInterpolator._validate_grid_dimensionsc                 C   s0  |j dkr|d|jf}|j\}}tt| jj }|d | d d d ||d   }| j|}|dkrr| j}n| j	}| j
| }	|d }
|| j|
 ||d d |
f |	}|g| jj|d  R }tj|| jjd}t|D ]N}||df }t|
d ddD ] }|| j| ||||f |	}q|||df< q|S )Nr   r   r-   r   .)r$   r`   sizer%   r   ranger&   Z	transpose	_do_pchip_do_spline_fitrM   r   r   rY   r   )rI   ra   r>   mnZaxesZaxxr&   Z
_eval_funcr   Zlast_dimZfirst_valuesr%   rh   jZfolded_valuesr   r   r   r    r]   
  s8    

"



z(RegularGridInterpolator._evaluate_splinec                 C   s   t | ||dd}||}|S )Nr   )r   r7   r
   xyptr   Zlocal_interpr&   r   r   r    r   A  s    z&RegularGridInterpolator._do_spline_fitc                 C   s   t | |dd}||}|S )Nr   r6   r   r   r   r   r    r   G  s    z!RegularGridInterpolator._do_pchipc                 C   s   t | j|S rN   )r	   r   )rI   ra   r   r   r    rU   M  s    z%RegularGridInterpolator._find_indicesc                 C   sN   t j|jd td}t|| jD ](\}}|||d k 7 }|||d k7 }q |S )Nr   r   r   r   )r   Zzerosr%   boolru   r   )rI   ra   rd   r   r   r   r   r    rn   P  s
    z+RegularGridInterpolator._find_out_of_bounds)N)N)__name__
__module____qualname____doc__rM   r\   rF   listkeysr<   r;   r   r_   rK   rG   r'   r!   r@   rA   ri   rT   rZ   r[   r=   r]   staticmethodr   r   rU   rn   r   r   r   r    r   5   s>    U 
	
l	7

r1   Tc              	   C   s  |dvrt d| dt|ds,t|}|j}|dkrJ|dkrJt d|sf|du rf|dkrft d	t| |krt d
t| |f t| |kr|dkrt dt| \}}t|| t|t|d}|j	d t|krt d|j	d t|f |rNt
|jD ]H\}	}
tt||	 d |
kt|
||	 d kst d|	 q|tjv rtt| ||||d}||S |dkr~|j	}|d|j	d }tj|d d |dddf k|dddf |d d k|d d |dddf k|dddf |d d kfdd}t|dddf }t| d | d |dd }|||df ||df ||< ||t|< ||dd S t d|dS )a  
    Multidimensional interpolation on regular or rectilinear grids.

    Strictly speaking, not all regular grids are supported - this function
    works on *rectilinear* grids, that is, a rectangular grid with even or
    uneven spacing.

    Parameters
    ----------
    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
        The points defining the regular grid in n dimensions. The points in
        each dimension (i.e. every elements of the points tuple) must be
        strictly ascending or descending.

    values : array_like, shape (m1, ..., mn, ...)
        The data on the regular grid in n dimensions. Complex data is
        accepted.

        .. deprecated:: 1.13.0
            Complex data is deprecated with ``method="pchip"`` and will raise an
            error in SciPy 1.15.0. This is because ``PchipInterpolator`` only
            works with real values. If you are trying to use the real components of
            the passed array, use ``np.real`` on ``values``.

    xi : ndarray of shape (..., ndim)
        The coordinates to sample the gridded data at

    method : str, optional
        The method of interpolation to perform. Supported are "linear",
        "nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d".
        "splinef2d" is only supported for 2-dimensional data.

    bounds_error : bool, optional
        If True, when interpolated values are requested outside of the
        domain of the input data, a ValueError is raised.
        If False, then `fill_value` is used.

    fill_value : number, optional
        If provided, the value to use for points outside of the
        interpolation domain. If None, values outside
        the domain are extrapolated.  Extrapolation is not supported by method
        "splinef2d".

    Returns
    -------
    values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
        Interpolated values at `xi`. See notes for behaviour when
        ``xi.ndim == 1``.

    See Also
    --------
    NearestNDInterpolator : Nearest neighbor interpolation on unstructured
                            data in N dimensions
    LinearNDInterpolator : Piecewise linear interpolant on unstructured data
                           in N dimensions
    RegularGridInterpolator : interpolation on a regular or rectilinear grid
                              in arbitrary dimensions (`interpn` wraps this
                              class).
    RectBivariateSpline : Bivariate spline approximation over a rectangular mesh
    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
                                    (suitable for e.g., N-D image resampling)

    Notes
    -----

    .. versionadded:: 0.14

    In the case that ``xi.ndim == 1`` a new axis is inserted into
    the 0 position of the returned array, values_x, so its shape is
    instead ``(1,) + values.shape[ndim:]``.

    If the input data is such that input dimensions have incommensurate
    units and differ by many orders of magnitude, the interpolant may have
    numerical artifacts. Consider rescaling the data before interpolation.

    Examples
    --------
    Evaluate a simple example function on the points of a regular 3-D grid:

    >>> import numpy as np
    >>> from scipy.interpolate import interpn
    >>> def value_func_3d(x, y, z):
    ...     return 2 * x + 3 * y - z
    >>> x = np.linspace(0, 4, 5)
    >>> y = np.linspace(0, 5, 6)
    >>> z = np.linspace(0, 6, 7)
    >>> points = (x, y, z)
    >>> values = value_func_3d(*np.meshgrid(*points, indexing='ij'))

    Evaluate the interpolating function at a point

    >>> point = np.array([2.21, 3.12, 1.15])
    >>> print(interpn(points, values, point))
    [12.63]

    )
r1   r2   r+   r,   r-   	splinef2dr*   r.   r/   r0   zinterpn only understands the methods 'linear', 'nearest', 'slinear', 'cubic', 'quintic', 'pchip', and 'splinef2d'. You provided r:   r$   r8   r   zBThe method splinef2d can only be used for 2-dimensional input dataNz4The method splinef2d does not support extrapolation.r"   zSThe method splinef2d can only be used for scalar data with one point per coordinaterj   r   zcThe requested sample points xi have dimension %d, but this RegularGridInterpolator has dimension %dr   rk   )r>   r?   rB   r   r6   zunknown method = )r   rP   r   r   r$   r#   r!   r'   r   r%   r   rV   rm   r   r   r;   r`   Z
empty_liker   ZevZlogical_not)r   r&   ra   r>   r?   rB   r$   r   r   r   r   Zinterprb   Z	idx_validrh   r   r   r    r   Z  sh    c






84 )__all__rv   rC   numpyr   Zscipy.sparse.linalgsparseZlinalgrL   Zinterpndr   Z_cubicr   Z_rgi_cythonr   r	   Z	_bsplinesr   Z	_fitpack2r   Z
_ndbspliner   r!   r'   r   r_   r   r   r   r   r    <module>   s(       )