
    `i]_                     |    d dgZ ddlZddlZddlmZ ddlmZ ddZd Z	d Z
 G d	 d           Zd
dej        fdZdS )RegularGridInterpolatorinterpn    Nmake_interp_splinePchipInterpolatorc                    t          | t                    rt          |           dk    r| d         } t          | t                    rt          j        |  }t          |          }t          d|          D ]-}||         j        |d         j        k    rt          d          .t          j        |d         j        t          |           fz   t                    } t          |          D ]\  }}|| d|f<   nNt          j        |           } | j        dk    r/||                     dd          } n|                     d|          } | S )zM
    Convert a tuple of coordinate arrays to a (..., ndim)-shaped array.
       r   z,coordinate arrays do not have the same shapedtype.N)
isinstancetuplelencpbroadcast_arraysrangeshape
ValueErroremptyfloat	enumerate
asanyarrayndimreshape)pointsr   pnjitems         p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/interpolate/_rgi.py_ndim_coords_from_arraysr"   	   sL    &%   S[[A%5%5&%   2(FFq! 	D 	DAtzQqTZ'' BD D D ( !A$*F~5UCCC || 	" 	"GAt!F36NN	" v&&;!|A..D11M    c                    g }g }t          |           D ]\  }}t          j        |t                    }t          j        |dd          |d d         k              sxt          j        |dd          |d d         k               r>|                    |           t          j        |          }t          j        |          }nt          d|z            |                    |           t          |          t          |          fS )Nr   r
   r   zCThe points in dimension %d must be strictly ascending or descending)
r   r   asarrayr   allappendflipascontiguousarrayr   r   )r   descending_dimensionsgridir   s        r!   _check_pointsr-   $   s	   D&!!  1 Jq&&&vaeafn%% 		3vaeafn%% 3%,,Q///GAJJ(++ .0123 3 3 	A;;34444r#   c                    t          |           |j        k    r&t          dt          |           |j        fz            t          |           D ]\  }}t	          j        |          j        dk    st          d|z            |j        |         t          |          k    s-t          dt          |          |j        |         |fz            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)r   r   r   r   r   r%   r   )r   valuesr,   r   s       r!   _check_dimensionalityr1   9   s    
6{{V[   &),Vfk(BC D D 	D&!! L L1z!}}!Q&& -/01 2 2 2|A#a&&(( ,/21vvv|A.JK L L L )	L Lr#   c                       e Zd ZdZdddddZ ee                                          Zddgez   Zdde	j
        fd	Zd
 Zd Zd Zd Zd ZddZd Zd Zd Zd Zed             Zed             Zd Z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 and nearest-neighbor
    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 : ndarray, 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", "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 ``cp.nan``.

    Notes
    -----
    Contrary to scipy's `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.

    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.

    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 cupyx.scipy.interpolate import RegularGridInterpolator
    >>> import cupy as cp
    >>> def f(x, y, z):
    ...     return 2 * x**3 + 3 * y**2 - z
    >>> x = cp.linspace(1, 4, 11)
    >>> y = cp.linspace(4, 7, 22)
    >>> z = cp.linspace(7, 9, 33)
    >>> xg, yg ,zg = cp.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 = cp.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 = cp.array([-2, 0, 4]), cp.array([-2, 0, 2, 5])
    >>> def ff(x, y):
    ...     return x**2 + y**2

    >>> xg, yg = cp.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().get(), yg.ravel().get(), data.ravel().get(),
    ...            s=60, c='k', label='data')

    Evaluate and plot the interpolator on a finer grid

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

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

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

    See Also
    --------
    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
    r
         )slinearcubicquinticpchiplinearnearestTc                    || j         vrt          d|z            || j        v r|                     ||           || _        || _        t          |          \  | _        | _        | 	                    |          | _
        |                     | j        | j
                   |                     | j
        |          | _        | j        r"t          j        || j                  | _
        d S d S )NMethod '%s' is not definedaxis)_ALL_METHODSr   _SPLINE_METHODS_validate_grid_dimensionsmethodbounds_errorr-   r+   _descending_dimensions_check_valuesr0   r1   _check_fill_value
fill_valuer   r(   )selfr   r0   rB   rC   rG   s         r!   __init__z RegularGridInterpolator.__init__   s    ***9FBCCCt+++**66:::(1>v1F1F.	4.((00""49dk:::00jII& 	L'&t/JKKKDKKK	L 	Lr#   c                 &    t          ||           d S N)r1   )rH   r+   r0   s      r!   r1   z-RegularGridInterpolator._check_dimensionality   s    dF+++++r#   c                     | j         |         }t          |          D ]K\  }}t          t          j        |                    }||k    rt          d| d| d| d|dz    d	          Ld S )Nz
There are z points in dimension z, but method z requires at least  r
   z points per dimension.)_SPLINE_DEGREE_MAPr   r   r   
atleast_1dr   )rH   r   rB   kr,   pointr   s          r!   rA   z1RegularGridInterpolator._validate_grid_dimensions   s    #F+!&)) 	B 	BHAur}U++,,Dqyy  "Ad "A "A "A "A06"A "A%&qS"A "A "A B B B 	B 	Br#   c                      t          |          S rK   )r-   )rH   r   s     r!   r-   z%RegularGridInterpolator._check_points   s    V$$$r#   c                     t          j        |j        t           j                  s|                    t
                    }|S rK   )r   
issubdtyper   inexactastyper   )rH   r0   s     r!   rE   z%RegularGridInterpolator._check_values   s0    }V\2:66 	*]]5))Fr#   c                     |Tt          j        |          j        }t          |d          r+t          j        ||j        d          st          d          |S )Nr   	same_kind)castingzDfill_value must be either 'None' or of a type compatible with values)r   r%   r   hasattrcan_castr   )rH   r0   rG   fill_value_dtypes       r!   rF   z)RegularGridInterpolator._check_fill_value   su    !!z*55;(( EK 0&,(35 5 5E ! "D E E Er#   Nc                    | j         |k    }|| j         n|}|| j        vrt          d|z            |                     |          \  }}}}}|dk    r4|                     |j                  \  }}	|                     ||	          }
nv|dk    r4|                     |j                  \  }}	|                     ||	          }
n<|| j        v r3|r| 	                    | j
        |           |                     ||          }
| j        s| j        
| j        |
|<   |j        |
j        k     r|d         }t          j        |t          j        |
          }
|
                    |dd         | j        j        |d         z             S )a  
        Interpolation at coordinates.

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

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

        Returns
        -------
        values_x : cupy.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 cupy as cp
        >>> x, y = cp.array([0, 1, 2]), cp.array([1, 3, 7])
        >>> def f(x, y):
        ...     return x**2 + y**2
        >>> data = f(*cp.meshgrid(x, y, indexing='ij', sparse=True))
        >>> from cupyx.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<   r9   r:   ).Nr   )rB   r?   r   _prepare_xi_find_indicesT_evaluate_linear_evaluate_nearestr@   rA   r+   _evaluate_splinerC   rG   r   r   wherenanr   r0   r   )rH   xirB   is_method_changedxi_shaper   nansout_of_boundsindicesnorm_distancesresults              r!   __call__z RegularGridInterpolator.__call__  s   d !K61 &F***9FBCCC262B2B22F2F/HdD-X&*&8&8&>&>#G^**7NCCFFy  &*&8&8&>&>#G^++G^DDFFt+++  B..ty&AAA**2v66F  	4T_%@$(OF=!9v{""	?D$//~~hssmdk.?.FFGGGr#   c           	      n   t          | j                  }t          ||          }|j        d         t          | j                  k    r t	          d|j        d          d|           |j        }|                    d|d                   }t          j        |t                    }t          j	        |          j
        }|d                                         }|dd          D ]}t          j        |||           | j        rt          |j
                  D ]z\  }}t          j        t          j        | j        |         d         |k              t          j        || j        |         d         k                        st	          d|z            {d }	n|                     |j
                  }	|||||	fS )	Nr   r   z.The requested sample points xi have dimension z0 but this RegularGridInterpolator has dimension r   r   r
   8One of the requested xi is out of bounds in dimension %d)r   r+   r"   r   r   r   r   r%   r   isnanr_   copy
logical_orrC   r   logical_andr&   _find_out_of_bounds)
rH   re   r   rg   is_nansrh   is_nanr,   r   ri   s
             r!   r]   z#RegularGridInterpolator._prepare_xiT  s   49~~%bt4448B<3ty>>)) M "M MFJM M N N N 8ZZHRL))Z%((( (2,,.qz  abbk 	. 	.FM$---- 	;!"$ = =1~bfTYq\!_-A&B&B&(fQ$)A,r2B-B&C&CE E =$ &8:;&< = = == !MM 44RT::M8T466r#   c                    t          d           fd| j        j        t          |          z
  z  z   }d |D             }d |D             }t	          ||          }t	          ||          }t          j        t	          ||           }t          j        dg          }	|D ]B}
t	          |
 \  }}t          j	        | j        |                   }|D ]}|||         z  }|	|z   }	C|	S )NrK   c                     g | ]}d |z
  S r
    ).0yis     r!   
<listcomp>z<RegularGridInterpolator._evaluate_linear.<locals>.<listcomp>w  s    @@@2B@@@r#   c                     g | ]}|d z   S rz   r{   )r|   r,   s     r!   r~   z<RegularGridInterpolator._evaluate_linear.<locals>.<listcomp>x  s    0001Q000r#   g        )
slicer0   r   r   zip	itertoolsproductr   arrayr%   )rH   rj   rk   vsliceshift_norm_distancesshift_indiceszipped1zipped2	hypercubevaluehedge_indicesweightstermws                  r!   r`   z(RegularGridInterpolator._evaluate_linearr  s    ++'4;+;c'll+J"KK  A@@@@00000 g344m^44
 %s7G'<'<=	" 	! 	!A$'G!L':dk,788D " "&	!DLEEr#   c                 j    d t          ||          D             }| j        t          |                   S )Nc                 N    g | ]"\  }}t          j        |d k    ||dz             #S )g      ?r
   )r   rc   )r|   r,   r}   s      r!   r~   z=RegularGridInterpolator._evaluate_nearest.<locals>.<listcomp>  sB     > > >q" 8B"HaQ// > > >r#   )r   r0   r   )rH   rj   rk   idx_ress       r!   ra   z)RegularGridInterpolator._evaluate_nearest  s=    > > #G^ < <> > >{5>>**r#   c           	         |j         dk    r|                    d|j        f          }|j        \  }}t	          t          | j        j                             }|d |         d d d         ||d          z   }| j                            |          }|dk    r| j        }n| j	        }| j
        |         }	|dz
  }
 || j        |
         ||d d |
f         |	          }|g| j        j        |d          R }t          j        || j        j                  }t          |          D ]K}||df         }t          |
dz
  dd          D ]#} || j        |         ||||f         |	          }$|||df<   L|S )Nr
   r   r8   r   .)r   r   sizer   r   r   r0   	transpose	_do_pchip_do_spline_fitrM   r+   r   r   r   )rH   re   rB   mr   axesaxxr0   
_eval_funcrO   last_dimfirst_valuesr   rl   r   folded_valuesr,   s                    r!   rb   z(RegularGridInterpolator._evaluate_spline  s    7a<<QL))Bx1 U4;+,,--2A2htttntABBx'&&s++WJJ,J#F+ q5!z$)H"5"("$QQQ[/"#% % +T[&qrr*++%t{'8999q 	+ 	+A )C0M8A:r2.. . . !+
49Q<+8+-ad8+,!. !. +F1c6NNr#   c                 B    t          | ||d          } ||          }|S )Nr   )rO   r>   r   xyptrO   local_interpr0   s         r!   r   z&RegularGridInterpolator._do_spline_fit  s,    )!Q!!<<<b!!r#   c                 @    t          | |d          } ||          }|S )Nr   r=   r   r   s         r!   r   z!RegularGridInterpolator._do_pchip  s*    (AA666b!!r#   c                 ~   g }g }t          || j                  D ]\  }}t          j        ||          dz
  }t          j        |d|j        dz
  |           |                    |           ||dz            ||         z
  }t          j        |dk    |||         z
  |z  d          }|                    |           ||fS )Nr
   r      )r   r+   r   searchsortedclipr   r'   rc   )	rH   re   rj   rk   r   r+   r,   denom	norm_dists	            r!   r^   z%RegularGridInterpolator._find_indices  s    2ty)) 		- 		-GAta((1,AGAq$)a-+++NN1 QK$q')E!a$q'kU-BAFFI!!),,,,&&r#   c                     t          j        |j        d         t                    }t	          || j                  D ]#\  }}|||d         k     z  }|||d         k    z  }$|S )Nr
   r   r   r   )r   zerosr   boolr   r+   )rH   re   ri   r   r+   s        r!   ru   z+RegularGridInterpolator._find_out_of_bounds  sg    "(1+d;;;2ty)) 	* 	*GAtQa[(MQb\)MMr#   rK   )__name__
__module____qualname____doc__rM   listkeysr@   r?   r   rd   rI   r1   rA   r-   rE   rF   rm   r]   r`   ra   rb   staticmethodr   r   r^   ru   r{   r#   r!   r   r   F   s~       J J\ &'q1MMd-224455Oi(?:L.6TFL L L L , , ,B B B% % %    JH JH JH JHX7 7 7<  <+ + +
5 5 5n   \
   \
' ' '&    r#   r9   Tc           	      
   |dvrt          d          |j        }t          |           |k    r!t          dt          |           |fz            t          |           \  }}t	          ||           t          |t          |                    }|j        d         t          |          k    r,t          d|j        d         t          |          fz            |rt          |j                  D ]p\  }	}
t          j
        t          j        ||	         d         |
k              t          j        |
||	         d         k                        st          d|	z            q|dv rt          | ||||	          } ||          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 cupy.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 : cupy.ndarray of shape (m1, ..., mn, ...)
        The data on the regular grid in n dimensions. Complex data can be
        acceptable.

    xi : cupy.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" and "pchip".

    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.

    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:]``.

    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 cupy as cp
    >>> from cupyx.scipy.interpolate import interpn
    >>> def value_func_3d(x, y, z):
    ...     return 2 * x + 3 * y - z
    >>> x = cp.linspace(0, 4, 5)
    >>> y = cp.linspace(0, 5, 6)
    >>> z = cp.linspace(0, 6, 7)
    >>> points = (x, y, z)
    >>> values = value_func_3d(*cp.meshgrid(*points, indexing='ij'))

    Evaluate the interpolating function at a point

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

    See Also
    --------
    RegularGridInterpolator : interpolation on a regular or rectilinear grid
                              in arbitrary dimensions (`interpn` wraps this
                              class).

    cupyx.scipy.ndimage.map_coordinates : interpolation on grids with equal
                                          spacing (suitable for e.g., N-D image
                                          resampling)
    )r9   r:   r5   r6   r7   r8   z{interpn only understands the methods 'linear', 'nearest', 'slinear', 'cubic', 'quintic' and 'pchip'. You provided {method}.r/   ro   r   zcThe requested sample points xi have dimension %d, but this RegularGridInterpolator has dimension %dr   rp   )rB   rC   rG   N)r   r   r   r-   r1   r"   r   r   r_   r   rt   r&   r   )r   r0   re   rB   rC   rG   r   r+   r*   r,   r   interps               r!   r   r     s   j  * * *%& & 	&
 ;D 6{{T &),Vd(;< = = 	= #0"7"7D
$''' 
""3t99	5	5	5B	x|s4yy   (+-8B<T*CD E E 	E  8bdOO 	8 	8DAq>"&aq"9"9"$&d1gbk)9":":< < 8  "356"7 8 8 88 NNN(6B4>@ @ @ vbzz	 ONr#   rK   )__all__r   cupyr   !cupyx.scipy.interpolate._bspline2r   cupyx.scipy.interpolate._cubicr   r"   r-   r1   r   rd   r   r{   r#   r!   <module>r      s   $i
0         @ @ @ @ @ @ < < < < < <   65 5 5*
L 
L 
Ll l l l l l l l^ (0dvy y y y y yr#   