
    (ph^             	       b   S r / SQrSSKrSSKJr  SSKJrJrJrJ	r	J
r
  SSKrSSKJr  SSKJr  \R                   R"                  R$                  r\" 5       rS	S
SSS.rSSSSSSSSS.r " S S5      r " S S\5      rSr " S S\5      r " S S5      rSSSSSSS S!.r " S" S#\5      r " S$ S%\5      r " S& S'\5      r " S( S)\5      r  " S* S+\5      r!\RE                  5       r#S,\#S-'   S.\#S/'    " S0 S1\5      r$ " S2 S3\$5      r% " S4 S5\$5      r&\RE                  5       r'S6\'S-'    " S7 S8\$5      r(g)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.
)
UnivariateSplineInterpolatedUnivariateSplineLSQUnivariateSplineBivariateSplineLSQBivariateSplineSmoothBivariateSplineLSQSphereBivariateSplineSmoothSphereBivariateSplineRectBivariateSplineRectSphereBivariateSpline    N)Lock)zerosconcatenateraveldiffarray   )_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]<x[1]<...<x[m-1]<=xe, w[i]>0, i=0..m-1
if iopt=-1:
  xb<t[k+1]<t[k+2]<...<t[n-k-2]<xe)r         
   r   r   )r   extrapolater   r   r   raiser   constc                       \ rS rSrSrSS/S-  SSSS4S jr\S	 5       r\SS
 j5       r	S r
S rSS jrS rSS jrS rS rS rS rS rS rSS jrSS jrSrg)r   I   a)  
1-D smoothing spline fit to a given set of data points.

.. legacy:: class

    Specifically, we recommend using `make_splrep` instead.

Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.  `s`
specifies the number of knots by specifying a smoothing condition.

Parameters
----------
x : (N,) array_like
    1-D array of independent input data. Must be increasing;
    must be strictly increasing if `s` is 0.
y : (N,) array_like
    1-D array of dependent input data, of the same length as `x`.
w : (N,) array_like, optional
    Weights for spline fitting.  Must be positive.  If `w` is None,
    weights are all 1. Default is None.
bbox : (2,) array_like, optional
    2-sequence specifying the boundary of the approximation interval. If
    `bbox` is None, ``bbox=[x[0], x[-1]]``. Default is None.
k : int, optional
    Degree of the smoothing spline.  Must be 1 <= `k` <= 5.
    ``k = 3`` is a cubic spline. Default is 3.
s : float or None, optional
    Positive smoothing factor used to choose the number of knots.  Number
    of knots will be increased until the smoothing condition is satisfied::

        sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) <= s

    However, because of numerical issues, the actual condition is::

        abs(sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) - s) < 0.001 * s

    If `s` is None, `s` will be set as `len(w)` for a smoothing spline
    that uses all data points.
    If 0, spline will interpolate through all data points. This is
    equivalent to `InterpolatedUnivariateSpline`.
    Default is None.
    The user can use the `s` to control the tradeoff between closeness
    and smoothness of fit. Larger `s` means more smoothing while smaller
    values of `s` indicate less smoothing.
    Recommended values of `s` depend on the weights, `w`. If the weights
    represent the inverse of the standard-deviation of `y`, then a good
    `s` value should be found in the range (m-sqrt(2*m),m+sqrt(2*m))
    where m is the number of datapoints in `x`, `y`, and `w`. This means
    ``s = len(w)`` should be a good value if ``1/w[i]`` is an
    estimate of the standard deviation of ``y[i]``.
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 or 'const', return the boundary value.

    Default 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
--------
BivariateSpline :
    a base class for bivariate splines.
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
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
InterpolatedUnivariateSpline :
    a interpolating univariate spline for a given set of data points.
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
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`.

**NaN handling**: If the input arrays contain ``nan`` values, the result
is not useful, since the underlying spline fitting routines cannot deal
with ``nan``. A workaround is to use zero weights for not-a-number
data points:

>>> 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()

Nr   r   r   Fc	                    U R                  XX4XVUU5      u  pp4U l        [           [        R                  " XXSUS   US   US9n	S S S 5        W	S   S:X  a  U R                  U	5      n	Xl        U R                  5         g ! , (       d  f       N?= f)Nr   r   wxbxes)validate_inputextFITPACK_LOCKdfitpackfpcurf0_reset_nest_data_reset_class)
selfxyr    bboxkr#   r&   check_finitedatas
             N/var/www/html/venv/lib/python3.13/site-packages/scipy/interpolate/_fitpack2.py__init__UnivariateSpline.__init__   s     #'"5"5aAQ36B#Datx ##A!T!W'+Aw!5D  8q=##D)D
 \s   A==
Bc                 n   [         R                  " U 5      [         R                  " U5      [         R                  " U5      p1n Ub  [         R                  " U5      nU(       a  Ub$  [         R                  " U5      R                  5       OSn[         R                  " U 5      R                  5       (       a0  [         R                  " U5      R                  5       (       a  U(       d  [	        S5      eUb  US:  a3  [         R                  " [        U 5      S:  5      (       d  [	        S5      eO2[         R                  " [        U 5      S:  5      (       d  [	        S5      eU R                  UR                  :w  a  [	        S5      eUb8  U R                  UR                  s=:X  a  UR                  :X  d  O  [	        S5      eUR                  S	:w  a  [	        S
5      eSUs=::  a  S::  d  O  [	        S5      eUb  US:  d  [	        S5      e [        U   nXX#U4$ ! [         a  n	[	        SU S35      U	eS n	A	ff = f)NTz,x and y array must not contain NaNs or infs.r           zx 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)r   zbbox shape should be (2,)r      zk should be 1 <= k <= 5s should be s >= 0.0Unknown extrapolation mode .)
npasarrayisfiniteall
ValueErrorr   sizeshape_extrap_modesKeyError)
r.   r/   r    r0   r1   r#   r&   r2   w_finitees
             r4   r%   UnivariateSpline.validate_input   s   ZZ]BJJqM2::d3Cd=

1A/0}r{{1~))+$HKKN&&((A0B0B0D0D   "1 2 29A66$q'S.)) !@AA * 66$q'C-(( !IJJ66QVV@AA]166QVV#=qvv#=DEEZZ4899q+A+677]18344	J$C Qc!!  	J:3%qABI	Js   	H 
H4H//H4c                     U R                  U 5      nUu  pEnXl        SSSSSUS[        U5      UUSSSS4Ul        X#l        U$ )z(Construct a spline object from given tckN)__new__
_eval_argslenr+   r&   )clstckr&   r-   tcr1   s          r4   	_from_tckUnivariateSpline._from_tck  sU     {{3aD$dAtSVQtT41
    c                    U R                   nUS   US   US   US   US   4u  p#pEnUS U US U U4U l        US:X  a  g US:X  a  U R                  [        5        g US:X  a  U R                  [        5        g US:X  a  U R                  [        5        [
        R                  US	U 35      n[        R                  " US
S9  g )N      	   r9   r$   r   r   ier=r   
stacklevel)	r+   rK   
_set_classr   r   _curfit_messagesgetwarningswarn)r-   r3   nrO   rP   r1   iermessages           r4   r,   UnivariateSpline._reset_class*  s    zzq'47DGT!Wd2hFaCBQ%2A/!8 BYOO89BY OO/0 ax 34&**3$se=GMM'a0rS   c                 \    Xl         U R                  [        [        [        4;   a  Xl        g g N)_spline_class	__class__r   r   r   )r-   rM   s     r4   r\   UnivariateSpline._set_classB  s,     >>.0L13 3 N rS   c                   ^^ TS   nTc  TS   [        TS   5      pTXT-   S-   mOUT::  d  [        S5      eUU4S jS 5       u  pgpTS S XgX8U	TS	   4-   n
[           [        R                  " U
6 mS S S 5        T$ ! , (       d  f       T$ = f)
Nr   r9   r   r   z`nest` can only be increasedc              3   X   >#    U  H  n[         R                  " TU   T5      v   M!     g 7frf   )r=   resize).0jr3   nests     r4   	<genexpr>/UnivariateSpline._reset_nest.<locals>.<genexpr>S  s*      /- =>ryya$77-s   '*)rV   rW         rV      )rL   rA   r'   r(   fpcurf1)r-   r3   ro   ra   r1   mrO   rP   fpintnrdataargss    ``        r4   r*   UnivariateSpline._reset_nestK  s    H<7CQLq3q5D9 !?@@/-/e BQx1648<<##T*D  \s   A99
Bc                 >   U R                   nUS   S:X  a  [        R                  " SSS9  gUSS U4-   USS -   n[           [        R
                  " U6 nSSS5        US   S:X  a  U R                  U5      nX l         U R                  5         g! , (       d  f       N?= f)	zContinue 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 knotsr   rZ   NrU   r   )r+   r_   r`   r'   r(   ru   r*   r,   )r-   r#   r3   ry   s       r4   set_smoothing_factor%UnivariateSpline.set_smoothing_factor[  s     zz7b=MM 8%&( BQx1$ab)##T*D 8q=##D)D
 \s   B
Bc                 \   [         R                  " U5      nUR                  S:X  a  [        / 5      $ Uc  U R                  nO
 [
        U   n[           [        R                  " XR                  X#S9sSSS5        $ ! [         a  n[        SU S35      UeSnAff = f! , (       d  f       g= f)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   Nr;   r<   )derr&   )r=   r>   rB   r   r&   rD   rE   rA   r'   r   splevrK   )r-   r.   nur&   rG   s        r4   __call__UnivariateSpline.__call__q  s    2 JJqM66Q;9;((CN#C(  &&q//rK \  N #>se1!EFAMN\s$   	A; B;
BBB
B+c                 @    U R                   nUS   US   p2US   X#U-
   $ )z{Return positions of interior knots of the spline.

Internally, the knot vector contains ``2*k`` additional boundary knots.
r9   rU   rV   r+   r-   r3   r1   ra   s       r4   	get_knotsUnivariateSpline.get_knots  s.    
 zzAwQ1Awq1~rS   c                 F    U R                   nUS   US   p2US   SX2-
  S-
   $ )Return spline coefficients.r9   rU   rW   Nr   r   r   s       r4   
get_coeffsUnivariateSpline.get_coeffs  s0    zzAwQ1AwvArS   c                      U R                   S   $ )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)

r   r   r-   s    r4   get_residualUnivariateSpline.get_residual  s     zz"~rS   c                     [            [        R                  " XU R                  5      sSSS5        $ ! , (       d  f       g= f)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'   r   splintrK   )r-   abs      r4   integralUnivariateSpline.integral  s&    J  ''doo> \\s	   !2
A c                     [            [        R                  " XR                  5      sSSS5        $ ! , (       d  f       g= f)a  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'   r   spalderK   )r-   r.   s     r4   derivativesUnivariateSpline.derivatives  s#    0  ''??; \\s    1
?c                    U R                   S   nUS:X  aO  U R                  S   nS[        U5      S-
  -  n[           [        R
                  " U R                  US9sSSS5        $ [        S5      e! , (       d  f       N= f)a?  Return the zeros of the spline.

Notes
-----
Restriction: only cubic splines are supported by FITPACK. For non-cubic
splines, use `PPoly.root` (see below for an example).

Examples
--------

For some data, this method may miss a root. This happens when one of
the spline knots (which FITPACK places automatically) happens to
coincide with the true root. A workaround is to convert to `PPoly`,
which uses a different root-finding algorithm.

For example,

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

r9   r   r   rU   )mestNz/finding roots unsupported for non-cubic splines)r+   rK   rL   r'   r   sprootNotImplementedError)r-   r1   rO   r   s       r4   rootsUnivariateSpline.roots  sq    R JJqM6"AA
#D$++DOO$G ! #6 7 	7 s   A00
A>c                     [            [        R                  " U R                  U5      nSSS5        U R                  S:X  a  SOU R                  n[
        R                  WUS9$ ! , (       d  f       N@= f)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)`.

Nr   r   )r&   )r'   r   splderrK   r&   r   rQ   )r-   ra   rN   r&   s       r4   
derivativeUnivariateSpline.derivative&  sX    Z &&t:C  88q=adhh))#3)77	 \s   "A##
A1c                     [            [        R                  " U R                  U5      nSSS5        [        R                  WU R                  5      $ ! , (       d  f       N.= f)ap  
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   
splantiderrK   r   rQ   r&   )r-   ra   rN   s      r4   antiderivativeUnivariateSpline.antiderivativeY  sB    h **4??A>C ))#txx88 \s   "A
A)rh   r+   rK   rg   r&   )r   rf   )r   N)r   )__name__
__module____qualname____firstlineno____doc__r5   staticmethodr%   classmethodrQ   r,   r\   r*   r}   r   r   r   r   r   r   r   r   r   __static_attributes__ rS   r4   r   r   I   s    _B  $4&(a4U   "  "D 	 	10 ,%LN&?P<607d18f69rS   r   c                   4    \ rS rSrSrSS/S-  SSS4S jrS	rg)
r   i  a  
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

Nr   r   r   Fc                 J   U R                  XX4US Xg5      u  pp4U l        [        R                  " [	        U5      S:  5      (       d  [        S5      e[           [        R                  " XXSUS   US   SS9U l	        S S S 5        U R                  5         g ! , (       d  f       N= f)Nr8   x must be strictly increasingr   r   r   )r%   r&   r=   r@   r   rA   r'   r(   r)   r+   r,   )r-   r.   r/   r    r0   r1   r&   r2   s           r4   r5   %InterpolatedUnivariateSpline.__init__  s     #'"5"5aAQ,/#?atxvvd1gm$$<== !))!47-1!W;DJ  	 \s   $B
B"r+   r&   r   r   r   r   r   r5   r   r   rS   r4   r   r     s"    Yv  $4&(aUrS   r   a  The 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                   4    \ rS rSrSrSS/S-  SSS4S jrS	rg)
r   i  a  
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.])

Nr   r   r   Fc	                    U R                  XXEUS Xx5      u  ppEU l        [        R                  " [	        U5      S:  5      (       d  [        S5      eUS   n	US   n
U	c  US   n	U
c  US   n
[        U	/US-   -  X:/US-   -  45      n[        U5      n[        R                  " X6S-   X-
   X6X-
  S-
   -
  S:  SS9(       d  [        S5      e[           [        R                  " XU5      S:X  d  [        [        5      e[        R                  " XXcXIU
S9nS S S 5        WS S	 S S US   4-   U l        U R                  5         g ! , (       d  f       N2= f)
Nr8   zx must be increasingr   r   r$   )axisz;Interior knots t must satisfy Schoenberg-Whitney conditions)r    r!   r"   )r%   r&   r=   r@   r   rA   r   rL   r'   r(   fpchec_fpchec_error_stringfpcurfm1r+   r,   )r-   r.   r/   rO   r    r0   r1   r&   r2   r!   r"   ra   r3   s                r4   r5   LSQUnivariateSpline.__init__  sV    #'"5"5aAQ69#Iatxvvd1gn%%344 !W!W:1B:2B"qsQac
34Fvva!ACjQSU+a/a8 = > >??1+q0 !566$$Q11CD  #2Y$d2h!77
 \s   AD>>
Er   r   r   rS   r4   r   r     s"    sj #'dVAXUrS   r   c                   J    \ rS rSrSr\S 5       rS rS rS r	SS jr
S rS	rg
)_BivariateSplineBasei  a  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                     U R                  U 5      n[        U5      S:w  a  [        S5      eUSS Ul        USS Ul        U$ )z3Construct a spline object from given tck and degreer9   z4tck should be a 5 element tuple of tx, ty, c, kx, kyNr   )rJ   rL   rA   rN   degrees)rM   rN   r-   s      r4   rQ   _BivariateSplineBase._from_tck  sN     {{3s8q= . / /r712wrS   c                     U R                   $ )zqReturn weighted sum of squared residuals of the spline
approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)
)fpr   s    r4   r   !_BivariateSplineBase.get_residual  s     wwrS   c                      U R                   SS $ )zReturn 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.
Nr   rN   r   s    r4   r   _BivariateSplineBase.get_knots  s     xx|rS   c                      U R                   S   $ )r   r   r   r   s    r4   r   _BivariateSplineBase.get_coeffs  s    xx{rS   c                    [         R                  " U5      n[         R                  " U5      nU R                  SS u  pgnU R                  u  pU(       Ga  UR                  S:X  d  UR                  S:X  aB  [         R
                  " UR                  UR                  4U R                  S   R                  S9$ UR                  S:  a=  [         R                  " [         R                  " U5      S:  5      (       d  [        S5      eUR                  S:  a=  [         R                  " [         R                  " U5      S:  5      (       d  [        S5      eU(       d  U(       aB  [           [        R                  " XgXXXAU5	      u  pSSS5        WS:X  d  [        S	U 35      e W$ [           [        R                  " XgXXU5      u  pSSS5        WS:X  d  [        S
U 35      e W$ UR                  UR                  :w  a  [         R                  " X5      u  pUR                  nUR!                  5       nUR!                  5       nUR                  S:X  d  UR                  S:X  a+  [         R
                  " XR                  S   R                  S9$ U(       d  U(       a@  [           [        R"                  " XgXXXAU5	      u  pSSS5        WS:X  d  [        SU 35      eO>[           [        R$                  " XgXXU5      u  pSSS5        WS:X  d  [        SU 35      eWR'                  U5      nU$ ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       N= f! , (       d  f       Nj= f)ag  
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()
Nr   r   r   dtyper8   z1x must be strictly increasing when `grid` is Truez1y must be strictly increasing when `grid` is TruezError code returned by parder: zError code returned by bispev: zError code returned by pardeu: zError code returned by bispeu: )r=   r>   rN   r   rB   r   r   r@   r   rA   r'   r(   parderbispevrC   broadcast_arraysr   pardeubispeureshape)r-   r.   r/   dxdygridtxtyrP   kxkyzrb   rC   s                 r4   r   _BivariateSplineBase.__call__  s   P JJqMJJqMHHRaL	vv{affkxx 08I8IJJ!bffRWWQZ3->&?&? !TUU!bffRWWQZ3->&?&? !TUUR!%__RQBB1MFA "ax$'Fse%LMM  > 9 "%__RQB1EFA "ax$'Fse%LMM  4 - ww!''!**10GGE	A	Avv{affkxxXXa[->->??R!%__RQBB1MFA "ax$'Fse%LMM   "%__RQB1EFA "ax$'Fse%LMM		% AC "\
 "\" "\
 "\s0   %L*'L<MM*
L9<
M
M
M-c           
         US:X  a  US:X  a  U $ U R                   u  p4US:  a  US:  d  [        S5      eX:  a  X$:  d  [        S5      eU R                  SS u  pVn[           [        R
                  " XVXsXAU5      u  pSSS5        W	S:w  a  [        SU	-  5      e[        U5      n
[        U5      nXQX-
   nXbX-
   nX1-
  XB-
  pX-
  U-
  S-
  X-
  U-
  S-
  -  n[        R                  XWSU X45      $ ! , (       d  f       N{= f)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 splineNr   z,Unexpected error code returned by pardtc: %dr   )	r   rA   rN   r'   r(   pardtcrL   _DerivedBivariateSplinerQ   )r-   r   r   r   r   r   r   rP   newcrb   nxnynewtxnewtynewkxnewkynewclens                    r4   partial_derivative'_BivariateSplineBase.partial_derivativeH  s1   . 7rQwK\\FB!Ga  ") * *G  "5 6 6!IBA$OOBA22F	 ax  "/14"5 6 6RBRB"'NE"'NE7BG5w|a'BGbL1,<=G*44e6:8Gn6;6D E E s   !C22
D )r   rN   Nr   r   T)r   r   r   r   r   r   rQ   r   r   r   r   r   r   r   rS   r4   r   r     s7       xt0ErS   r   z
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.z
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.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<tx[kx+1]<tx[kx+2]<...<tx[nx-kx-2]<xe
  yb<ty[ky+1]<ty[ky+2]<...<ty[ny-ky-2]<yea  
The coefficients of the spline returned have been computed as the
minimal norm least-squares solution of a (numerically) rank deficient
system (deficiency=%i). If deficiency is large, the results may be
inaccurate. Deficiency may strongly depend on the value of eps.)r   r   r      r9   r   r   c                   8    \ rS rSrSrSS jrS r\S 5       rSr	g)	r   i  a  
Base class for bivariate splines.

This describes a spline ``s(x, y)`` of degrees ``kx`` and ``ky`` on
the rectangle ``[xb, xe] * [yb, ye]`` calculated from a given set
of data points ``(x, y, z)``.

This class is meant to be subclassed, not instantiated directly.
To construct these splines, call either `SmoothBivariateSpline` or
`LSQBivariateSpline` or `RectBivariateSpline`.

See Also
--------
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
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
c                 $    U R                  XX4SS9$ )a  
Evaluate the spline at points

Returns the interpolated value at ``(xi[i], yi[i]),
i=0,...,len(xi)-1``.

Parameters
----------
xi, yi : 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")``.
dx : int, optional
    Order of x-derivative

    .. versionadded:: 0.14.0
dy : int, optional
    Order of y-derivative

    .. 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
>>> 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()
Fr   r   r   r   )r-   xiyir   r   s        r4   evBivariateSpline.ev  s    x }}R}>>rS   c                     U R                   SS u  pVnU R                  u  p[           [        R                  " XVXxXX#U5	      sSSS5        $ ! , (       d  f       g= f)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   )rN   r   r'   r(   dblint)
r-   xar!   yaybr   r   rP   r   r   s
             r4   r   BivariateSpline.integral  sC    " HHRaL	??21"""E \\s   A
Ac                 L   [         R                  " U 5      [         R                  " U5      [         R                  " U5      p!n U R                  UR                  s=:X  a  UR                  :X  d  O  [        S5      eUbd  [         R                  " U5      nU R                  UR                  :w  a  [        S5      e[         R                  " US:  5      (       d  [        S5      eUb  SUs=:  a  S:  d  O  [        S5      eU R                  US-   US-   -  :  d  [        S5      eXX#4$ )	Nz%x, y, and z should have a same lengthz(x, y, z, and w should have a same lengthr8   w should be positive      ?eps should be between (0, 1)r   z;The length of x, y and z should be at least (kx+1) * (ky+1))r=   r>   rB   rA   r@   )r.   r/   r   r    r   r   epss          r4   _validate_inputBivariateSpline._validate_input  s    **Q-A

1avv)166)DEE=

1Avv !KLLVVAH%% !788OcCo#o;<<vv"q&R!V,, 0 1 1QzrS   r   Nr   r   )
r   r   r   r   r   r   r   r   r  r   r   rS   r4   r   r     s(     D<?|F,  rS   r   c                   2    \ rS rSrSrSr\S 5       rS rSr	g)r   i0  a  Bivariate 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 objectc                 2    [        SU R                   35      e)Nzattribute "fp" AttributeError_invalid_whyr   s    r4   r   _DerivedBivariateSpline.fpC  s    01B1B0CDEErS   c                 2    [        SU R                   35      e)Nzmethod "get_residual" r  r   s    r4   r   $_DerivedBivariateSpline.get_residualG  s    78I8I7JKLLrS   r   N)
r   r   r   r   r   r	  propertyr   r   r   r   rS   r4   r   r   0  s*    L F FMrS   r   c                   6    \ rS rSrSrSS/S-  SSSS4S jrSrg)	r   iK  aY
  
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.

Nr   r   缉ؗҜ<c
                 N   U R                  XX4XgU	5      u  pp4[        U5      nUR                  S:X  d  [        S5      eUb  US:  d  [        S5      eUu  pp[           [
        R                  " XX4XXXgXSS9u  pnnnnnnUS:  a"  [
        R                  " XX4XXXgXUS9u  pnnnnnnS S S 5        WS;   a  O.[        R                  US	U 35      n[        R                  " US
S9  WU l        WS W WS W WS X-
  S-
  UU-
  S-
  -   4U l        Xg4U l        g ! , (       d  f       Nt= f)Nr   bbox shape should be (4,)r8   r:   r   )r#   r  lwrk2r   r   r$   rX   rY   r   rZ   )r  r   rC   rA   r'   r(   surfit_smth_surfit_messagesr^   r_   r`   r   rN   r   )r-   r.   r/   r   r    r0   r   r   r#   r  r!   r"   r   yer   r   r   r   rP   r   wrk1rb   rc   s                          r4   r5   SmoothBivariateSpline.__init__  sL    ))!bcB
aT{zzT!899=c344/7/C/CaBBBa0K,BBAr4Rx3;3G3G!!40B2tS	  +&**3$se=GMM'a0cr7BsGQ';q2b57(;%<<v \s   AD
D$r   r   rN   r   r   rS   r4   r   r   K  s$    CJ #'dVaZA!trS   r   c                   4    \ rS rSrSrSS/S-  SSS4S jrSrg)r   i  a^  
Weighted least-squares bivariate spline approximation.

Parameters
----------
x, y, z : array_like
    1-D sequences of data points (order is not important).
tx, ty : array_like
    Strictly ordered 1-D sequences of knots coordinates.
w : array_like, optional
    Positive 1-D array of weights, of the same length as `x`, `y` and `z`.
bbox : (4,) array_like, optional
    Sequence of length 4 specifying the boundary of the rectangular
    approximation domain.  By default,
    ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.
kx, ky : ints, optional
    Degrees of the bivariate spline. Default is 3.
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
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.

Nr   r   c                 L   U R                  XX6XU
5      u  pp6[        U5      nUR                  S:X  d  [        S5      eSU-  S-   [	        U5      -   nSU	-  S-   [	        U5      -   n[        X5      n[        U4[        5      n[        U4[        5      nXNUS-   X-
  S-
  & X_U	S-   X-
  S-
  & Uu  nnnn[           [        R                  " XX;XUUUUUUXU
SS9u  pnnnUS:  a$  [        R                  " XUXXUUUUUXU
US9u  pnnnS S S 5        WS;   a  O_US:  a+  X-
  S-
  X-
  S-
  -  U-   n[        R                  S	5      U-  nO[        R                  US
U 35      n[        R                  " USS9  WU l        US U US U W4U l        X4U l        g ! , (       d  f       N= f)Nr  r  r   r   )r  r   r  rX   r   rY   rZ   )r  r   rC   rA   rL   maxr   floatr'   r(   
surfit_lsqr  r^   r_   r`   r   rN   r   )r-   r.   r/   r   r   r   r    r0   r   r   r  r   r   nmaxtx1ty1r!   r"   r   r  rP   r   rb   
deficiencyrc   s                            r4   r5   LSQBivariateSpline.__init__  s    ))!bcB
aT{zzT!899rT!VCG^rT!VCG^ 2{TGU#TGU#BqDqBqDqBB#+#6#6qQCS45r2r246Cq$J CaS Rx'/':':18:!8:BB8:3(P$!R  +Rx eAga04
*..r2jA*..sd3%LAMM'a0s8S"Xq(v) \s   8AF
F#r  r   r   rS   r4   r   r     s!    4l +/dVAX!*rS   r   c                   2    \ rS rSrSrS/S-  SSS4S jrSrg)	r
   i  as  
Bivariate spline approximation over a rectangular mesh.

Can be used for both smoothing and interpolating data.

Parameters
----------
x,y : array_like
    1-D arrays of coordinates in strictly ascending order.
    Evaluated points outside the data range will be extrapolated.
z : array_like
    2-D array of data with shape (x.size,y.size).
bbox : array_like, optional
    Sequence of length 4 specifying the boundary of the rectangular
    approximation domain, which means the start and end spline knots of
    each dimension are set by these values. 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((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline
    function. Default is ``s=0``, which is for interpolation.

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
SmoothSphereBivariateSpline :
    a smoothing bivariate spline in spherical coordinates
LSQSphereBivariateSpline :
    a bivariate spline in spherical coordinates using weighted
    least-squares fitting
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
-----

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.

Nr   r   r   c                    [        U5      [        U5      [        U5      pBn[        R                  " U5      n[        R                  " [	        U5      S:  5      (       d  [        S5      e[        R                  " [	        U5      S:  5      (       d  [        S5      eUR                  UR                  S   :X  d  [        S5      eUR                  UR                  S   :X  d  [        S5      eUR                  S:X  d  [        S	5      eUb  US:  d  [        S
5      e[        U5      nUu  pp[           [        R                  " XX8XXXg5
      u  ppnnnS S S 5        WS;  a$  [        R                  USU 35      n[        U5      eWU l        WS W WS W WS X-
  S-
  X-
  S-
  -   4U l        XV4U l        g ! , (       d  f       Nh= f)Nr8   r   zy must be strictly increasingr   z7x dimension of z must have same number of elements as xr   z7y dimension of z must have same number of elements as yr  r  r:   r  rY   )r   r=   r>   r@   r   rA   rB   rC   r'   r(   regrid_smthr  r^   r   rN   r   )r-   r.   r/   r   r0   r   r   r#   r!   r"   r   r  r   r   r   r   rP   r   rb   msgs                       r4   r5   RectBivariateSpline.__init__J  s   1XuQxtdJJqMvvd1gm$$<==vvd1gm$$<==vv# - . .vv# - . .zzT!899=c344!H)1)=)=aA2<>B*K&BBAr3  k!"&&sd3%L9CS/!cr7BsGQ'E11(E%FFv \s   0!F33
Gr  r   r   rS   r4   r
   r
     s    5n '+VaZA!q rS   r
   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, 0<eps<1,
            0<=teta(i)<=pi, 0<=phi(i)<=2*pi, w(i)>0, 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<tt(5)<tt(6)<...<tt(nt-4)<pi
                        0<tp(5)<tp(6)<...<tp(np-4)<2*pi
            if iopt>=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.r   a  
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.r   c                   ,    \ rS rSrSrSS jrSS jrSrg)	SphereBivariateSplinei  a5  
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           	      (   [         R                  " U5      n[         R                  " U5      nUR                  S:  aA  UR                  5       S:  d"  UR	                  5       [         R
                  :  a  [        S5      e[        R                  XUX4US9$ )a  
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   r8   zrequested theta out of bounds.r   )	r=   r>   rB   minr  pirA   r   r   r-   thetaphidthetadphir   s         r4   r   SphereBivariateSpline.__call__  sx    R 

5!jjo::>uyy{R/599;3F=>>#,,T#06d - L 	LrS   c                 $    U R                  XX4SS9$ )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()
Fr2  r3  r   r   )r-   r0  r1  r2  r3  s        r4   r   SphereBivariateSpline.ev  s    z }}U}NNrS   r   Nr   r  )r   r   r   r   r   r   r   r   r   rS   r4   r+  r+    s    (PLd=OrS   r+  c                   ,    \ rS rSrSrSS jrSS jrSrg)	r	   i*  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           
         [         R                  " U5      [         R                  " U5      [         R                  " U5      p2nSU:*  R                  5       (       a&  U[         R                  :*  R                  5       (       d  [	        S5      eSU:*  R                  5       (       a)  US[         R                  -  :*  R                  5       (       d  [	        S5      eUb9  [         R                  " U5      nUS:  R                  5       (       d  [	        S5      eUS:  d  [	        S5      eSUs=:  a  S:  d  O  [	        S5      e[
           [        R                  " XX4UUS	9u  pxppnS S S 5        WS
;  a$  [        R                  USU 35      n[	        U5      eWU l
        WS W W
S W	 WS US-
  U	S-
  -   4U l        SU l        g ! , (       d  f       Nc= f)Nr8   theta should be between [0, pi]       @phi should be between [0, 2pi]r   s should be positiver   r   )r    r#   r  r  rY   r   r   r   )r=   r>   r@   r.  rA   r'   r(   spherfit_smth_spherefit_messagesr^   r   rN   r   )r-   r0  r1  rr    r#   r  nt_tt_np_tp_rP   r   rb   rc   s                  r4   r5   $SmoothSphereBivariateSpline.__init__  s   

5)2::c?BJJqMA ""$$%255.)=)=)?)?>??  ""sRUU{(:'?'?'A'A=>>=

1AH>>## !788Cx344S3;<<-5-C-CEDEaHK.M*Ccs  k!)--cT#<@GW%%t9c$3i+AS1Wq,A)BB \s   F>>
Gc           	      ,   [         R                  " U5      n[         R                  " U5      nUR                  S:  aD  UR                  5       S:  d%  UR	                  5       S[         R
                  -  :  a  [        S5      e[        R                  XX#XES9$ Nr   r8   r;  zrequested phi out of bounds.r6  	r=   r>   rB   r-  r  r.  rA   r+  r   r/  s         r4   r   $SmoothSphereBivariateSpline.__call__  v    

5!jjo88a<SWWY^swwy2:/E;<<$--d337 . D 	DrS   r  )Nr8   r  r   r   r   r   r   r   r5   r   r   r   rS   r4   r	   r	   *  s    aF<	DrS   r	   c                   ,    \ rS rSrSrSS jrSS jrSrg)	r   i  at  
Weighted least-squares bivariate spline approximation in spherical
coordinates.

Determines a smoothing bicubic spline according to a given
set of knots in the `theta` and `phi` directions.

.. 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]``.
tt, tp : array_like
    Strictly ordered 1-D sequences of knots coordinates.
    Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``.
w : array_like, optional
    Positive 1-D sequence of weights, of the same length as `theta`, `phi`
    and `r`.
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
SmoothSphereBivariateSpline :
    a smoothing bivariate spline in spherical coordinates
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):

>>> 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                    [         R                  " U5      [         R                  " U5      [         R                  " U5      p2n[         R                  " U5      [         R                  " U5      pTSU:*  R                  5       (       a&  U[         R                  :*  R                  5       (       d  [	        S5      eSU:*  R                  5       (       a)  US[         R                  -  :*  R                  5       (       d  [	        S5      eSU:  R                  5       (       a&  U[         R                  :  R                  5       (       d  [	        S5      eSU:  R                  5       (       a)  US[         R                  -  :  R                  5       (       d  [	        S5      eUb9  [         R                  " U5      nUS:  R                  5       (       d  [	        S5      eSUs=:  a  S:  d  O  [	        S	5      eS
[        U5      -   S
[        U5      -   p[        U4[        5      [        U	4[        5      pXEsU
SS& USS& [         R                  S[         R                  -  sU
SS & USS & [           [        R                  " XX:UXgS9u  ppnS S S 5        WS:  a$  [        R                  USU 35      n[	        U5      eWU l        XW4U l        SU l        g ! , (       d  f       NP= f)Nr8   r:  r   r<  ztt should be between (0, pi)ztp should be between (0, 2pi)r   r   r   rV   r   r;  )r    r  r   rY   r>  )r=   r>   r@   r.  rA   rL   r   r  r'   r(   spherfit_lsqr@  r^   r   rN   r   )r-   r0  r1  rA  tttpr    r  rB  rD  rC  rE  rP   r   rb   rc   s                   r4   r5   !LSQSphereBivariateSpline.__init__$  s;   

5)2::c?BJJqMABBB""$$%255.)=)=)?)?>??  ""qw';';'='==>>r  b255j%5%5%7%7;<<r  b1RUU7l%7%7%9%9<===

1AH>>## !788S3;<<s2w;CGS#'vu)=S!Ab	3q9UUBJBC#bc(#+#8#8QS:;$F CaS  7)--cT#<@GW%%Q; \s   #K		
Kc           	      ,   [         R                  " U5      n[         R                  " U5      nUR                  S:  aD  UR                  5       S:  d%  UR	                  5       S[         R
                  -  :  a  [        S5      e[        R                  XX#XES9$ rH  rI  r/  s         r4   r   !LSQSphereBivariateSpline.__call__G  rK  rS   r  )Nr  r   rL  r   rS   r4   r   r     s    iV!F	DrS   r   a  
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)<u(i)< pi,i=2,..,mu,
          -pi<=v(1)< pi, v(1)<v(i-1)<v(i)<v(1)+2*pi, i=3,...,mv
          if iopt(1)=-1: 8<=nu<=min(nuest,mu+6+iopt(2)+iopt(3))
                         0<tu(5)<tu(6)<...<tu(nu-4)< pi
                         8<=nv<=min(nvest,mv+7)
                         v(1)<tv(5)<tv(6)<...<tv(nv-4)<v(1)+2*pi
                         the schoenberg-whitney conditions, i.e. there must be
                         subset of grid coordinates uu(p) and vv(q) such that
                            tu(p) < uu(p) < tu(p+4) ,p=1,...,nu-4
                            (iopt(2)=1 and iopt(3)=1 also count for a uu-value
                            tv(q) < vv(q) < tv(q+4) ,q=1,...,nv-4
                            (vv(q) is either a value v(j) or v(j)+2*pi)
          if iopt(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                   0    \ rS rSrSr  SS jrSS jrSrg)	r   ip  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	                 h   [         R                  " / SQ[        S9n	[         R                  " / SQ[        S9n
Uc  SnO7[        U[        [         R
                  [         R                  45      (       a  Xf4n[        U[        5      (       a  XU4n[        U[        5      (       a  Xw4n[        U[        5      (       a  X4nUu  pXYSS & Uc  SU
S'   OUS   U
S'   Uc  SU
S'   OUS   U
S'   Uu  U
S'   U
S	'   [         R                  " U5      [         R                  " U5      p![         R                  " U5      nS
US   :  a  US   [         R                  :  d  [        S5      e[         R                  * US   s=::  a  [         R                  :  d  O  [        S5      eUS   US   S[         R                  -  -   ::  d  [        S5      e[         R                  " [         R                  " U5      S
:  5      (       d  [        S5      e[         R                  " [         R                  " U5      S
:  5      (       d  [        S5      eUR                  UR                  S   :X  d  [        S5      eUR                  UR                  S   :X  d  [        S5      eUS   SL a  US   SL a  [        S5      eUS   SL a  US   SL a  [        S5      eUS
:  d  [        S5      e[         R                  " U5      n[            ["        R$                  " XUR'                  5       UR'                  5       UR'                  5       XU5      u  pnnnnnS S S 5        WS;  a$  [(        R+                  USU 35      n[        U5      eWU l        WS W WS W WS US-
  US-
  -   4U l        SU l        US   U l        g ! , (       d  f       Nm= f)N)r   r   r   r   )r$   r   r$   r   )NNr   r$   r   r   r   r8   zu should be between (0, pi)z v[0] should be between [-pi, pi)z#v[-1] should be v[0] + 2pi or less zu must be strictly increasingzv 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_flatr=  r  rY   r   r>  )r=   r   dfitpack_int
isinstancer  float32float64boolr   r>   r.  rA   r@   r   rB   rC   r'   r(   regrid_smth_sphercopy_spfit_messagesr^   r   rN   r   v0)r-   uvrA  r#   pole_continuitypole_values
pole_exact	pole_flatioptiderr0r1r   tunvtvrP   r   rb   r(  s                        r4   r5   "RectSphereBivariateSpline.__init__	  sX   xx	6xxl;&KeRZZ%DEE&4Kot,,.@Oj$''$1Ji&&".I"QR:DG mDG:DG mDG$Qaxx{BHHQK1JJqMad
quruu}:;;v1%%?@@u!qw&BCCvvbggaj3&''<==vvbggaj3&''<==vv# - . .vv# - . . 1&9Q<4+? ) * *1&9Q<4+? ) * * Cx344HHQK)1)C)CDDEFFHDEFFHDEFFHDFA	*O&BBAr3  k!!%%cT#<8CS/!cr7BsGQ'9aBqD(9%::A$ \s   /AN##
N1c           	          [         R                  " U5      n[         R                  " U5      n[        R                  XX#XES9$ )Nr6  )r=   r>   r+  r   r/  s         r4   r   "RectSphereBivariateSpline.__call__T	  s>    

5!jjo$--d337 . D 	DrS   )r   r   rN   r`  )r8   FNFFr   rL  r   rS   r4   r   r   p  s     Sj JN-2L\DrS   r   ))r   __all__r_   	threadingr   numpyr   r   r   r   r   r=    r   r   r(   typesintvarr   rX  r'   r]   rD   r   r   r   r   r   r  r   r   r   r   r
   r^  r@  r+  r	   r   r_  r   r   rS   r4   <module>rw     s  
!   8 8   # ~~$$**v
J
J&' : a#F	9 F	9Rh#3 hV O* OhXE XEv

I
I


-CE' TH* HVM2 M6`O `Fa aHV/ Vr '++- 8 B  B dO0 dONKD"7 KD\XD4 XDv #'')" 8jD 5 jDrS   