a
    BCCfM                     @   s   d Z ddlZddlmZ ddlZddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZmZmZ d
gZh dZh dZddddddZdd Zdd ZG dd
 d
ZdS )zModule for RBF interpolation.    N)combinations_with_replacement)LinAlgError)KDTree)comb)dgesv   )_build_system_build_evaluation_coefficients_polynomial_matrixRBFInterpolator>   quinticcubiclinearZgaussianmultiquadricZinverse_multiquadricthin_plate_splineZinverse_quadratic>   r   r   r   r      )r   r   r   r   r   c                 C   s~   t ||  | dd}tj|| ftdd}d}t|d D ]>}tt| |D ]*}|D ]}|||f  d7  < qT|d7 }qLq:|S )a\  Return the powers for each monomial in a polynomial.

    Parameters
    ----------
    ndim : int
        Number of variables in the polynomial.
    degree : int
        Degree of the polynomial.

    Returns
    -------
    (nmonos, ndim) int ndarray
        Array where each row contains the powers for each variable in a
        monomial.

    T)exactlongdtyper   r   )r   npZzerosr   ranger   )ndimdegreenmonosoutcountdegmonovar r    X/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/interpolate/_rbfinterp.py_monomial_powers2   s    r"   c                 C   s   t | |||||\}}}}	t||ddd\}
}
}}|dk rNtd|  dn^|dkrd}|jd }|dkrt| | |	 |}tj|}||k rd| d| d	}t|||	|fS )
a   Build and solve the RBF interpolation system of equations.

    Parameters
    ----------
    y : (P, N) float ndarray
        Data point coordinates.
    d : (P, S) float ndarray
        Data values at `y`.
    smoothing : (P,) float ndarray
        Smoothing parameter for each data point.
    kernel : str
        Name of the RBF.
    epsilon : float
        Shape parameter.
    powers : (R, N) int ndarray
        The exponents for each monomial in the polynomial.

    Returns
    -------
    coeffs : (P + R, S) float ndarray
        Coefficients for each RBF and monomial.
    shift : (N,) float ndarray
        Domain shift used to create the polynomial matrix.
    scale : (N,) float ndarray
        Domain scaling used to create the polynomial matrix.

    T)Zoverwrite_aZoverwrite_br   zThe z"-th argument had an illegal value.zSingular matrix.zqSingular matrix. The matrix of monomials evaluated at the data point coordinates does not have full column rank (/z).)	r   r   
ValueErrorshaper
   r   ZlinalgZmatrix_rankr   )yd	smoothingkernelepsilonpowerslhsrhsshiftscale_coeffsinfomsgr   ZpmatZrankr    r    r!   _build_and_solve_systemR   s*    
r4   c                   @   s,   e Zd ZdZdddZddd	Zd
d ZdS )r   aU  Radial basis function (RBF) interpolation in N dimensions.

    Parameters
    ----------
    y : (npoints, ndims) array_like
        2-D array of data point coordinates.
    d : (npoints, ...) array_like
        N-D array of data values at `y`. The length of `d` along the first
        axis must be equal to the length of `y`. Unlike some interpolators, the
        interpolation axis cannot be changed.
    neighbors : int, optional
        If specified, the value of the interpolant at each evaluation point
        will be computed using only this many nearest data points. All the data
        points are used by default.
    smoothing : float or (npoints, ) array_like, optional
        Smoothing parameter. The interpolant perfectly fits the data when this
        is set to 0. For large values, the interpolant approaches a least
        squares fit of a polynomial with the specified degree. Default is 0.
    kernel : str, optional
        Type of RBF. This should be one of

            - 'linear'               : ``-r``
            - 'thin_plate_spline'    : ``r**2 * log(r)``
            - 'cubic'                : ``r**3``
            - 'quintic'              : ``-r**5``
            - 'multiquadric'         : ``-sqrt(1 + r**2)``
            - 'inverse_multiquadric' : ``1/sqrt(1 + r**2)``
            - 'inverse_quadratic'    : ``1/(1 + r**2)``
            - 'gaussian'             : ``exp(-r**2)``

        Default is 'thin_plate_spline'.
    epsilon : float, optional
        Shape parameter that scales the input to the RBF. If `kernel` is
        'linear', 'thin_plate_spline', 'cubic', or 'quintic', this defaults to
        1 and can be ignored because it has the same effect as scaling the
        smoothing parameter. Otherwise, this must be specified.
    degree : int, optional
        Degree of the added polynomial. For some RBFs the interpolant may not
        be well-posed if the polynomial degree is too small. Those RBFs and
        their corresponding minimum degrees are

            - 'multiquadric'      : 0
            - 'linear'            : 0
            - 'thin_plate_spline' : 1
            - 'cubic'             : 1
            - 'quintic'           : 2

        The default value is the minimum degree for `kernel` or 0 if there is
        no minimum degree. Set this to -1 for no added polynomial.

    Notes
    -----
    An RBF is a scalar valued function in N-dimensional space whose value at
    :math:`x` can be expressed in terms of :math:`r=||x - c||`, where :math:`c`
    is the center of the RBF.

    An RBF interpolant for the vector of data values :math:`d`, which are from
    locations :math:`y`, is a linear combination of RBFs centered at :math:`y`
    plus a polynomial with a specified degree. The RBF interpolant is written
    as

    .. math::
        f(x) = K(x, y) a + P(x) b,

    where :math:`K(x, y)` is a matrix of RBFs with centers at :math:`y`
    evaluated at the points :math:`x`, and :math:`P(x)` is a matrix of
    monomials, which span polynomials with the specified degree, evaluated at
    :math:`x`. The coefficients :math:`a` and :math:`b` are the solution to the
    linear equations

    .. math::
        (K(y, y) + \lambda I) a + P(y) b = d

    and

    .. math::
        P(y)^T a = 0,

    where :math:`\lambda` is a non-negative smoothing parameter that controls
    how well we want to fit the data. The data are fit exactly when the
    smoothing parameter is 0.

    The above system is uniquely solvable if the following requirements are
    met:

        - :math:`P(y)` must have full column rank. :math:`P(y)` always has full
          column rank when `degree` is -1 or 0. When `degree` is 1,
          :math:`P(y)` has full column rank if the data point locations are not
          all collinear (N=2), coplanar (N=3), etc.
        - If `kernel` is 'multiquadric', 'linear', 'thin_plate_spline',
          'cubic', or 'quintic', then `degree` must not be lower than the
          minimum value listed above.
        - If `smoothing` is 0, then each data point location must be distinct.

    When using an RBF that is not scale invariant ('multiquadric',
    'inverse_multiquadric', 'inverse_quadratic', or 'gaussian'), an appropriate
    shape parameter must be chosen (e.g., through cross validation). Smaller
    values for the shape parameter correspond to wider RBFs. The problem can
    become ill-conditioned or singular when the shape parameter is too small.

    The memory required to solve for the RBF interpolation coefficients
    increases quadratically with the number of data points, which can become
    impractical when interpolating more than about a thousand data points.
    To overcome memory limitations for large interpolation problems, the
    `neighbors` argument can be specified to compute an RBF interpolant for
    each evaluation point using only the nearest data points.

    .. versionadded:: 1.7.0

    See Also
    --------
    NearestNDInterpolator
    LinearNDInterpolator
    CloughTocher2DInterpolator

    References
    ----------
    .. [1] Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab.
        World Scientific Publishing Co.

    .. [2] http://amadeus.math.iit.edu/~fass/603_ch3.pdf

    .. [3] Wahba, G., 1990. Spline Models for Observational Data. SIAM.

    .. [4] http://pages.stat.wisc.edu/~wahba/stat860public/lect/lect8/lect8.pdf

    Examples
    --------
    Demonstrate interpolating scattered data to a grid in 2-D.

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.interpolate import RBFInterpolator
    >>> from scipy.stats.qmc import Halton

    >>> rng = np.random.default_rng()
    >>> xobs = 2*Halton(2, seed=rng).random(100) - 1
    >>> yobs = np.sum(xobs, axis=1)*np.exp(-6*np.sum(xobs**2, axis=1))

    >>> xgrid = np.mgrid[-1:1:50j, -1:1:50j]
    >>> xflat = xgrid.reshape(2, -1).T
    >>> yflat = RBFInterpolator(xobs, yobs)(xflat)
    >>> ygrid = yflat.reshape(50, 50)

    >>> fig, ax = plt.subplots()
    >>> ax.pcolormesh(*xgrid, ygrid, vmin=-0.25, vmax=0.25, shading='gouraud')
    >>> p = ax.scatter(*xobs.T, c=yobs, s=50, ec='k', vmin=-0.25, vmax=0.25)
    >>> fig.colorbar(p)
    >>> plt.show()

    N        r   c                 C   s~  t j|tdd}|jdkr"td|j\}}	t |r:tnt}
t j||
dd}|jd |krltd| d|jdd  }||d	f}|	t}t 
|rt j||td
}n,t j|tdd}|j|fkrtd| d| }|tvrtdt d|d u r&|tv rd}ntdt dnt|}t|d	}|d u rPt|d}nVt|}|d	k rltdn:d	|  k r|k rn ntjd| d| dtdd |d u r|}ntt||}|}t|	|}|jd |krtd|jd  d| d|	 d|d u r:t||||||\}}}|| _|| _|| _n
t|| _|| _|| _|| _ |
| _!|| _"|| _#|| _$|| _%|| _&d S )NCr   orderr   z"`y` must be a 2-dimensional array.r   z.Expected the first axis of `d` to have length .r   r   z3Expected `smoothing` to be a scalar or have shape (z,).z`kernel` must be one of g      ?z6`epsilon` must be specified if `kernel` is not one of z`degree` must be at least -1.z`degree` should not be below z except -1 when `kernel` is 'zk'.The interpolant may not be uniquely solvable, and the smoothing parameter may have an unintuitive effect.)
stacklevelz	At least z+ data points are required when `degree` is z! and the number of dimensions is )'r   asarrayfloatr   r$   r%   ZiscomplexobjcomplexreshapeviewZisscalarfulllower
_AVAILABLE_SCALE_INVARIANT_NAME_TO_MIN_DEGREEgetmaxintwarningswarnUserWarningminr"   r4   _shift_scale_coeffsr   _treer&   r'   d_shaped_dtype	neighborsr(   r)   r*   r+   )selfr&   r'   rS   r(   r)   r*   r   nyr   rR   rQ   Z
min_degreeZnobsr+   r.   r/   r1   r    r    r!   __init__  s    









	




zRBFInterpolator.__init__@B c              	   C   s   |j \}}| jdu rt|}	n| j}	|| jj d |	  d }
|
|krtj|| jj d ftd}td||
D ]R}t	||||
 ddf || j
| j| j||}t||||||
 ddf< qjn&t	||| j
| j| j||}t||}|S )a  
        Evaluate the interpolation while controlling memory consumption.
        We chunk the input if we need more memory than specified.

        Parameters
        ----------
        x : (Q, N) float ndarray
            array of points on which to evaluate
        y: (P, N) float ndarray
            array of points on which we know function values
        shift: (N, ) ndarray
            Domain shift used to create the polynomial matrix.
        scale : (N,) float ndarray
            Domain scaling used to create the polynomial matrix.
        coeffs: (P+R, S) float ndarray
            Coefficients in front of basis functions
        memory_budget: int
            Total amount of memory (in units of sizeof(float)) we wish
            to devote for storing the array of coefficients for
            interpolated points. If we need more memory than that, we
            chunk the input.

        Returns
        -------
        (Q, S) float ndarray
        Interpolated array
        Nr   r   r   )r%   rS   lenr+   r   emptyr'   r=   r   r	   r)   r*   dot)rT   xr&   r.   r/   r1   memory_budgetnxr   Znnei	chunksizer   iZvecr    r    r!   _chunk_evaluator  s:    $


$z RBFInterpolator._chunk_evaluatorc              	   C   s  t j|tdd}|jdkr"td|j\}}|| jjd krTtd| jjd  dt|j| jj | j	j d}| j
d	u r| j|| j| j| j| j|d
}n"| j|| j
\}}| j
dkr|d	d	d	f }t j|dd}t j|ddd\}}t |d}dd tt|D }	t|D ]\}
}|	| |
 qt j|| j	jd ftd}t|	|D ]h\}}|| }| j| }| j	| }| j| }t|||| j| j| j\}}}| j||||||d
||< qT|| j }||f| j! }|S )a  Evaluate the interpolant at `x`.

        Parameters
        ----------
        x : (Q, N) array_like
            Evaluation point coordinates.

        Returns
        -------
        (Q, ...) ndarray
            Values of the interpolant at `x`.

        r6   r7   r   z"`x` must be a 2-dimensional array.r   z/Expected the second axis of `x` to have length r9   rW   N)r\   )axisTr   )Zreturn_inversera   )r:   c                 S   s   g | ]}g qS r    r    ).0r0   r    r    r!   
<listcomp>      z,RBFInterpolator.__call__.<locals>.<listcomp>r   )"r   r<   r=   r   r$   r%   r&   rG   sizer'   rS   r`   rM   rN   rO   rP   querysortuniquer?   r   rX   	enumerateappendrY   zipr(   r4   r)   r*   r+   r@   rR   rQ   )rT   r[   r]   r   r\   r   r0   ZyindicesinvZxindicesr_   jZxidxZyidxZxnbrZynbrZdnbrZsnbrr.   r/   r1   r    r    r!   __call__  sh    











zRBFInterpolator.__call__)Nr5   r   NN)rW   )__name__
__module____qualname____doc__rV   r`   rn   r    r    r    r!   r      s         
t 
C)rr   rI   	itertoolsr   numpyr   Znumpy.linalgr   Zscipy.spatialr   Zscipy.specialr   Zscipy.linalg.lapackr   Z_rbfinterp_pythranr   r	   r
   __all__rC   rD   rE   r"   r4   r   r    r    r    r!   <module>   s(   		 4