a
    ¬ˆc'_  ã                   @   st   d dgZ ddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
m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©Úmake_interp_spline)ÚRectBivariateSplinec           
      C   s¸   t dd„ | D ƒƒ}t dd„ t| |ƒD ƒƒ}t dd„ |D ƒƒ}t dd„ tj|Ž D ƒ¡ ¡ }t dd„ tj|Ž D ƒ¡ ¡ }t t |¡¡}t||ƒD ]\}}	|t |	ƒ |t |ƒ< q’||fS )Nc                 s   s   | ]}t  |¡V  qd S ©N)ÚnpZargsort)Ú.0Úpoint© r   úY/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/scipy/interpolate/_rgi.pyÚ	<genexpr>   ó    z4_make_points_and_values_ascending.<locals>.<genexpr>c                 s   s    | ]\}}t  |¡| V  qd S r
   ©r   Úasarray)r   r   Z
sort_indexr   r   r   r      s   c                 s   s   | ]}g t t|ƒƒ¢V  qd S r
   )ÚrangeÚlen)r   Úxr   r   r   r      r   c                 S   s   g | ]}|  ¡ ‘qS r   ©Úflatten©r   Úir   r   r   Ú
<listcomp>   r   z5_make_points_and_values_ascending.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   r   r   r   r   r   r      r   )ÚtupleÚzipr   ÚarrayZmeshgridZ	transposeZ
zeros_liker   )
ÚpointsÚvaluesZsorted_indexesZ
points_ascZordered_indexesZordered_indexes_arrayZsorted_indexes_arrayZ
values_ascÚoÚsr   r   r   Ú!_make_points_and_values_ascending   s    þÿÿr#   c                   @   s„   e Zd ZdZddddœZee ¡ ƒZddge Zdde	j
fd	d
„Zddd„Zdd„ Zdd„ Zdd„ Zdd„ Zedd„ ƒZdd„ ZdS )r   a  
    Interpolation 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 can be
        acceptable.

    method : str, optional
        The method of interpolation to perform. Supported are "linear",
        "nearest", "slinear", "cubic", and "quintic". 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``.

    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

    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
    >>> 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 interpolation on *unstructured*
                            data in N dimensions

    LinearNDInterpolator : Piecewise linear interpolant 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   é   é   )ZslinearZcubicZquinticÚlinearÚnearestTc           
      C   s   || j vrtd| ƒ‚n|| jv r.|  ||¡ || _|| _t|dƒsNt |¡}t	|ƒ|j
krrtdt	|ƒ|j
f ƒ‚t|dƒr t|dƒr t |jtj¡s | t¡}|| _|d urÞt |¡j}t|dƒrÞtj||jdd�sÞtdƒ‚t|ƒD ]š\}}t |¡}	t |	d	k¡�s4t |	d	k ¡�r(t||ƒ\}}ntd
| ƒ‚t |¡j
dk�sRtd| ƒ‚|j| t	|ƒksætdt	|ƒ|j| |f ƒ‚qætdd„ |D ƒƒ| _|| _d S )NúMethod '%s' is not definedÚndimú7There are %d point arrays, but values has %d dimensionsÚdtypeÚastypeZ	same_kind)ZcastingzDfill_value must be either 'None' or of a type compatible with valuesç        úCThe points in dimension %d must be strictly ascending or descendingr   ú0The points in dimension %d must be 1-dimensionalú1There are %d points and %d values in dimension %dc                 S   s   g | ]}t  |¡‘qS r   r   ©r   Úpr   r   r   r     r   z4RegularGridInterpolator.__init__.<locals>.<listcomp>)Ú_ALL_METHODSÚ
ValueErrorÚ_SPLINE_METHODSÚ_validate_grid_dimensionsÚmethodÚbounds_errorÚhasattrr   r   r   r)   Z
issubdtyper+   Zinexactr,   ÚfloatÚ
fill_valueZcan_castÚ	enumerateÚdiffÚallr#   Úshaper   Úgridr    )
Úselfr   r    r7   r8   r;   Zfill_value_dtyper   r2   Údiff_pr   r   r   Ú__init__Ô   s\    



ÿ


ÿÿ
ÿ
ÿÿÿÿz RegularGridInterpolator.__init__Nc              	   C   sÊ  | j |k}|du r| j n|}|| jvr2td| ƒ‚t| jƒ}t||d�}|jd t| jƒkrrtd|jd |f ƒ‚|j}| d|d ¡}tj	t 
|¡dd�}| jröt|jƒD ]H\}}t t | j| d |k¡t || j| d k¡¡s¬td	| ƒ‚q¬|  |j¡\}	}
}|d
k�r"|  |	|
|¡}nR|dk�r<|  |	|
|¡}n8|| jv �rt|�r\|  | j|¡ |  | jj|| j| ¡}| j�s’| jdu�r’| j||< t 	|¡�r¨tj||< | |dd… | jj|d…  ¡S )aV  
        Interpolation at coordinates.

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

        method : str
            The method of interpolation to perform. Supported are "linear" and
            "nearest".

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

        >>> 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])
        Nr(   ©r)   éÿÿÿÿúcThe requested sample points xi have dimension %d, but this RegularGridInterpolator has dimension %dr   ©Úaxisr   ú8One of the requested xi is out of bounds in dimension %dr&   r'   )r7   r3   r4   r   r@   r   r?   Úreshaper   ÚanyÚisnanr8   r<   ÚTÚlogical_andr>   Ú_find_indicesÚ_evaluate_linearÚ_evaluate_nearestr5   r6   Ú_evaluate_spliner    Ú_SPLINE_DEGREE_MAPr;   Únan)rA   Úxir7   Zis_method_changedr)   Úxi_shapeZnansr   r2   ÚindicesÚnorm_distancesÚout_of_boundsÚresultr   r   r   Ú__call__  sV    $


þÿÿ
þ
þÿ

z RegularGridInterpolator.__call__c                 C   s–   t d ƒfd| jjt|ƒ   }tjdd„ |D ƒŽ }d}|D ]V}d}t|||ƒD ]$\}	}
}|t |	|
kd| |¡9 }qN|t 	| j| ¡||  7 }q:|S )Nr
   c                 S   s   g | ]}||d  g‘qS )r   r   r   r   r   r   r   `  r   z<RegularGridInterpolator._evaluate_linear.<locals>.<listcomp>r-   g      ð?r   )
Úslicer    r)   r   Ú	itertoolsÚproductr   r   Úwherer   )rA   rW   rX   rY   ZvsliceÚedgesr    Zedge_indicesZweightÚeir   Úyir   r   r   rP   Z  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   r_   )r   r   rb   r   r   r   r   j  s   ÿz=RegularGridInterpolator._evaluate_nearest.<locals>.<listcomp>)r   r    r   )rA   rW   rX   rY   Zidx_resr   r   r   rQ   i  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.)rS   r<   r   r   Z
atleast_1dr4   )rA   r   r7   Úkr   r   r)   r   r   r   r6   n  s    
ÿþz1RegularGridInterpolator._validate_grid_dimensionsc              	   C   s¶   |j dkr| d|jf¡}|j\}}|d }|  | j| ||d d …|f |¡}tj|| jj	d�}t
|ƒD ]H}	||	 }
t
|d ddƒD ]"}|  | j| |
||	|f |¡}
q„|
||	< qh|S )Nr   ©r+   rE   )r)   rJ   Úsizer?   Ú_do_spline_fitr@   r   Úemptyr    r+   r   )rA   r    rU   Zspline_degreeÚmÚnZlast_dimZfirst_valuesrZ   ÚjZfolded_valuesr   r   r   r   rR   w  s(    

ý
ý
z(RegularGridInterpolator._evaluate_splinec                 C   s   t | ||dd�}||ƒ}|S )Nr   )rc   rH   r   )r   ÚyÚptrc   Zlocal_interpr    r   r   r   rf   œ  s    z&RegularGridInterpolator._do_spline_fitc           
   	   C   s
  g }g }t j|jd td�}t|| jƒD ]Ö\}}t  ||¡d }d||dk < |jd |||jd k< | |¡ ||d  ||  }t j	ddd��. t  
|dk|||  | d¡}	W d   ƒ n1 sÄ0    Y  | |	¡ | js(|||d k 7 }|||d k7 }q(|||fS )Nr   rd   r   é   Úignore)ÚdivideÚinvalidrE   )r   Úzerosr?   Úboolr   r@   Zsearchsortedre   ÚappendZerrstater_   r8   )
rA   rU   rW   rX   rY   r   r@   r   ZdenomZ	norm_distr   r   r   rO   ¢  s     
<
z%RegularGridInterpolator._find_indices)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rS   ÚlistÚkeysr5   r3   r   rT   rC   r[   rP   rQ   r6   rR   Ústaticmethodrf   rO   r   r   r   r   r   "   s     .ÿ
2
T	%
r&   Tc              	   C   s>  |dvrt d| ƒ‚t|dƒs(t |¡}|j}|dkrF|dkrFt dƒ‚|sb|du rb|dkrbt dƒ‚t| ƒ|kr‚t d	t| ƒ|f ƒ‚t| ƒ|krž|dkržt d
ƒ‚t| ƒD ]–\}}t |¡}	t |	dk¡sðt |	dk ¡rät	| |ƒ\} }nt d| ƒ‚t |¡jdk�st d| ƒ‚|j
| t|ƒks¦t dt|ƒ|j
| |f ƒ‚q¦tdd„ | D ƒƒ}
t|t|
ƒd�}|j
d t|
ƒk�rŽt d|j
d t|
ƒf ƒ‚|�rèt|jƒD ]H\}}t t |
| d |k¡t ||
| d k¡¡�sžt d| ƒ‚�qž|dk�rt| |d||d�}||ƒS |dk�r0t| |d||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 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 can be
        acceptable.

    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" and
        "nearest", 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 input coordinates.

    Notes
    -----

    .. versionadded:: 0.14

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

    >>> 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]

    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)

    )r&   r'   Ú	splinef2dz[interpn only understands the methods 'linear', 'nearest', and 'splinef2d'. You provided %s.r)   rm   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 coordinater-   r.   r   r/   r0   c                 S   s   g | ]}t  |¡‘qS r   r   r1   r   r   r   r   <  r   zinterpn.<locals>.<listcomp>rD   rE   rF   r   rI   r&   )r7   r8   r;   r'   rG   )r4   r9   r   r   r)   r   r<   r=   r>   r#   r?   r   r   rM   rN   r   rJ   Z
empty_liker	   ZevZlogical_not)r   r    rU   r7   r8   r;   r)   r   r2   rB   r@   ZinterprV   Z	idx_validrZ   r   r   r   r   ½  s”    Wþ


ÿ
ÿ
ÿÿÿþÿÿ

þ
þ
84ÿþ )Ú__all__r]   Únumpyr   Zinterpndr   Z_cubicr   Z	_bsplinesr   Z	_fitpack2r	   r#   r   rT   r   r   r   r   r   Ú<module>   s      ÿ