L i6xddgZddlZddlZddlmcmZddlm Z ddl m Z ddl m Z mZddlmZdd lmZdd lmZd Zd ZGd dZddej0fdZy)RegularGridInterpolatorinterpnN)_ndim_coords_from_arraysPchipInterpolator)evaluate_linear_2d find_indicesmake_interp_spline)RectBivariateSpline) make_ndbsplcg}g}t|D]\}}tj|t}tj|dd|ddkDsTtj|dd|ddkr'|j |tj |}ntd|dtj|}|j |t|t|fS)NdtyperThe points in dimension z) must be strictly ascending or descending) enumeratenpasarrayfloatallappendflip ValueErrorascontiguousarraytuple)pointsdescending_dimensionsgridips \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/interpolate/_rgi.py _check_pointsr$s D&!1 JJq &vvaeafn%vvaeafn%%,,Q/GGAJ .qc2!"   # A!" ;34 44c t||jkDr%tdt|d|jdt|D]{\}}t j |jdk(std|d|j |t|k(rStdt|d|j |d|y) N There are  point arrays, but values has dimensionsrrz must be 1-dimensionalz points and z values in dimension )lenndimrrrrshape)rvaluesr!r"s r#_check_dimensionalityr.(s 6{V[[ V %C{{m; (  &!1zz!}!!Q&7s:PQR R||A#a&(SVHLa0ABC!  r%ceZdZdZddddddddZhdZhdZeejZ dd ge zZ dd e jfd d d d Z ddZdZdZdZdZdd ddZdZdZdZdZdZedZedZdZdZy )ruInterpolator of specified order on a rectilinear grid in N ≥ 1 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. 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. **Rounding rule at half points with `nearest` method** The rounding rule with the `nearest` method at half points is rounding *down*. 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 `. 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)slinearcubicquinticpchipslinear_legacy cubic_legacyquintic_legacy>r5r7r8r6>r3r4r2linearnearestTN)solver solver_argsc ||jvrtd|d||jvr|j||||_d|_||_t|\|_|_ |j||_ |j|j|j|j|j||_|jr&tj ||j|_ |jdk(r,tj"|jr d}t|||j$vr|i}|j&||fi||_y||rtd|d|d|d y) NMethod '' is not definedaxisr5z`PchipInterpolator` only works with real values. If you are trying to use the real components of the passed array, use `np.real` on the array before passing to `RegularGridInterpolator`.zmethod =z6 does not accept the 'solver' argument. Got solver = z and with arguments .) _ALL_METHODSr_SPLINE_METHODS_validate_grid_dimensionsmethod_spline bounds_errorr$r _descending_dimensions _check_valuesr-r._check_fill_value fill_valuerr iscomplexobj_SPLINE_METHODS_ndbspl_construct_spline) selfrr-rFrHrLr;r<msgs r#__init__z RegularGridInterpolator.__init__sm ** *xx/?@A A t++ +  * *66 :  (1>v1F. 4.((0  ""499dkk:00jI  & &''&t/J/JKDK ;;' !boodkk&BLCS/ ! T00 0" 1411&&PKPDL![ vj!"{"6{m1F&1r%c |tj}t|j|j|j |fd|i|}|S)Nr;)sslgcrotmkrr r-_SPLINE_DEGREE_MAP)rPrFr;r<spls r#rOz)RegularGridInterpolator._construct_spline2sK >[[F 4;;(?(?(G!, r%ct||yN)r.)rPr r-s r#r.z-RegularGridInterpolator._check_dimensionality;s dF+r%ct|SrY)r$)rPrs r#r$z%RegularGridInterpolator._check_points>s V$$r%ct|dstj|}t|drOt|drCtj|jtj s|j t}|S)Nr+rastype)hasattrrr issubdtyperinexactr\r)rPr-s r#rJz%RegularGridInterpolator._check_valuesAsVvv&ZZ'F 67 #(A==rzz:u- r%c|Xtj|j}t|dr-tj||jds t d|S)Nr same_kind)castingzDfill_value must be either 'None' or of a type compatible with values)rrrr]can_castr)rPr-rLfill_value_dtypes r#rKz)RegularGridInterpolator._check_fill_valueLsZ  !!zz*5;; (KK 0&,,(35 "DEEr%nuc|j}| |jn|}|j|k7}||jvrtd|d|r||jvr|j |}|*||jvrtd|jd|d|j |\}}}}} |dk(r;|j|j\} } |dk(rt|jd r|jjdk(r|jjjr|jjtj tj"fvr|jjj$d k(r\tj&| j(d |jj } t+|j| | |j,| } n|j/| | } n|d k(r1|j|j\} } |j1| | } nW||j2vrI|r|j5|j,|||j6vr|j9||} n |||} |j:s|j<|j< | <tj>|rtj@ |< jC|dd|jj(|dzS)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]) Nr>r?z)Can only compute derivatives for methods z, got method =rBr9r=rrr:rer)"rGrFrCrrNrO _prepare_xi _find_indicesTr]r-r+flags writeablerrfloat64 complex128 byteorderemptyr,r r _evaluate_linear_evaluate_nearestrDrE_SPLINE_METHODS_recursive_evaluate_splinerHrLanynanreshape)rPxirFrfrGis_method_changedxi_shaper+nans out_of_boundsindicesnorm_distancesoutresults r#__call__z RegularGridInterpolator.__call__Vsr,, &F KK61 ** *xx/?@A A 4+F+F!F,,V4G >fD,G,GG;../fZqB  372B2B22F/HdD- X &*&8&8&> #G^ gdkk7;KK$$)dkk.?.?.I.IKK%%"**bmm)DDKK%%//36hhw}}Q/t{{7H7HI+DKK,3,:,0II,/ 1 ..wG y &*&8&8&> #G^++G^DF t++ + ..tyy&A777..r6: +  T__%@$(OOF= ! 66$<66F4L~~hsmdkk.?.?.FFGGr%c t|j}t||}|jdt|jk7rt d|jdd||j}|j d|d}t j|t}t jt j|d}|jrt|jD]u\}}t jt j|j|d|kt j||j|dkrit d|d}n|j!|j}|||||fS) Nr+r.The requested sample points xi have dimension z0 but this RegularGridInterpolator has dimension rr@r6One of the requested xi is out of bounds in dimension )r*r rr,rryrrrrwisnanrHrrl logical_andr_find_out_of_bounds)rPrzr+r|r}r!r"r~s r#rjz#RegularGridInterpolator._prepare_xis\499~ %bt 4 88B<3tyy> )M " ~.FFJVMN N88 ZZHRL ) ZZ% (vvbhhrl,   !"$$ 1~~bffTYYq\!_-A&B&(ffQ$))A,r2B-B&CE$PQRPST  !M 44RTT:M8T466r%ctdfd|jjt|z zz}|Dcgc]}d|z  }}|Dcgc]}|dz }}t ||}t ||} t j t || } tjdg} | D]\} t | \} }tjdg}|D]}||z} tj|j| ||z}| |z} ^| Scc}wcc}w)NrYrgg?) slicer-r+r*zip itertoolsproductrarrayr)rPrrvsliceyishift_norm_distancesr! shift_indiceszipped1zipped2 hypercubevalueh edge_indicesweightsweightwterms r#rsz(RegularGridInterpolator._evaluate_linears+'4;;+;+;c'l+J"KK2@@2B@@(/01Q0 0g34m^4 %%s7G'<= " !A$'G !L'XXrd^F $! $::dkk,786&>IDDLE  ! 1 A0s D D c t||Dcgc]"\}}tj|dk||dz$}}}|jt |Scc}}w)Ng?r)rrwherer-r)rPrrr!ridx_ress r#rtz)RegularGridInterpolator._evaluate_nearestsW #G^ <>q"88B"HaQ/>>{{5>**>s'Ac |j|}t|D]C\}}ttj|}||ks*t d|d|d|d|dzd y)Nr'z points in dimension z , but method z requires at least rz points per dimension.)rVrr*r atleast_1dr)rPrrFkr!pointr+s r#rEz1RegularGridInterpolator._validate_grid_dimensionss  # #F +!&) BHAur}}U+,Dqy :dV3HL006x8%%&qSE)?"ABB Br%c |jdk(r|jd|jf}|j\}}t t |j j}|d|ddd||dz}|j j|}|dk(r |j}n |j}|j|} |dz } ||j| ||dd| f| } |g|j j|d} tj| |j j} t |D]B}| |df}t | dz ddD]}||j|||||f| }!|| |df<D| S)Nrrr5r.)r+rysizer,rranger- transpose _do_pchip_do_spline_fitrVr rrrr)rPrzrFmnaxesaxxr- _eval_funcrlast_dim first_valuesr,rj folded_valuesr!s r#rvz(RegularGridInterpolator._evaluate_spline s 77a<QL)Bxx1U4;;++,-2AhttntABx'&&s+ W J,,J  # #F +q5!$))H"5"("$Q[/"#% +T[[&&qr*+%t{{'8'89q +A)C0M8A:r2. .!+499Q<+8+-ad8+,!.  .+F1c6N + r%c4t|||d}||}|S)Nr)rrAr xyptr local_interpr-s r#rz&RegularGridInterpolator._do_spline_fitCs!)!Q!!< b! r%c2t||d}||}|S)Nrr@rrs r#rz!RegularGridInterpolator._do_pchipIs(AA6 b! r%c.t|j|SrY)r r )rPrzs r#rkz%RegularGridInterpolator._find_indicesOsDIIr**r%ctj|jdt}t ||j D]\}}|||dkz }|||dkDz }|S)Nrrrr)rzerosr,boolrr )rPrzr~rr s r#rz+RegularGridInterpolator._find_out_of_boundsRsd"((1+d; 2tyy) *GAt Qa[ (M Qb\ )M *r%rY)__name__ __module__ __qualname____doc__rVrurNlistkeysrDrCrrxrRrOr.r$rJrKrrjrsrtrErv staticmethodrrrkrr%r#rr8sNd&'q1,-qTUX!;<-2245Oi(?:L.6TFF.2>,% kHdkHZ78>+ B5n  +r%r9Tc |dvrtd|dt|dstj|}|j}|dkDr|dk(r td|s||dk(r td t ||kDrtd t |d |d t ||k7r|dk(r td t |\}}t||t|t |}|jdt |k7r'td|jddt ||ryt|jD]a\} } tjtj|| d| ktj| || dkrUtd| |tjvrt|||||} | |S|dk(r|j} |j!d|jd}tj|dd|dddfk|dddf|ddk|dd|dddfk|dddf|ddkfd} tj"|dddf}t%|d|d|dd} | j'|| df|| df|| <||tj(| <|j!| ddStd|)aL 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. 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] ) r9r:r3r4r5 splinef2dr2r6r7r8zinterpn only understands the methods 'linear', 'nearest', 'slinear', 'cubic', 'quintic', 'pchip', and 'splinef2d'. You provided rBr+rhrzBThe method splinef2d can only be used for 2-dimensional input dataNz4The method splinef2d does not support extrapolation.r'r(r)zSThe method splinef2d can only be used for scalar data with one point per coordinaterrrz1, but this RegularGridInterpolator has dimension rr)rFrHrLrr@zunknown method = )rr]rrr+r*r$r.rr,rrlrrrrCry empty_liker ev logical_not)rr-rzrFrHrLr+r rr!r"interpr| idx_validrs r#rr\s@xJJ::@DE E 66 "F# ;;D axFk)45 5 J.6[3HOPP 6{TV %CD6 U   6{dv4EF F#0"7D $' ""3t9 5B xx|s4y >A$i[ J  bddO DAq>>"&&aq"9"$&&d1gbk)9":< LQCP (555(6B4>@bz ; 88 ZZBHHRL )FFDGAJ"QT(2Bq!tHQ 4K GAJ"QT(2Bq!tHQ 4KM !# r!Q$x(%VAYq 6!9E"IIbA&69a<8HIy,6r~~i()~~hsm,,-F;/00r%)__all__rnumpyrscipy.sparse.linalgsparselinalgrT _interpndr_cubicr _rgi_cythonr r _bsplinesr _fitpack2r _ndbsplinerr$r.rrxrrr%r#rsX $i 0!!/%9)*#5.  aaH(0dvv`1r%