L iA_ bdZgdZddlZddlmZddlmZmZmZm Z m Z ddlZ ddl m Z ddl mZej j"j$ZeZd d d d d ZdddddddddZGddZGddeZdZGddeZGddZddddddd d!ZGd"d#eZGd$d%eZGd&d'eZGd(d)eZ Gd*d+eZ!ejEZ#d,e#d-<d.e#d/<Gd0d1eZ$Gd2d3e$Z%Gd4d5e$Z&ejEZ'd6e'd-<Gd7d8e$Z(y)9z fitpack --- curve and surface fitting with splines fitpack is based on a collection of Fortran routines DIERCKX by P. Dierckx (see http://www.netlib.org/dierckx/) transformed to double routines by Pearu Peterson. ) UnivariateSplineInterpolatedUnivariateSplineLSQUnivariateSplineBivariateSplineLSQBivariateSplineSmoothBivariateSplineLSQSphereBivariateSplineSmoothSphereBivariateSplineRectBivariateSplineRectSphereBivariateSplineN)Lock)zeros concatenateraveldiffarray) _fitpack_impl) _dfitpacka The required storage space exceeds the available storage space, as specified by the parameter nest: nest too small. If nest is already large (say nest > m/2), it may also indicate that s is too small. The approximation returned is the weighted least-squares spline according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp gives the corresponding weighted sum of squared residuals (fp>s). a A theoretically impossible result was found during the iteration process for finding a smoothing spline with fp = s: s too small. There is an approximation returned but the corresponding weighted sum of squared residuals does not satisfy the condition abs(fp-s)/s < tol.a The maximal number of iterations maxit (set to 20 by the program) allowed for finding a smoothing spline with fp=s has been reached: s too small. There is an approximation returned but the corresponding weighted sum of squared residuals does not satisfy the condition abs(fp-s)/s < tol.z Error on entry, no approximation returned. The following conditions must hold: xb<=x[0]0, i=0..m-1 if iopt=-1: xb>> import numpy as np >>> from scipy.interpolate import UnivariateSpline >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4]) >>> w = np.isnan(y) >>> y[w] = 0. >>> spl = UnivariateSpline(x, y, w=~w) Notice the need to replace a ``nan`` by a numerical value (precise value does not matter as long as the corresponding weight is zero.) References ---------- Based on algorithms described in [1]_, [2]_, [3]_, and [4]_: .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and integration of experimental data using spline functions", J.Comp.Appl.Maths 1 (1975) 165-184. .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular grid while using spline functions", SIAM J.Numer.Anal. 19 (1982) 1286-1304. .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981. .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on Numerical Analysis, Oxford University Press, 1993. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.interpolate import UnivariateSpline >>> rng = np.random.default_rng() >>> x = np.linspace(-3, 3, 50) >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) >>> plt.plot(x, y, 'ro', ms=5) Use the default value for the smoothing parameter: >>> spl = UnivariateSpline(x, y) >>> xs = np.linspace(-3, 3, 1000) >>> plt.plot(xs, spl(xs), 'g', lw=3) Manually change the amount of smoothing: >>> spl.set_smoothing_factor(0.5) >>> plt.plot(xs, spl(xs), 'b', lw=3) >>> plt.show() Nrrr Fc $|j||||||||\}}}}|_t5tj|||||d|d|} ddd ddk(r|j | } | |_|jy#1swY:xYw)Nr rwxbxes)validate_inputext FITPACK_LOCKdfitpackfpcurf0 _reset_nest_data _reset_class) selfxyrbboxkr"r% check_finitedatas a/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/interpolate/_fitpack2.py__init__zUnivariateSpline.__init__s#'"5"5aAtQ36B#D1atx 5##Aq!qT!W'+Aw!5D 5 8q=##D)D   5 5s #BBc0tj|tj|tj|}}}|tj|}|rz|#tj|jnd}tj|jr%tj|jr|s t d||dkDr,tjt |dk\s7t dtjt |dkDs t d|j |j k7r t d|@|j |j cxk(r|j k(st dt d|jd k7r t d d |cxkrd kst d t d ||dk\s t d t|}|||||fS#t$r} t d|d| d} ~ wwxYw)NTz,x and y array must not contain NaNs or infs.r zx must be increasing if s > 0z&x must be strictly increasing if s = 0z!x and y should have a same lengthz%x, y, and w should have a same length)rzbbox shape should be (2,)rzk should be 1 <= k <= 5s should be s >= 0.0Unknown extrapolation mode .) npasarrayisfiniteall ValueErrorrsizeshape _extrap_modesKeyError) r-r.rr/r0r"r%r1w_finitees r3r$zUnivariateSpline.validate_inputsZZ]BJJqM2::d3Cd1 = 1 A /0}r{{1~))+$HKKN&&( A0B0B0D  "122 9A66$q'S.) !@AA66$q'C-( !IJJ 66QVV @A A ]166QVV#=qvv#=DE E$>DE E ZZ4 89 9q+A+67 767 7 ]1834 4 J$C!Qc!! J:3%qAB I Js' G77 HHHc|j|}|\}}}||_ddddd|dt|||ddddf|_||_|S)z(Construct a spline object from given tckN)__new__ _eval_argslenr*r%)clstckr%r,tcr0s r3 _from_tckzUnivariateSpline._from_tcks[{{31aD$dAtSVQtT41  c|j}|d|d|d|d|df\}}}}}|d||d||f|_|dk(ry|dk(r|jty|dk(r|jty|dk(r|jtt j |d |}tj|d y) N r7r#r rier=r stacklevel) r*rH _set_classrr_curfit_messagesgetwarningswarn)r,r2nrLrMr0iermessages r3r+zUnivariateSpline._reset_class*szzq'47DGT!Wd2hF1aCBQ%2A/ !8  BY OO8 9 BY OO/ 0ax 34&**3$se =G MM'a 0rOc\||_|jtttfvr||_yyN) _spline_class __class__rrr)r,rJs r3rXzUnivariateSpline._set_classBs0  >>.0L13 3 DN rOcd}dtd}}||zdzn|ks tdfddD\}}}} dd||||| d fz} t5tj| dddS#1swYSxYw) Nrr7r rz`nest` can only be increasedc3PK|]}tj|ywra)r;resize).0jr2nests r3 z/UnivariateSpline._reset_nest..Ss$/Aryya$7/s#&)rRrS rR )rIr?r&r'fpcurf1) r,r2rir]r0mrLrMfpintnrdataargss `` r3r)zUnivariateSpline._reset_nestKs H <7CQLqAQ3q5D9 !?@@/-/1eVBQx1aE648<<  +##T*D +  + s A;;Bc4|j}|ddk(rtjddy|dd|fz|ddz}t5t j |}ddd|ddk(r|j |}||_|jy#1swY:xYw) z Continue spline computation with the given smoothing factor s and with the knots found at the last call. This routine modifies the spline in place. r#z9smoothing factor unchanged forLSQ spline with fixed knotsrrVNrQr)r*r[r\r&r'rnr)r+)r,r"r2rrs r3set_smoothing_factorz%UnivariateSpline.set_smoothing_factor[szz 7b= MM8%& ( BQx1$ab)  +##T*D + 8q=##D)D    + +s BBcRtj|}|jdk(r tgS| |j}n t |}t5tj||j||cdddS#t $r}td|d|d}~wwxYw#1swYyxYw)a Evaluate spline (or its nu-th derivative) at positions x. Parameters ---------- x : array_like A 1-D array of points at which to return the value of the smoothed spline or its derivatives. Note: `x` can be unordered but the evaluation is more efficient if `x` is (partially) ordered. nu : int The order of derivative of the spline to compute. ext : int Controls the value returned for elements of `x` not in the interval defined by the knot sequence. * if ext=0 or 'extrapolate', return the extrapolated value. * if ext=1 or 'zeros', return 0 * if ext=2 or 'raise', raise a ValueError * if ext=3 or 'const', return the boundary value. The default value is 0, passed from the initialization of UnivariateSpline. r Nr9r:)derr%) r;r<r@rr%rBrCr?r&rsplevrH)r,r-nur%rEs r3__call__zUnivariateSpline.__call__qs2 JJqM 66Q;9  ;((C N#C( L &&q$//rsK L L N #>se1!EFAM N L Ls$ A<#B< BBBB&cD|j}|d|d}}|d|||z S)z Return positions of interior knots of the spline. Internally, the knot vector contains ``2*k`` additional boundary knots. r7rQrRr*r,r2r0r]s r3 get_knotszUnivariateSpline.get_knotss2 zzAwQ1Awq1~rOcJ|j}|d|d}}|dd||z dz S)zReturn spline coefficients.r7rQrSNrr|r}s r3 get_coeffszUnivariateSpline.get_coeffss4zzAwQ1Awv!ArOc |jdS)zReturn weighted sum of squared residuals of the spline approximation. This is equivalent to:: sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) rr|r,s r3 get_residualzUnivariateSpline.get_residualszz"~rOc|t5tj|||jcdddS#1swYyxYw)a Return definite integral of the spline between two given points. Parameters ---------- a : float Lower limit of integration. b : float Upper limit of integration. Returns ------- integral : float The value of the definite integral of the spline between limits. Examples -------- >>> import numpy as np >>> from scipy.interpolate import UnivariateSpline >>> x = np.linspace(0, 3, 11) >>> y = x**2 >>> spl = UnivariateSpline(x, y) >>> spl.integral(0, 3) 9.0 which agrees with :math:`\int x^2 dx = x^3 / 3` between the limits of 0 and 3. A caveat is that this routine assumes the spline to be zero outside of the data limits: >>> spl.integral(-1, 4) 9.0 >>> spl.integral(-1, 0) 0.0 N)r&rsplintrH)r,abs r3integralzUnivariateSpline.integrals3J ? ''1doo> ? ? ?s!2;czt5tj||jcdddS#1swYyxYw)aE Return all derivatives of the spline at the point x. Parameters ---------- x : float The point to evaluate the derivatives at. Returns ------- der : ndarray, shape(k+1,) Derivatives of the orders 0 to k. Examples -------- >>> import numpy as np >>> from scipy.interpolate import UnivariateSpline >>> x = np.linspace(0, 3, 11) >>> y = x**2 >>> spl = UnivariateSpline(x, y) >>> spl.derivatives(1.5) array([2.25, 3.0, 2.0, 0]) N)r&rspalderH)r,r-s r3 derivativeszUnivariateSpline.derivativess00 < ''4??; < < >> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05] >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03, ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03, ... 6.520430e-03, 8.170770e-03] >>> from scipy.interpolate import UnivariateSpline >>> spl = UnivariateSpline(x, y, s=0) >>> spl.roots() array([], dtype=float64) Converting to a PPoly object does find the roots at `x=2`: >>> from scipy.interpolate import splrep, PPoly >>> tck = splrep(x, y, s=0) >>> ppoly = PPoly.from_spline(tck) >>> ppoly.roots(extrapolate=False) array([2.]) See Also -------- sproot PPoly.roots r7rr rQ)mestNz/finding roots unsupported for non-cubic splines)r*rHrIr&rsprootNotImplementedError)r,r0rLrs r3rootszUnivariateSpline.rootssR JJqM 6"AA #D H$++DOO$G H H!#67 7 H!#67 7s !A11Bct5tj|j|}ddd|jdk(rdn |j}t j |S#1swY=xYw)a Construct a new spline representing the derivative of this spline. Parameters ---------- n : int, optional Order of derivative to evaluate. Default: 1 Returns ------- spline : UnivariateSpline Spline of order k2=k-n representing the derivative of this spline. See Also -------- splder, antiderivative Notes ----- .. versionadded:: 0.13.0 Examples -------- This can be used for finding maxima of a curve: >>> import numpy as np >>> from scipy.interpolate import UnivariateSpline >>> x = np.linspace(0, 10, 70) >>> y = np.sin(x) >>> spl = UnivariateSpline(x, y, k=4, s=0) Now, differentiate the spline and find the zeros of the derivative. (NB: `sproot` only works for order 3 splines, so we fit an order 4 spline): >>> spl.derivative().roots() / np.pi array([ 0.50000001, 1.5 , 2.49999998]) This agrees well with roots :math:`\pi/2 + n\pi` of :math:`\cos(x) = \sin'(x)`. Nrr)r%)r&rsplderrHr%rrN)r,r]rKr%s r3 derivativezUnivariateSpline.derivative&s`Z ;&&t:C ;88q=adhh))#3)77  ; ;s !A$$A-ct5tj|j|}dddtj |j S#1swY)xYw)a Construct a new spline representing the antiderivative of this spline. Parameters ---------- n : int, optional Order of antiderivative to evaluate. Default: 1 Returns ------- spline : UnivariateSpline Spline of order k2=k+n representing the antiderivative of this spline. Notes ----- .. versionadded:: 0.13.0 See Also -------- splantider, derivative Examples -------- >>> import numpy as np >>> from scipy.interpolate import UnivariateSpline >>> x = np.linspace(0, np.pi/2, 70) >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2) >>> spl = UnivariateSpline(x, y, s=0) The derivative is the inverse operation of the antiderivative, although some floating point error accumulates: >>> spl(1.7), spl.antiderivative().derivative()(1.7) (array(2.1565429877197317), array(2.1565429877201865)) Antiderivative can be used to evaluate definite integrals: >>> ispl = spl.antiderivative() >>> ispl(np.pi/2) - ispl(0) 2.2572053588768486 This is indeed an approximation to the complete elliptic integral :math:`K(m) = \int_0^{\pi/2} [1 - m\sin^2 x]^{-1/2} dx`: >>> from scipy.special import ellipk >>> ellipk(0.8) 2.2572053268208538 N)r&r splantiderrHrrNr%)r,r]rKs r3antiderivativezUnivariateSpline.antiderivativeYsJh ?**4??A>C ?))#txx88 ? ?s !AA)r ra)r N)r)__name__ __module__ __qualname____doc__r4 staticmethodr$ classmethodrNr+rXr)rurzr~rrrrrrrrOr3rrIs_B $4&(a4U  " "D  10 ,%LN &?P<607d18f69rOrc*eZdZdZddgdzdddfdZy)ra> 1-D interpolating spline for a given set of data points. .. legacy:: class Specifically, we recommend using `make_interp_spline` instead. Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. Spline function passes through all provided points. Equivalent to `UnivariateSpline` with `s` = 0. Parameters ---------- x : (N,) array_like Input dimension of data points -- must be strictly increasing y : (N,) array_like input dimension of data points w : (N,) array_like, optional Weights for spline fitting. Must be positive. If None (default), weights are all 1. bbox : (2,) array_like, optional 2-sequence specifying the boundary of the approximation interval. If None (default), ``bbox=[x[0], x[-1]]``. k : int, optional Degree of the smoothing spline. Must be ``1 <= k <= 5``. Default is ``k = 3``, a cubic spline. ext : int or str, optional Controls the extrapolation mode for elements not in the interval defined by the knot sequence. * if ext=0 or 'extrapolate', return the extrapolated value. * if ext=1 or 'zeros', return 0 * if ext=2 or 'raise', raise a ValueError * if ext=3 of 'const', return the boundary value. The default value is 0. check_finite : bool, optional Whether to check that the input arrays contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination or non-sensical results) if the inputs do contain infinities or NaNs. Default is False. See Also -------- UnivariateSpline : a smooth univariate spline to fit a given set of data points. LSQUnivariateSpline : a spline for which knots are user-selected SmoothBivariateSpline : a smoothing bivariate spline through the given points LSQBivariateSpline : a bivariate spline using weighted least-squares fitting splrep : a function to find the B-spline representation of a 1-D curve splev : a function to evaluate a B-spline or its derivatives sproot : a function to find the roots of a cubic B-spline splint : a function to evaluate the definite integral of a B-spline between two given points spalde : a function to evaluate all derivatives of a B-spline Notes ----- The number of data points must be larger than the spline degree `k`. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.interpolate import InterpolatedUnivariateSpline >>> rng = np.random.default_rng() >>> x = np.linspace(-3, 3, 50) >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) >>> spl = InterpolatedUnivariateSpline(x, y) >>> plt.plot(x, y, 'ro', ms=5) >>> xs = np.linspace(-3, 3, 1000) >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7) >>> plt.show() Notice that the ``spl(x)`` interpolates `y`: >>> spl.get_residual() 0.0 Nrrr Fc F|j|||||d||\}}}}|_tjt |dkDs t dt 5tj|||||d|dd|_ ddd|jy#1swYxYw)Nr6x must be strictly increasingr rr) r$r%r;r>rr?r&r'r(r*r+)r,r-r.rr/r0r%r1s r3r4z%InterpolatedUnivariateSpline.__init__s#'"5"5aAtQ,/#?1atxvvd1gm$<= = ;!))!QQ47-1!W;DJ ;  ; ;s (BB rrrrr4rrOr3rrs"Yv $4&(aU rOraThe input parameters have been rejected by fpchec. This means that at least one of the following conditions is violated: 1) k+1 <= n-k-1 <= m 2) t(1) <= t(2) <= ... <= t(k+1) t(n-k) <= t(n-k+1) <= ... <= t(n) 3) t(k+1) < t(k+2) < ... < t(n-k) 4) t(k+1) <= x(i) <= t(n-k) 5) The conditions specified by Schoenberg and Whitney must hold for at least one subset of data points, i.e., there must be a subset of data points y(j) such that t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 c*eZdZdZddgdzdddfdZy)ra 1-D spline with explicit internal knots. .. legacy:: class Specifically, we recommend using `make_lsq_spline` instead. Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `t` specifies the internal knots of the spline Parameters ---------- x : (N,) array_like Input dimension of data points -- must be increasing y : (N,) array_like Input dimension of data points t : (M,) array_like interior knots of the spline. Must be in ascending order and:: bbox[0] < t[0] < ... < t[-1] < bbox[-1] w : (N,) array_like, optional weights for spline fitting. Must be positive. If None (default), weights are all 1. bbox : (2,) array_like, optional 2-sequence specifying the boundary of the approximation interval. If None (default), ``bbox = [x[0], x[-1]]``. k : int, optional Degree of the smoothing spline. Must be 1 <= `k` <= 5. Default is `k` = 3, a cubic spline. ext : int or str, optional Controls the extrapolation mode for elements not in the interval defined by the knot sequence. * if ext=0 or 'extrapolate', return the extrapolated value. * if ext=1 or 'zeros', return 0 * if ext=2 or 'raise', raise a ValueError * if ext=3 of 'const', return the boundary value. The default value is 0. check_finite : bool, optional Whether to check that the input arrays contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination or non-sensical results) if the inputs do contain infinities or NaNs. Default is False. Raises ------ ValueError If the interior knots do not satisfy the Schoenberg-Whitney conditions See Also -------- UnivariateSpline : a smooth univariate spline to fit a given set of data points. InterpolatedUnivariateSpline : a interpolating univariate spline for a given set of data points. splrep : a function to find the B-spline representation of a 1-D curve splev : a function to evaluate a B-spline or its derivatives sproot : a function to find the roots of a cubic B-spline splint : a function to evaluate the definite integral of a B-spline between two given points spalde : a function to evaluate all derivatives of a B-spline Notes ----- The number of data points must be larger than the spline degree `k`. Knots `t` must satisfy the Schoenberg-Whitney conditions, i.e., there must be a subset of data points ``x[j]`` such that ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. Examples -------- >>> import numpy as np >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng() >>> x = np.linspace(-3, 3, 50) >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) Fit a smoothing spline with a pre-defined internal knots: >>> t = [-1, 0, 1] >>> spl = LSQUnivariateSpline(x, y, t) >>> xs = np.linspace(-3, 3, 1000) >>> plt.plot(x, y, 'ro', ms=5) >>> plt.plot(xs, spl(xs), 'g-', lw=3) >>> plt.show() Check the knot vector: >>> spl.get_knots() array([-3., -1., 0., 1., 3.]) Constructing lsq spline using the knots from another spline: >>> x = np.arange(10) >>> s = UnivariateSpline(x, x, s=0) >>> s.get_knots() array([ 0., 2., 3., 4., 5., 6., 7., 9.]) >>> knt = s.get_knots() >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1]) # Chop 1st and last knot >>> s1.get_knots() array([ 0., 2., 3., 4., 5., 6., 7., 9.]) Nrrr Fc |j|||||d||\}}}}|_tjt |dk\s t d|d} |d} | |d} | |d} t | g|dzz|| g|dzzf}t|} tj||dz| |z ||| |z dz z dkDds t dt5tj|||dk(st ttj|||||| | } ddd dd dd| dfz|_ |jy#1swY-xYw) Nr6zx must be increasingr rr#)axisz;Interior knots t must satisfy Schoenberg-Whitney conditions)rr r!)r$r%r;r>rr?rrIr&r'fpchec_fpchec_error_stringfpcurfm1r*r+) r,r-r.rLrr/r0r%r1r r!r]r2s r3r4zLSQUnivariateSpline.__init__s{#'"5"5aAtQ69<#I1atxvvd1gn%34 4!W !W :1B :2B "qsQac 3 4 Fvva!AaCj1QqSU+a/a8=> >  D??1a+q0 !566$$Q1a1CD D#2Y$d2h!77    D Ds AEE rrrOr3rr s"sj#'dVAXUrOrc@eZdZdZedZdZdZdZd dZ dZ y) _BivariateSplineBasea Base class for Bivariate spline s(x,y) interpolation on the rectangle [xb,xe] x [yb, ye] calculated from a given set of data points (x,y,z). See Also -------- bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives BivariateSpline : a base class for bivariate splines. SphereBivariateSpline : a bivariate spline on a spherical grid c|j|}t|dk7r td|dd|_|dd|_|S)z3Construct a spline object from given tck and degreer7z4tck should be a 5 element tuple of tx, ty, c, kx, kyNr)rGrIr?rKdegrees)rJrKr,s r3rNz_BivariateSplineBase._from_tcksN{{3 s8q=./ /r712w  rOc|jS)z Return weighted sum of squared residuals of the spline approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0) )fprs r3rz!_BivariateSplineBase.get_residuals wwrOc |jddS)a Return a tuple (tx,ty) where tx,ty contain knots positions of the spline with respect to x-, y-variable, respectively. The position of interior and additional knots are given as t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively. NrrKrs r3r~z_BivariateSplineBase.get_knotss xx|rOc |jdS)z Return spline coefficients.rrrs r3rz_BivariateSplineBase.get_coeffssxx{rOc rtj|}tj|}|jdd\}}}|j\} } |rt|jdk(s|jdk(rDtj |j|jf|jdj S|jdk\r6tjtj|dk\s td|jdk\r6tjtj|dk\s td|s|rBt5tj|||| | |||| \} } ddd dk(sNtd | t5tj|||| | ||\} } ddd dk(std |  S|j|jk7rtj||\}}|j} |j!}|j!}|jdk(s|jdk(r.tj | |jdj S|s|rBt5tj"|||| | |||| \} } ddd dk(sNtd | t5tj$|||| | ||\} } ddd dk(std |  j'| } | S#1swYxYw#1swYoxYw#1swYxYw#1swYUxYw) a Evaluate the spline or its derivatives at given positions. Parameters ---------- x, y : array_like Input coordinates. If `grid` is False, evaluate the spline at points ``(x[i], y[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting is obeyed. If `grid` is True: evaluate spline at the grid points defined by the coordinate arrays x, y. The arrays must be sorted to increasing order. The ordering of axes is consistent with ``np.meshgrid(..., indexing="ij")`` and inconsistent with the default ordering ``np.meshgrid(..., indexing="xy")``. dx : int Order of x-derivative .. versionadded:: 0.14.0 dy : int Order of y-derivative .. versionadded:: 0.14.0 grid : bool Whether to evaluate the results on a grid spanned by the input arrays, or at points specified by the input arrays. .. versionadded:: 0.14.0 Examples -------- Suppose that we want to bilinearly interpolate an exponentially decaying function in 2 dimensions. >>> import numpy as np >>> from scipy.interpolate import RectBivariateSpline We sample the function on a coarse grid. Note that the default indexing="xy" of meshgrid would result in an unexpected (transposed) result after interpolation. >>> xarr = np.linspace(-3, 3, 100) >>> yarr = np.linspace(-3, 3, 100) >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij") The function to interpolate decays faster along one axis than the other. >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2)) Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear). >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1) >>> xarr_fine = np.linspace(-3, 3, 200) >>> yarr_fine = np.linspace(-3, 3, 200) >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij") >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False) And check that the result agrees with the input by plotting both. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal") >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal") >>> ax1.imshow(zdata) >>> ax2.imshow(zdata_interp) >>> plt.show() Nrr rdtyper6z1x must be strictly increasing when `grid` is Truez1y must be strictly increasing when `grid` is TruezError code returned by parder: zError code returned by bispev: zError code returned by pardeu: zError code returned by bispeu: )r;r<rKrr@rrr>rr?r&r'parderbispevrAbroadcast_arraysrpardeubispeureshape)r,r-r.dxdygridtxtyrMkxkyzr^rAs r3rzz_BivariateSplineBase.__call__sP JJqM JJqMHHRaL BB vv{affkxx 0 8I8IJJ! bffRWWQZ3->&? !TUU! bffRWWQZ3->&? !TUUR!N%__RQBB1MFAsNax$'Fse%LMM!F%__RQB1EFAsFax$'Fse%LMM2-ww!''!**1a01GGE A Avv{affkxxTXXa[->->??R!N%__RQBB1MFAsNax$'Fse%LMM!F%__RQB1EFAsFax$'Fse%LMM % ACNN FF"NN FFs0!LL8!L!:L-LL!L*-L6c |dk(r|dk(r|S|j\}}|dk\r|dk\s td||kr||ks td|jdd\}}}t5t j |||||||\}} ddd dk7rtd| t |} t |} ||| |z } ||| |z } ||z ||z }}| |z |z dz | |z |z dz z}tj| | d|||fS#1swYxYw)a\Construct a new spline representing a partial derivative of this spline. Parameters ---------- dx, dy : int Orders of the derivative in x and y respectively. They must be non-negative integers and less than the respective degree of the original spline (self) in that direction (``kx``, ``ky``). Returns ------- spline : A new spline of degrees (``kx - dx``, ``ky - dy``) representing the derivative of this spline. Notes ----- .. versionadded:: 1.9.0 r z,order of derivative must be positive or zeroz6order of derivative must be less than degree of splineNrz*Unexpected error code returned by pardtc: r) rr?rKr&r'pardtcrI_DerivedBivariateSplinerN)r,rrrrrrrMnewcr^nxnynewtxnewtynewkxnewkynewclens r3partial_derivativez'_BivariateSplineBase.partial_derivativeHs\. 7rQwK\\FB!Ga ")**GR "566! IBA G$OOBAr2r2F c Gax #McU!STTRBRBr"r'NEr"r'NE7BG5EBw|a'BGbL1,<=G*44eU6:8Gn6;U6DE E G Gs C==DNr r T) rrrrrrNrr~rrzrrrOr3rrs7  xt/ErOrz The required storage space exceeds the available storage space: nxest or nyest too small, or s too small. The weighted least-squares spline corresponds to the current set of knots.z A theoretically impossible result was found during the iteration process for finding a smoothing spline with fp = s: s too small or badly chosen eps. Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.a the maximal number of iterations maxit (set to 20 by the program) allowed for finding a smoothing spline with fp=s has been reached: s too small. Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol. Try increasing maxit by passing it as a keyword argument.z No more knots can be added because the number of b-spline coefficients (nx-kx-1)*(ny-ky-1) already exceeds the number of data points m: either s or m too small. The weighted least-squares spline corresponds to the current set of knots.z No more knots can be added because the additional knot would (quasi) coincide with an old one: s too small or too large a weight to an inaccurate data point. The weighted least-squares spline corresponds to the current set of knots.z Error on entry, no approximation returned. The following conditions must hold: xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1 If iopt==-1, then xb>> import numpy as np >>> from scipy.interpolate import RectBivariateSpline >>> def f(x, y): ... return np.exp(-np.sqrt((x / 2) ** 2 + y**2)) We sample the function on a coarse grid and set up the interpolator. Note that the default ``indexing="xy"`` of meshgrid would result in an unexpected (transposed) result after interpolation. >>> xarr = np.linspace(-3, 3, 21) >>> yarr = np.linspace(-3, 3, 21) >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij") >>> zdata = f(xgrid, ygrid) >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1) Next we sample the function along a diagonal slice through the coordinate space on a finer grid using interpolation. >>> xinterp = np.linspace(-3, 3, 201) >>> yinterp = np.linspace(3, -3, 201) >>> zinterp = rbs.ev(xinterp, yinterp) And check that the interpolation passes through the function evaluations as a function of the distance from the origin along the slice. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(1, 1, 1) >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or") >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b") >>> plt.show() Frrrrz)r,xiyirrs r3evzBivariateSpline.evsx}}Rr}>>rOc |jdd\}}}|j\}} t5tj||||| |||| cdddS#1swYyxYw)a Evaluate the integral of the spline over area [xa,xb] x [ya,yb]. Parameters ---------- xa, xb : float The end-points of the x integration interval. ya, yb : float The end-points of the y integration interval. Returns ------- integ : float The value of the resulting integral. Nr)rKrr&r'dblint) r,xar yaybrrrMrrs r3rzBivariateSpline.integrals^"HHRaL BB  F??2r1b"b"b"E F F Fs AAcVtj|tj|tj|}}}|j|jcxk(r|jk(stdtd|\tj|}|j|jk7r tdtj|dk\s td|"d|cxkrdkstdtd|j|dz|dzzk\s td||||fS) Nz%x, y, and z should have a same lengthz(x, y, z, and w should have a same lengthr6w should be positive?eps should be between (0, 1)rz;The length of x, y and z should be at least (kx+1) * (ky+1))r;r<r@r?r>)r-r.rrrrepss r3_validate_inputzBivariateSpline._validate_inputs **Q-A 1 a1vv)166)DE E*DE E = 1 Avv !KLLVVAH% !788 OcCo#o;< <'6;< <vv"q&R!V,,01 1!QzrONr r )rrrrrrrrrrOr3rrs( D<?|F,rOrc*eZdZdZdZedZdZy)raBivariate spline constructed from the coefficients and knots of another spline. Notes ----- The class is not meant to be instantiated directly from the data to be interpolated or smoothed. As a result, its ``fp`` attribute and ``get_residual`` method are inherited but overridden; ``AttributeError`` is raised when they are accessed. The other inherited attributes can be used as usual. zis unavailable, because _DerivedBivariateSpline instance is not constructed from data that are to be interpolated or smoothed, but derived from the underlying knots and coefficients of another spline objectc2td|j)Nzattribute "fp" AttributeError _invalid_whyrs r3rz_DerivedBivariateSpline.fpCs01B1B0CDEErOc2td|j)Nzmethod "get_residual" rrs r3rz$_DerivedBivariateSpline.get_residualGs78I8I7JKLLrON)rrrrrpropertyrrrrOr3rr0s* L FFMrOrc,eZdZdZddgdzddddfdZy)raI Smooth bivariate spline approximation. Parameters ---------- x, y, z : array_like 1-D sequences of data points (order is not important). w : array_like, optional Positive 1-D sequence of weights, of same length as `x`, `y` and `z`. bbox : array_like, optional Sequence of length 4 specifying the boundary of the rectangular approximation domain. By default, ``bbox=[min(x), max(x), min(y), max(y)]``. kx, ky : ints, optional Degrees of the bivariate spline. Default is 3. s : float, optional Positive smoothing factor defined for estimation condition: ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s`` Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an estimate of the standard deviation of ``z[i]``. eps : float, optional A threshold for determining the effective rank of an over-determined linear system of equations. `eps` should have a value within the open interval ``(0, 1)``, the default is 1e-16. See Also -------- BivariateSpline : a base class for bivariate splines. UnivariateSpline : a smooth univariate spline to fit a given set of data points. LSQBivariateSpline : a bivariate spline using weighted least-squares fitting RectSphereBivariateSpline : a bivariate spline over a rectangular mesh on a sphere SmoothSphereBivariateSpline : a smoothing bivariate spline in spherical coordinates LSQSphereBivariateSpline : a bivariate spline in spherical coordinates using weighted least-squares fitting RectBivariateSpline : a bivariate spline over a rectangular mesh bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives Notes ----- The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``. 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 interpolating. This routine constructs spline knot vectors automatically via the FITPACK algorithm. The spline knots may be placed away from the data points. For some data sets, this routine may fail to construct an interpolating spline, even if one is requested via ``s=0`` parameter. In such situations, it is recommended to use `bisplrep` / `bisplev` directly instead of this routine and, if needed, increase the values of ``nxest`` and ``nyest`` parameters of `bisplrep`. For linear interpolation, prefer `LinearNDInterpolator`. See ``https://gist.github.com/ev-br/8544371b40f414b7eaf3fe6217209bff`` for discussion. Nrr缉ؗҜrr?r@rAr&r' regrid_smthrrZrrKr)r,r-r.rr/rrr"maxitr r!rrrrrrrMrr^msgs r3r4zRectBivariateSpline.__init__Ms1XuQxtd1 JJqMvvd1gm$<= =vvd1gm$<= =vv#-. .vv#-. .zzT!89 9 =c34 4 !HBB  R)1)=)=aAr2r<>B5*R &BBAr3 R k !"&&sd3%L9CS/ !cr7BsGQ'Eb1b1(E%FF2v  R Rs !(F,,F5rrrOr3r r s 8t'+VaZA!qrOr a ERROR. On entry, the input data are controlled on validity. The following restrictions must be satisfied: -1<=iopt<=1, m>=2, ntest>=8 ,npest >=8, 00, i=1,...,m lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m kwrk >= m+(ntest-7)*(npest-7) if iopt=-1: 8<=nt<=ntest , 9<=np<=npest 0=0: s>=0 if one of these conditions is found to be violated,control is immediately repassed to the calling program. in that case there is no approximation returned.ra WARNING. The coefficients of the spline returned have been computed as the minimal norm least-squares solution of a (numerically) rank deficient system (deficiency=%i, rank=%i). Especially if the rank deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large, the results may be inaccurate. They could also seriously depend on the value of eps.rc eZdZdZddZddZy)SphereBivariateSplineau Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a given set of data points (theta,phi,r). .. versionadded:: 0.11.0 See Also -------- bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives UnivariateSpline : a smooth univariate spline to fit a given set of data points. SmoothBivariateSpline : a smoothing bivariate spline through the given points LSQUnivariateSpline : a univariate spline using weighted least-squares fitting c(tj|}tj|}|jdkDr?|jdks!|j tj kDr t dtj||||||S)al Evaluate the spline or its derivatives at given positions. Parameters ---------- theta, phi : array_like Input coordinates. If `grid` is False, evaluate the spline at points ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting is obeyed. If `grid` is True: evaluate spline at the grid points defined by the coordinate arrays theta, phi. The arrays must be sorted to increasing order. The ordering of axes is consistent with ``np.meshgrid(..., indexing="ij")`` and inconsistent with the default ordering ``np.meshgrid(..., indexing="xy")``. dtheta : int, optional Order of theta-derivative .. versionadded:: 0.14.0 dphi : int Order of phi-derivative .. versionadded:: 0.14.0 grid : bool Whether to evaluate the results on a grid spanned by the input arrays, or at points specified by the input arrays. .. versionadded:: 0.14.0 Examples -------- Suppose that we want to use splines to interpolate a bivariate function on a sphere. The value of the function is known on a grid of longitudes and colatitudes. >>> import numpy as np >>> from scipy.interpolate import RectSphereBivariateSpline >>> def f(theta, phi): ... return np.sin(theta) * np.cos(phi) We evaluate the function on the grid. Note that the default indexing="xy" of meshgrid would result in an unexpected (transposed) result after interpolation. >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") >>> zdata = f(thetagrid, phigrid) We next set up the interpolator and use it to evaluate the function on a finer grid. >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) >>> thetaarr_fine = np.linspace(0, np.pi, 200) >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200) >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine) Finally we plot the coarsly-sampled input data alongside the finely-sampled interpolated data to check that they agree. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(1, 2, 1) >>> ax2 = fig.add_subplot(1, 2, 2) >>> ax1.imshow(zdata) >>> ax2.imshow(zdata_fine) >>> plt.show() r r6zrequested theta out of bounds.r) r;r<r@minrpir?rrzr,thetaphidthetadphirs r3rzzSphereBivariateSpline.__call__s|R 5!jjo ::>uyy{R/599;3F=> >#,,T5#064d-L LrOc.|j||||dS)a Evaluate the spline at points Returns the interpolated value at ``(theta[i], phi[i]), i=0,...,len(theta)-1``. Parameters ---------- theta, phi : array_like Input coordinates. Standard Numpy broadcasting is obeyed. The ordering of axes is consistent with np.meshgrid(..., indexing="ij") and inconsistent with the default ordering np.meshgrid(..., indexing="xy"). dtheta : int, optional Order of theta-derivative .. versionadded:: 0.14.0 dphi : int, optional Order of phi-derivative .. versionadded:: 0.14.0 Examples -------- Suppose that we want to use splines to interpolate a bivariate function on a sphere. The value of the function is known on a grid of longitudes and colatitudes. >>> import numpy as np >>> from scipy.interpolate import RectSphereBivariateSpline >>> def f(theta, phi): ... return np.sin(theta) * np.cos(phi) We evaluate the function on the grid. Note that the default indexing="xy" of meshgrid would result in an unexpected (transposed) result after interpolation. >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") >>> zdata = f(thetagrid, phigrid) We next set up the interpolator and use it to evaluate the function at points not on the original grid. >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200) >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200) >>> zinterp = rsbs.ev(thetainterp, phiinterp) Finally we plot the original data for a diagonal slice through the initial grid, and the spline approximation along the same slice. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(1, 1, 1) >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or") >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b") >>> plt.show() Fr rrr)r,r r r rs r3rzSphereBivariateSpline.evsz}}UCT}NNrONrr)rrrrrzrrrOr3rrs(PLd=OrOrc eZdZdZddZddZy)r a Smooth bivariate spline approximation in spherical coordinates. .. versionadded:: 0.11.0 Parameters ---------- theta, phi, r : array_like 1-D sequences of data points (order is not important). Coordinates must be given in radians. Theta must lie within the interval ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``. w : array_like, optional Positive 1-D sequence of weights. s : float, optional Positive smoothing factor defined for estimation condition: ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s`` Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an estimate of the standard deviation of ``r[i]``. eps : float, optional A threshold for determining the effective rank of an over-determined linear system of equations. `eps` should have a value within the open interval ``(0, 1)``, the default is 1e-16. See Also -------- BivariateSpline : a base class for bivariate splines. UnivariateSpline : a smooth univariate spline to fit a given set of data points. SmoothBivariateSpline : a smoothing bivariate spline through the given points LSQBivariateSpline : a bivariate spline using weighted least-squares fitting RectSphereBivariateSpline : a bivariate spline over a rectangular mesh on a sphere LSQSphereBivariateSpline : a bivariate spline in spherical coordinates using weighted least-squares fitting RectBivariateSpline : a bivariate spline over a rectangular mesh. bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives Notes ----- For more information, see the FITPACK_ site about this function. .. _FITPACK: http://www.netlib.org/dierckx/sphere.f Examples -------- Suppose we have global data on a coarse grid (the input data does not have to be on a grid): >>> import numpy as np >>> theta = np.linspace(0., np.pi, 7) >>> phi = np.linspace(0., 2*np.pi, 9) >>> data = np.empty((theta.shape[0], phi.shape[0])) >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0. >>> data[1:-1,1], data[1:-1,-1] = 1., 1. >>> data[1,1:-1], data[-2,1:-1] = 1., 1. >>> data[2:-2,2], data[2:-2,-2] = 2., 2. >>> data[2,2:-2], data[-3,2:-2] = 2., 2. >>> data[3,3:-2] = 3. >>> data = np.roll(data, 4, 1) We need to set up the interpolator object >>> lats, lons = np.meshgrid(theta, phi) >>> from scipy.interpolate import SmoothSphereBivariateSpline >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(), ... data.T.ravel(), s=3.5) As a first test, we'll see what the algorithm returns when run on the input coordinates >>> data_orig = lut(theta, phi) Finally we interpolate the data to a finer grid >>> fine_lats = np.linspace(0., np.pi, 70) >>> fine_lons = np.linspace(0., 2 * np.pi, 90) >>> data_smth = lut(fine_lats, fine_lons) >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(131) >>> ax1.imshow(data, interpolation='nearest') >>> ax2 = fig.add_subplot(132) >>> ax2.imshow(data_orig, interpolation='nearest') >>> ax3 = fig.add_subplot(133) >>> ax3.imshow(data_smth, interpolation='nearest') >>> plt.show() Nc rtj|tj|tj|}}}d|kjr!|tjkjs t dd|kjr$|dtjzkjs t d|3tj|}|dk\js t d|dk\s t dd|cxkrdkst dt dt 5t j|||||| \}}} } } } } ddd d vr$tj| d | }t | |_ d d  d|d z | d z zf|_ d |_ y#1swY\xYw)Nr6theta should be between [0, pi]@phi should be between [0, 2pi]rs should be positiverr)rr"rrrUrrr) r;r<r>r r?r&r' spherfit_smth_spherefit_messagesrZrrKr)r,r r rrr"rnt_tt_np_tp_rMrr^r_s r3r4z$SmoothSphereBivariateSpline.__init__s 5)2::c?BJJqMAs""$%255.)=)=)?>? ?  "sRUU{(:'?'?'A=> > = 1 AH>># !788Cx34 4S3;< <;< <  M-5-C-CE3DEaHK.M *Cc32s M k !)--cT#<@GW% %t9c$3i+AS1Wq,A)BB  M Ms .$F--F6c.tj|}tj|}|jdkDrB|jdks$|j dtj zkDr t dtj||||||SNr r6rzrequested phi out of bounds.r r;r<r@rrr r?rrzr s r3rzz$SmoothSphereBivariateSpline.__call__| 5!jjo 88a>> from scipy.interpolate import LSQSphereBivariateSpline >>> import numpy as np >>> import matplotlib.pyplot as plt >>> theta = np.linspace(0, np.pi, num=7) >>> phi = np.linspace(0, 2*np.pi, num=9) >>> data = np.empty((theta.shape[0], phi.shape[0])) >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0. >>> data[1:-1,1], data[1:-1,-1] = 1., 1. >>> data[1,1:-1], data[-2,1:-1] = 1., 1. >>> data[2:-2,2], data[2:-2,-2] = 2., 2. >>> data[2,2:-2], data[-3,2:-2] = 2., 2. >>> data[3,3:-2] = 3. >>> data = np.roll(data, 4, 1) We need to set up the interpolator object. Here, we must also specify the coordinates of the knots to use. >>> lats, lons = np.meshgrid(theta, phi) >>> knotst, knotsp = theta.copy(), phi.copy() >>> knotst[0] += .0001 >>> knotst[-1] -= .0001 >>> knotsp[0] += .0001 >>> knotsp[-1] -= .0001 >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), ... data.T.ravel(), knotst, knotsp) As a first test, we'll see what the algorithm returns when run on the input coordinates >>> data_orig = lut(theta, phi) Finally we interpolate the data to a finer grid >>> fine_lats = np.linspace(0., np.pi, 70) >>> fine_lons = np.linspace(0., 2*np.pi, 90) >>> data_lsq = lut(fine_lats, fine_lons) >>> fig = plt.figure() >>> ax1 = fig.add_subplot(131) >>> ax1.imshow(data, interpolation='nearest') >>> ax2 = fig.add_subplot(132) >>> ax2.imshow(data_orig, interpolation='nearest') >>> ax3 = fig.add_subplot(133) >>> ax3.imshow(data_lsq, interpolation='nearest') >>> plt.show() Nc jtj|tj|tj|}}}tj|tj|}}d|kjr!|tjkjs t dd|kjr$|dtjzkjs t dd|kjr!|tjkjs t dd|kjr$|dtjzkjs t d|3tj|}|dk\js t dd|cxkrdkst d t d d t |zd t |z} }t |ftt | ft} } ||c| d d | d d tjd tjzc| d d| d dt5tj|||| | ||\} } } } }ddddkDr$tj|d|}t | |_ | |  f|_d|_y#1swYKxYw)Nr6rrrztt should be between (0, pi)ztp should be between (0, 2pi)rrrrRrr)rrr rUr)r;r<r>r r?rIrrr&r' spherfit_lsqrrZrrKr)r,r r rtttprrrrrrrMrr^r_s r3r4z!LSQSphereBivariateSpline.__init__'sS 5)2::c?BJJqMAsBBB""$%255.)=)=)?>? ?  "qw';';'==> >r b255j%5%5%7;< <r b1RUU7l%7%7%9<= = = 1 AH>># !788S3;< <;< <s2w;CG S#'vu)=S!2Ab 3q9UUBJBC#bc(  F#+#8#8QS:;$F CaS F 7)--cT#<@GW% %Q;  F Fs <#J))J2c.tj|}tj|}|jdkDrB|jdks$|j dtj zkDr t dtj||||||Sr r!r s r3rzz!LSQSphereBivariateSpline.__call__Jr"rO)Nrrr#rrOr3rrsiV!F DrOra ERROR: on entry, the input data are controlled on validity the following restrictions must be satisfied. -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1, -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0. -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0. mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8, kwrk>=5+mu+mv+nuest+nvest, lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest) 0< u(i-1)=0: s>=0 if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7 if one of these conditions is found to be violated,control is immediately repassed to the calling program. in that case there is no approximation returned.c$eZdZdZ ddZddZy)r a} Bivariate spline approximation over a rectangular mesh on a sphere. Can be used for smoothing data. .. versionadded:: 0.11.0 Parameters ---------- u : array_like 1-D array of colatitude coordinates in strictly ascending order. Coordinates must be given in radians and lie within the open interval ``(0, pi)``. v : array_like 1-D array of longitude coordinates in strictly ascending order. Coordinates must be given in radians. First element (``v[0]``) must lie within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy ``v[-1] <= v[0] + 2*pi``. r : array_like 2-D array of data with shape ``(u.size, v.size)``. s : float, optional Positive smoothing factor defined for estimation condition (``s=0`` is for interpolation). pole_continuity : bool or (bool, bool), optional Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and ``u=pi`` (``pole_continuity[1]``). The order of continuity at the pole will be 1 or 0 when this is True or False, respectively. Defaults to False. pole_values : float or (float, float), optional Data values at the poles ``u=0`` and ``u=pi``. Either the whole parameter or each individual element can be None. Defaults to None. pole_exact : bool or (bool, bool), optional Data value exactness at the poles ``u=0`` and ``u=pi``. If True, the value is considered to be the right function value, and it will be fitted exactly. If False, the value will be considered to be a data value just like the other data values. Defaults to False. pole_flat : bool or (bool, bool), optional For the poles at ``u=0`` and ``u=pi``, specify whether or not the approximation has vanishing derivatives. Defaults to False. See Also -------- BivariateSpline : a base class for bivariate splines. UnivariateSpline : a smooth univariate spline to fit a given set of data points. SmoothBivariateSpline : a smoothing bivariate spline through the given points LSQBivariateSpline : a bivariate spline using weighted least-squares fitting SmoothSphereBivariateSpline : a smoothing bivariate spline in spherical coordinates LSQSphereBivariateSpline : a bivariate spline in spherical coordinates using weighted least-squares fitting RectBivariateSpline : a bivariate spline over a rectangular mesh. bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives Notes ----- Currently, only the smoothing spline approximation (``iopt[0] = 0`` and ``iopt[0] = 1`` in the FITPACK routine) is supported. The exact least-squares spline approximation is not implemented yet. When actually performing the interpolation, the requested `v` values must lie within the same length 2pi interval that the original `v` values were chosen from. For more information, see the FITPACK_ site about this function. .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f Examples -------- Suppose we have global data on a coarse grid >>> import numpy as np >>> lats = np.linspace(10, 170, 9) * np.pi / 180. >>> lons = np.linspace(0, 350, 18) * np.pi / 180. >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, ... np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T We want to interpolate it to a global one-degree grid >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180 >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180 >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons) We need to set up the interpolator object >>> from scipy.interpolate import RectSphereBivariateSpline >>> lut = RectSphereBivariateSpline(lats, lons, data) Finally we interpolate the data. The `RectSphereBivariateSpline` object only takes 1-D arrays as input, therefore we need to do some reshaping. >>> data_interp = lut.ev(new_lats.ravel(), ... new_lons.ravel()).reshape((360, 180)).T Looking at the original and the interpolated data, one can see that the interpolant reproduces the original data very well: >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(211) >>> ax1.imshow(data, interpolation='nearest') >>> ax2 = fig.add_subplot(212) >>> ax2.imshow(data_interp, interpolation='nearest') >>> plt.show() Choosing the optimal value of ``s`` can be a delicate task. Recommended values for ``s`` depend on the accuracy of the data values. If the user has an idea of the statistical errors on the data, she can also find a proper estimate for ``s``. By assuming that, if she specifies the right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly reproduces the function underlying the data, she can evaluate ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``. For example, if she knows that the statistical errors on her ``r(i,j)``-values are not greater than 0.1, she may expect that a good ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``. If nothing is known about the statistical error in ``r(i,j)``, ``s`` must be determined by trial and error. The best is then to start with a very large value of ``s`` (to determine the least-squares polynomial and the corresponding upper bound ``fp0`` for ``s``) and then to progressively decrease the value of ``s`` (say by a factor 10 in the beginning, i.e. ``s = fp0 / 10, fp0 / 100, ...`` and more carefully as the approximation shows more detail) to obtain closer fits. The interpolation results for different values of ``s`` give some insight into this process: >>> fig2 = plt.figure() >>> s = [3e9, 2e9, 1e9, 1e8] >>> for idx, sval in enumerate(s, 1): ... lut = RectSphereBivariateSpline(lats, lons, data, s=sval) ... data_interp = lut.ev(new_lats.ravel(), ... new_lons.ravel()).reshape((360, 180)).T ... ax = fig2.add_subplot(2, 2, idx) ... ax.imshow(data_interp, interpolation='nearest') ... ax.set_title(f"s = {sval:g}") >>> plt.show() Nc $tjgdt} tjgdt} |d}n6t|ttj ztj zr||f}t|tr||f}t|tr||f}t|tr||f}|\} } || dd| d| d<n|d| d<| d| d<n|d| d<|\| d<| d <tj|tj|}}tj|}d |dkr|dtjks td tj |dcxkrtjkstd td |d|ddtjzzks td tjtj|d kDs tdtjtj|d kDs td|j|jdk(s td|j|jdk(s td|ddur|ddur td|ddur|ddur td|d k\s tdtj|}t 5t#j$| | |j'|j'|j'| | |\} }}}}}}ddddvr$t(j+|d|}t||_d dd| dz |dz zf|_d|_|d|_y#1swYfxYw)N)r r r r)r#r r#r )NNrr#r rrr6zu should be between (0, pi)z v[0] should be between [-pi, pi)z#v[-1] should be v[0] + 2pi or less zu must be strictly increasingzv must be strictly increasingz7u dimension of r must have same number of elements as uz7v dimension of r must have same number of elements as vFTz1if pole_continuity is False, so must be pole_flatrrrUrr)r;r dfitpack_int isinstancerfloat32float64boolrr<r r?r>rr@rAr&r'regrid_smth_sphercopy_spfit_messagesrZrrKrv0)r,uvrr"pole_continuity pole_values pole_exact pole_flatioptiderr0r1rytunvtvrMrr^rs r3r4z"RectSphereBivariateSpline.__init__ szxx 6xxl;  &K  URZZ%7"**%D E& 4K ot ,.@O j$ '$j1J i &"I.IB"QR :DG mDG :DG mDG$Qaxx{BHHQK1 JJqMad quruu}:; ;v1%%?@ @&?@ @u!qw&BC Cvvbggaj3&'<= =vvbggaj3&'<= =vv#-. .vv#-. . 1  &9Q<4+?)* * 1  &9Q<4+?)* *Cx34 4 HHQK  O)1)C)CD$DEFFHDEFFHDEFFHDFA *O &BBAr3 O k !!%%cT#<8CS/ !cr7BsGQ'9aBqD(9%:: A$ O Os ANNctj|}tj|}tj||||||S)Nr)r;r<rrzr s r3rzz"RectSphereBivariateSpline.__call__W sD 5!jjo$--dE3v37d.D DrO)r6FNFFrr#rrOr3r r ss SjJN-2L\DrOr ))r__all__r[ threadingr numpyrrrrrr;rrr'typesintvarrr-r&rYrBrrrrrrrrrrr r3rrr rr4r rrOr3rJs !88#~~$$** v J J &':a# F 9F 9Rh#3hV O*OhWEWEt I =   -CG(VH*HVM2M6`O`FaaHY/Yx'++- 8BBdO0dONKD"7KD\XD4XDv#'')"8jD 5jDrO