L i MdZddlZddlmZddlZddlmZddlm Z ddl m Z ddl m Z dd lmZmZmZd gZhd Zhd Zddddd dZdZdZGdd Zy)zModule for RBF interpolation.N)combinations_with_replacement) LinAlgError)KDTree)comb)dgesv) _build_system_build_evaluation_coefficients_polynomial_matrixRBFInterpolator>cubiclinearquinticgaussian multiquadricinverse_quadraticthin_plate_splineinverse_multiquadric>r rrr)rrrr rct||z|d}tj||ftjd}d}t |dzD]7}t t ||D]}|D]}|||fxxdz cc<|dz }9|S)a\Return the powers for each monomial in a polynomial. Parameters ---------- ndim : int Number of variables in the polynomial. degree : int Degree of the polynomial. Returns ------- (nmonos, ndim) int ndarray Array where each row contains the powers for each variable in a monomial. T)exactlongdtyperr)rnpzerosrranger)ndimdegreenmonosoutcountdegmonovars b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp.py_monomial_powersr'2s"&4-T 2F ((FD>&)9 :C EVaZ 1%+sC D %E3J1$ % QJE   JcRt||||||\}}}} t||dd\} } } } | dkrtd| d| dkDr`d} |jd}|dkDr?t ||z | z |}t j j|}||kr d|d|d } t| || | fS) aBuild and solve the RBF interpolation system of equations. Parameters ---------- y : (P, N) float ndarray Data point coordinates. d : (P, S) float ndarray Data values at `y`. smoothing : (P,) float ndarray Smoothing parameter for each data point. kernel : str Name of the RBF. epsilon : float Shape parameter. powers : (R, N) int ndarray The exponents for each monomial in the polynomial. Returns ------- coeffs : (P + R, S) float ndarray Coefficients for each RBF and monomial. shift : (N,) float ndarray Domain shift used to create the polynomial matrix. scale : (N,) float ndarray Domain scaling used to create the polynomial matrix. T) overwrite_a overwrite_brzThe z"-th argument had an illegal value.zSingular matrix.zqSingular matrix. The matrix of monomials evaluated at the data point coordinates does not have full column rank (/z).) r r ValueErrorshaper rlinalg matrix_rankr)yd smoothingkernelepsilonpowerslhsrhsshiftscale_coeffsinfomsgr pmatranks r&_build_and_solve_systemrARs8+ 1i& CeUsCTtLAq&$ ax4w&HIJJ  a A:%q5y%&7@D99((.Df}!F!F82/ # % r(c2eZdZdZ ddZ ddZdZy)r uTRadial basis function interpolator in N ≥ 1 dimensions. Parameters ---------- y : (npoints, ndims) array_like 2-D array of data point coordinates. d : (npoints, ...) array_like N-D array of data values at `y`. The length of `d` along the first axis must be equal to the length of `y`. Unlike some interpolators, the interpolation axis cannot be changed. neighbors : int, optional If specified, the value of the interpolant at each evaluation point will be computed using only this many nearest data points. All the data points are used by default. smoothing : float or (npoints, ) array_like, optional Smoothing parameter. The interpolant perfectly fits the data when this is set to 0. For large values, the interpolant approaches a least squares fit of a polynomial with the specified degree. Default is 0. kernel : str, optional Type of RBF. This should be one of - 'linear' : ``-r`` - 'thin_plate_spline' : ``r**2 * log(r)`` - 'cubic' : ``r**3`` - 'quintic' : ``-r**5`` - 'multiquadric' : ``-sqrt(1 + r**2)`` - 'inverse_multiquadric' : ``1/sqrt(1 + r**2)`` - 'inverse_quadratic' : ``1/(1 + r**2)`` - 'gaussian' : ``exp(-r**2)`` Default is 'thin_plate_spline'. epsilon : float, optional Shape parameter that scales the input to the RBF. If `kernel` is 'linear', 'thin_plate_spline', 'cubic', or 'quintic', this defaults to 1 and can be ignored because it has the same effect as scaling the smoothing parameter. Otherwise, this must be specified. degree : int, optional Degree of the added polynomial. For some RBFs the interpolant may not be well-posed if the polynomial degree is too small. Those RBFs and their corresponding minimum degrees are - 'multiquadric' : 0 - 'linear' : 0 - 'thin_plate_spline' : 1 - 'cubic' : 1 - 'quintic' : 2 The default value is the minimum degree for `kernel` or 0 if there is no minimum degree. Set this to -1 for no added polynomial. Notes ----- An RBF is a scalar valued function in N-dimensional space whose value at :math:`x` can be expressed in terms of :math:`r=||x - c||`, where :math:`c` is the center of the RBF. An RBF interpolant for the vector of data values :math:`d`, which are from locations :math:`y`, is a linear combination of RBFs centered at :math:`y` plus a polynomial with a specified degree. The RBF interpolant is written as .. math:: f(x) = K(x, y) a + P(x) b, where :math:`K(x, y)` is a matrix of RBFs with centers at :math:`y` evaluated at the points :math:`x`, and :math:`P(x)` is a matrix of monomials, which span polynomials with the specified degree, evaluated at :math:`x`. The coefficients :math:`a` and :math:`b` are the solution to the linear equations .. math:: (K(y, y) + \lambda I) a + P(y) b = d and .. math:: P(y)^T a = 0, where :math:`\lambda` is a non-negative smoothing parameter that controls how well we want to fit the data. The data are fit exactly when the smoothing parameter is 0. The above system is uniquely solvable if the following requirements are met: - :math:`P(y)` must have full column rank. :math:`P(y)` always has full column rank when `degree` is -1 or 0. When `degree` is 1, :math:`P(y)` has full column rank if the data point locations are not all collinear (N=2), coplanar (N=3), etc. - If `kernel` is 'multiquadric', 'linear', 'thin_plate_spline', 'cubic', or 'quintic', then `degree` must not be lower than the minimum value listed above. - If `smoothing` is 0, then each data point location must be distinct. When using an RBF that is not scale invariant ('multiquadric', 'inverse_multiquadric', 'inverse_quadratic', or 'gaussian'), an appropriate shape parameter must be chosen (e.g., through cross validation). Smaller values for the shape parameter correspond to wider RBFs. The problem can become ill-conditioned or singular when the shape parameter is too small. The memory required to solve for the RBF interpolation coefficients increases quadratically with the number of data points, which can become impractical when interpolating more than about a thousand data points. To overcome memory limitations for large interpolation problems, the `neighbors` argument can be specified to compute an RBF interpolant for each evaluation point using only the nearest data points. .. versionadded:: 1.7.0 See Also -------- NearestNDInterpolator LinearNDInterpolator CloughTocher2DInterpolator References ---------- .. [1] Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab. World Scientific Publishing Co. .. [2] http://amadeus.math.iit.edu/~fass/603_ch3.pdf .. [3] Wahba, G., 1990. Spline Models for Observational Data. SIAM. .. [4] http://pages.stat.wisc.edu/~wahba/stat860public/lect/lect8/lect8.pdf Examples -------- Demonstrate interpolating scattered data to a grid in 2-D. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.interpolate import RBFInterpolator >>> from scipy.stats.qmc import Halton >>> rng = np.random.default_rng() >>> xobs = 2*Halton(2, seed=rng).random(100) - 1 >>> yobs = np.sum(xobs, axis=1)*np.exp(-6*np.sum(xobs**2, axis=1)) >>> xgrid = np.mgrid[-1:1:50j, -1:1:50j] >>> xflat = xgrid.reshape(2, -1).T >>> yflat = RBFInterpolator(xobs, yobs)(xflat) >>> ygrid = yflat.reshape(50, 50) >>> fig, ax = plt.subplots() >>> ax.pcolormesh(*xgrid, ygrid, vmin=-0.25, vmax=0.25, shading='gouraud') >>> p = ax.scatter(*xobs.T, c=yobs, s=50, ec='k', vmin=-0.25, vmax=0.25) >>> fig.colorbar(p) >>> plt.show() Nc tj|td}|jdk7r t d|j \}} tj |rtnt} tj|| d}|j d|k7rt d|d|j dd} |j|d f}|jt}tj|rtj||t }n;tj|td}|j |fk7rt d |d |j}|tvrt d td||tvrd}nt dtdt|}tj!|d } | t#| d}nLt%|}|d kr t dd |cxkr| kr&nn#t'j(d| d|dt*d||} nt%t-||}|} t/| |}|j d| kDr"t d|j dd|d| d|*t1||||||\}}}||_||_||_nt9||_||_||_| |_ | |_!||_"||_#||_$||_%||_&y)NCrorderrz"`y` must be a 2-dimensional array.rz.Expected the first axis of `d` to have length .rrz3Expected `smoothing` to be a scalar or have shape (z,).z`kernel` must be one of g?z6`epsilon` must be specified if `kernel` is not one of z`degree` must be at least -1.z`degree` should not be below z except -1 when `kernel` is 'zk'.The interpolant may not be uniquely solvable, and the smoothing parameter may have an unintuitive effect.) stacklevelz At least z+ data points are required when `degree` is z! and the number of dimensions is )'rasarrayfloatrr-r. iscomplexobjcomplexreshapeviewisscalarfulllower _AVAILABLE_SCALE_INVARIANT_NAME_TO_MIN_DEGREEgetmaxintwarningswarn UserWarningminr'rA_shift_scale_coeffsr_treer1r2d_shaped_dtype neighborsr3r4r5r6)selfr1r2rcr3r4r5rnyrrbra min_degreenobsr6r9r:r<s r&__init__zRBFInterpolator.__init__s JJqS 1 66Q;AB B77D__Q/'U JJqs 3 771: @AF ''!"+ IIr2h  FF5M ;;y !IU;I 9EEI2%' t3    #7 |1EF F ?)) L'(+ GnG(,,VR8 >Q'F[F{ !@AAf)z) 3J<@))/1*+  A   DC 2./ID!$/ <<?T !FLLO,-%h&GvQP   #:1i&$ E5&  DKDK!DL DJ  ""   r(c |j\}}|j t|} n |j} ||jjd| zzdz} | |krt j ||j jdft} td|| D]_} t|| | | zddf||j|j|j||} t j| || | | | zddf<a| St|||j|j|j||} t j| |} | S)a Evaluate the interpolation while controlling memory consumption. We chunk the input if we need more memory than specified. Parameters ---------- x : (Q, N) float ndarray array of points on which to evaluate y: (P, N) float ndarray array of points on which we know function values shift: (N, ) ndarray Domain shift used to create the polynomial matrix. scale : (N,) float ndarray Domain scaling used to create the polynomial matrix. coeffs: (P+R, S) float ndarray Coefficients in front of basis functions memory_budget: int Total amount of memory (in units of sizeof(float)) we wish to devote for storing the array of coefficients for interpolated points. If we need more memory than that, we chunk the input. Returns ------- (Q, S) float ndarray Interpolated array Nrrr) r.rclenr6remptyr2rKrr r4r5dot)rdxr1r9r:r< memory_budgetnxrnnei chunksizer!ivecs r&_chunk_evaluatorz RBFInterpolator._chunk_evaluators=H77D >> !q6D>>D!dkk&7&7&:T&ABQF ?((B Q0>C1b), >4aI oq()KKLLKK+-&&f*=Aa)mOQ&' >( 1   C&&f%C r(c tj|td}|jdk7r t d|j \}}||j j dk7r&t d|j j ddt|j|j jz|jjzd}|jA|j||j |j|j|j| }n|jj!||j\}}|jdk(r |d d d f}tj"|d }tj$|d d \}}tj&|d}t)t+|Dcgc]}g} }t-|D]\} } | | j/| tj0||jj dft}t3| |D]\} } || }|j | }|j| }|j4| }t7||||j8|j:|j<\}}}|j|||||| || <|j?|j@}|j'|f|jBz}|Scc}w)aEvaluate the interpolant at `x`. Parameters ---------- x : (Q, N) array_like Evaluation point coordinates. Returns ------- (Q, ...) ndarray Values of the interpolant at `x`. rDrErz"`x` must be a 2-dimensional array.rz/Expected the second axis of `x` to have length rG@BN)rn)axisTr)return_inverserw)rHr)"rrJrKrr-r.r1rWsizer2rcrtr]r^r_r`querysortuniquerNrrj enumerateappendrkzipr3rAr4r5r6rOrbra)rdrmrorrnr!r;yindicesinvxindicesrrjxidxyidxxnbrynbrdnbrsnbrr9r:r<s r&__call__zRBFInterpolator.__call__s JJqS 1 66Q;AB B77D 466<<? "N $ Q034 4AFFTVV[[0466;;>H >> !''   + (-C****1dnn=KAx~~"#AtG, wwxa0HIIht!LMHc**S%(C%*#h-$89q9H9!# &1 ""1% &((B Q0>C!(H5 1 dwvvd|vvd|~~d+'>KKLLKK ($uf!11"/ 21D ! 10hht||$kk2&4<</0 ?:s8 K,)NgrNN)rv)__name__ __module__ __qualname____doc__rhrtrr(r&r r s3Vr + kh"AFWr()rrY itertoolsrnumpyr numpy.linalgr scipy.spatialr scipy.specialrscipy.linalg.lapackr_rbfinterp_pythranr r r __all__rSrTrUr'rAr rr(r&rsr#3$ %55    G  @1 h``r(