a
    ߙfb%0                     @   s   d Z ddlZddlZddlmZ ddlmZ zddl	m
Z
 dZW n eyV   dZY n0 g d	Zd
dgiZG dd deZddd
ZedddZedddZdZde e_ de e_ dS )a  
Tabular models.

Tabular models of any dimension can be created using `tabular_model`.
For convenience `Tabular1D` and `Tabular2D` are provided.

Examples
--------
>>> table = np.array([[ 3.,  0.,  0.],
...                  [ 0.,  2.,  0.],
...                  [ 0.,  0.,  0.]])
>>> points = ([1, 2, 3], [1, 2, 3])
>>> t2 = Tabular2D(points, lookup_table=table, bounds_error=False,
...                fill_value=None, method='nearest')

    N)units   )Model)interpnTF)tabular_model	Tabular1D	Tabular2Dr   Zscipyc                       s   e Zd ZdZdZdZdZdZdZdddde	j
f fdd	Zd	d
 Zdd Zedd Zedd Zedd Zdd Zedd Z  ZS )_Tabulara  
    Returns an interpolated lookup table value.

    Parameters
    ----------
    points : tuple of ndarray of float, optional
        The points defining the regular grid in n dimensions.
        ndarray must have shapes (m1, ), ..., (mn, ),
    lookup_table : array-like
        The data on a regular grid in n dimensions.
        Must have shapes (m1, ..., mn, ...)
    method : str, optional
        The method of interpolation to perform. Supported are "linear" and
        "nearest", and "splinef2d". "splinef2d" is only supported for
        2-dimensional data. Default is "linear".
    bounds_error : bool, optional
        If True, when interpolated values are requested outside of the
        domain of the input data, a ValueError is raised.
        If False, then ``fill_value`` is used.
    fill_value : float or `~astropy.units.Quantity`, optional
        If provided, the value to use for points outside of the
        interpolation domain. If None, values outside
        the domain are extrapolated.  Extrapolation is not supported by method
        "splinef2d". If Quantity is given, it will be converted to the unit of
        ``lookup_table``, if applicable.

    Returns
    -------
    value : ndarray
        Interpolated values at input coordinates.

    Raises
    ------
    ImportError
        Scipy is not installed.

    Notes
    -----
    Uses `scipy.interpolate.interpn`.

    FTr   Nlinearc           	         sr  | dd}|dkrtdt jf i | d| _|d u rDtdt|tjsZt	
|}| jj|jkrztd| jj|d u rtdd |jD }n~|jdkrt|ts|f}t|}||jkrtd	|j||dkrt|d
 tjrttdd |D dkrtdt|tjrPt|tjsBtd|j||jj}|| _|| _|| _|| _|| _d S )Nn_modelsr   zOnly n_models=1 is supported.)yzMust provide a lookup table.z3lookup_table should be an array with {} dimensions.c                 s   s   | ]}t j|td V  qdS ))ZdtypeN)npZarangefloat.0x r   7lib/python3.9/site-packages/astropy/modeling/tabular.py	<genexpr>m   s   z$_Tabular.__init__.<locals>.<genexpr>z.Expected grid points in {} directions, got {}.r   c                 S   s   g | ]}t |d dqS )unitN)getattrr   pr   r   r   
<listcomp>x       z%_Tabular.__init__.<locals>.<listcomp>z#points must all have the same unit.z0fill value is in {} but expected to be unitless.)getNotImplementedErrorsuper__init__outputs
ValueError
isinstanceuQuantityr   Zasarraylookup_tablendimformattupleshapelensetr   tovaluepointsbounds_errormethod
fill_value)	selfr-   r$   r/   r.   r0   kwargsr   Znpts	__class__r   r   r   Z   sR    


z_Tabular.__init__c                 C   s   d | jj| j| jS )Nz <{}(points={}, lookup_table={})>)r&   r4   __name__r-   r$   r1   r   r   r   __repr__   s    z_Tabular.__repr__c                 C   sh   d| j jfd| jfd| jfd| jfdd| jfd| jfd| jfd	| jfd
| j	fg
}dd |D }d
|S )Nr   NameZN_inputsZ	N_outputs)Z
Parameters z  pointsz  lookup_tablez  methodz  fill_valuez  bounds_errorc                 S   s&   g | ]\}}|d ur| d| qS )Nz: r   )r   keywordr,   r   r   r   r      s   z$_Tabular.__str__.<locals>.<listcomp>
)r4   r5   namen_inputs	n_outputsr-   r$   r/   r0   r.   join)r1   Zdefault_keywordspartsr   r   r   __str__   s    
z_Tabular.__str__c                    s2   | j d  t tjsd S t fdd| jD S )Nr   c                    s   g | ]}| j fqS r   )r   r   Zptsr   r   r      r   z(_Tabular.input_units.<locals>.<listcomp>)r-   r!   r"   r#   dictinputsr6   r   rB   r   input_units   s    
z_Tabular.input_unitsc                 C   s$   t | jtjsd S | jd | jjiS )Nr   )r!   r$   r"   r#   r   r   r6   r   r   r   return_units   s    z_Tabular.return_unitsc                 C   s2   dd | j D ddd }t|dkr.|d }|S )ay  
        Tuple defining the default ``bounding_box`` limits,
        ``(points_low, points_high)``.

        Examples
        --------
        >>> from astropy.modeling.models import Tabular1D, Tabular2D
        >>> t1 = Tabular1D(points=[1, 2, 3], lookup_table=[10, 20, 30])
        >>> t1.bounding_box
        ModelBoundingBox(
            intervals={
                x: Interval(lower=1, upper=3)
            }
            model=Tabular1D(inputs=('x',))
            order='C'
        )
        >>> t2 = Tabular2D(points=[[1, 2, 3], [2, 3, 4]],
        ...                lookup_table=[[10, 20, 30], [20, 30, 40]])
        >>> t2.bounding_box
        ModelBoundingBox(
            intervals={
                x: Interval(lower=1, upper=3)
                y: Interval(lower=2, upper=4)
            }
            model=Tabular2D(inputs=('x', 'y'))
            order='C'
        )

        c                 S   s   g | ]}t |t|fqS r   )minmaxr   r   r   r   r      r   z)_Tabular.bounding_box.<locals>.<listcomp>Nr   r   )r-   r)   )r1   Zbboxr   r   r   bounding_box   s    z_Tabular.bounding_boxc                    s   t j| }|d j dd |d| j D }t |j}tsDtdt| j	| j
|| j| j| jd}t| j
tjrt| j	d tjs|| j
j }| jdkr| }n fdd|D }|S )	a  
        Return the interpolated values at the input coordinates.

        Parameters
        ----------
        inputs : list of scalar or list of ndarray
            Input coordinates. The number of inputs must be equal
            to the dimensions of the lookup table.
        r   c                 S   s   g | ]}|  qS r   )Zflatten)r   Zinpr   r   r   r      r   z%_Tabular.evaluate.<locals>.<listcomp>NzTabular model requires scipy.)r/   r.   r0   r   c                    s   g | ]}|  qS r   )reshape)r   rr(   r   r   r      r   )r   Zbroadcast_arraysr(   r=   ZarrayT	has_scipyImportErrorr   r-   r$   r/   r.   r0   r!   r"   r#   r   r>   rK   )r1   rD   resultr   rM   r   evaluate   s$    



z_Tabular.evaluatec                 C   s   | j dkrtt| jdkr2| j}| jd }n@tt| jdk rn| jd d d }| jd d d d }ntt||| j| j	| j
dS tdd S )Nr   r   rI   )r-   r$   r/   r.   r0   zHAn analytical inverse transform has not been implemented for this model.)r=   r   allZdiffr$   r-   r   r   r/   r.   r0   )r1   r-   r$   r   r   r   inverse   s    

z_Tabular.inverse)r5   
__module____qualname____doc__r
   ZfittableZstandard_broadcastingZ_is_dynamic_idr   nanr   r7   rA   propertyrE   rF   rJ   rR   rT   __classcell__r   r   r3   r   r	   &   s(   *-


# r	   c                 C   s   | dk rt dtdg|  }|| dd}| dkr>d|d< nd|d< |du rltj}t jd7  _d	| }tt|tf|}d
|_|S )a  
    Make a ``Tabular`` model where ``n_inputs`` is
    based on the dimension of the lookup_table.

    This model has to be further initialized and when evaluated
    returns the interpolated values.

    Parameters
    ----------
    dim : int
        Dimensions of the lookup table.
    name : str
        Name for the class.

    Examples
    --------
    >>> table = np.array([[3., 0., 0.],
    ...                   [0., 2., 0.],
    ...                   [0., 0., 0.]])

    >>> tab = tabular_model(2, name='Tabular2D')
    >>> print(tab)
    <class 'astropy.modeling.tabular.Tabular2D'>
    Name: Tabular2D
    N_inputs: 2
    N_outputs: 1

    >>> points = ([1, 2, 3], [1, 2, 3])

    Setting fill_value to None, allows extrapolation.
    >>> m = tab(points, lookup_table=table, name='my_table',
    ...         bounds_error=False, fill_value=None, method='nearest')

    >>> xinterp = [0, 1, 1.5, 2.72, 3.14]
    >>> m(xinterp, xinterp)  # doctest: +FLOAT_CMP
    array([3., 3., 3., 0., 0.])

    r   z.Lookup table must have at least one dimension.   )r$   r=   r>   TZ
_separableFNZTabularzastropy.modeling.tabular)r    r   Zzerosr	   rX   typestrrU   )Zdimr<   tablemembersZmodel_idZmodel_classr   r   r   r     s    '

r   )r<   r\   r   a  
    method : str, optional
        The method of interpolation to perform. Supported are "linear" and
        "nearest", and "splinef2d". "splinef2d" is only supported for
        2-dimensional data. Default is "linear".
    bounds_error : bool, optional
        If True, when interpolated values are requested outside of the
        domain of the input data, a ValueError is raised.
        If False, then ``fill_value`` is used.
    fill_value : float, optional
        If provided, the value to use for points outside of the
        interpolation domain. If None, values outside
        the domain are extrapolated.  Extrapolation is not supported by method
        "splinef2d".

    Returns
    -------
    value : ndarray
        Interpolated values at input coordinates.

    Raises
    ------
    ImportError
        Scipy is not installed.

    Notes
    -----
    Uses `scipy.interpolate.interpn`.
a!  
    Tabular model in 1D.
    Returns an interpolated lookup table value.

    Parameters
    ----------
    points : array-like of float of ndim=1.
        The points defining the regular grid in n dimensions.
    lookup_table : array-like, of ndim=1.
        The data in one dimensions.
ai  
    Tabular model in 2D.
    Returns an interpolated lookup table value.

    Parameters
    ----------
    points : tuple of ndarray of float, optional
        The points defining the regular grid in n dimensions.
        ndarray with shapes (m1, m2).
    lookup_table : array-like
        The data on a regular grid in 2 dimensions.
        Shape (m1, m2).

)N)rW   abcZnumpyr   Zastropyr   r"   corer   Zscipy.interpolater   rO   rP   __all__Z__doctest_requires__r	   r   r   r   Z	_tab_docsr   r   r   r   <module>   s.   

 b
<
