B
    q\*                 @   s   d Z ddlZddlZddlmZ ddlmZ ddl	m
Z
 yddlZddlmZ dZW n ek
rl   d	ZY nX eoze
ed
Zdddg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   )Model)units)
minversion)interpnTFz0.14tabular_model	Tabular1D	Tabular2Dscipyc                   s   e Zd ZdZdZdZdZdZee	j
d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  ZS )_Tabulara\  
    Returns an interpolated lookup table value.

    Parameters
    ----------
    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ), optional
        The points defining the regular grid in n dimensions.
    lookup_table : array-like, shape (m1, ..., mn, ...)
        The data on a regular grid in n dimensions.
    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`.

    F)yc             C   s   d S )N )selfr   r   7lib/python3.7/site-packages/astropy/modeling/tabular.pylookup_tableY   s    z_Tabular.lookup_tableTr   Nlinearc       	         sh  | dd}|dkrtdt jf | |d kr:tdt|tjsPt	|}| j
j|jkrptd| j
j|d k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rFt|tjs8td|j||jj}|| _|| _
|| _|| _|| _d S )Nn_modelsr   zOnly n_models=1 is supported.zMust provide a lookup table.z4lookup_table should be an array with {0} dimensions.c             s   s   | ]}t j|td V  qdS ))ZdtypeN)npZarangefloat).0xr   r   r   	<genexpr>u   s   z$_Tabular.__init__.<locals>.<genexpr>z0Expected grid points in {0} directions, got {1}.r   c             S   s   g | ]}t |d dqS )unitN)getattr)r   pr   r   r   
<listcomp>   s    z%_Tabular.__init__.<locals>.<listcomp>z#points must all have the same unit.z1fill value is in {0} but expected to be unitless.)getNotImplementedErrorsuper__init__
ValueError
isinstanceuQuantityr   Zasarrayr   ndimformattupleshapelensetr   tovaluepointsbounds_errormethod
fill_value)	r   r,   r   r.   r-   r/   kwargsr   Znpts)	__class__r   r   r   b   sD    


z_Tabular.__init__c             C   s   d | jj| j| j}|S )Nz#<{0}(points={1}, lookup_table={2})>)r%   r1   __name__r,   r   )r   Zfmtr   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InputsZOutputs)Z
Parameters z  pointsz  lookup_tablez  methodz  fill_valuez  bounds_errorc             S   s$   g | ]\}}|d k	rd ||qS )Nz{0}: {1})r%   )r   keywordr+   r   r   r   r      s   z$_Tabular.__str__.<locals>.<listcomp>
)r1   r2   nameinputsoutputsr,   r   r.   r/   r-   join)r   Zdefault_keywordspartsr   r   r   __str__   s    
z_Tabular.__str__c                s6   | j d  t tjsd S t fdd| jD S d S )Nr   c                s   g | ]}| j fqS r   )r   )r   r   )ptsr   r   r      s    z(_Tabular.input_units.<locals>.<listcomp>)r,   r!   r"   r#   dictr9   )r   r   )r>   r   input_units   s    
z_Tabular.input_unitsc             C   s"   t | jtjsd S d| jjiS d S )Nr   )r!   r   r"   r#   r   )r   r   r   r   return_units   s    z_Tabular.return_unitsc             C   s6   dd | j D ddd }t|dkr.|d }t|S )a  
        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
        (1, 3)
        >>> t2 = Tabular2D(points=[[1, 2, 3], [2, 3, 4]],
        ...                lookup_table=[[10, 20, 30], [20, 30, 40]])
        >>> t2.bounding_box
        ((2, 4), (1, 3))

        c             S   s   g | ]}t |t|fqS r   )minmax)r   r   r   r   r   r      s    z)_Tabular.bounding_box.<locals>.<listcomp>Nr   r   )r,   r(   r&   )r   Zbboxr   r   r   bounding_box   s    z_Tabular.bounding_boxc                s   t |tjr|j}|d j dd |d| j D }t|j}t	sLt
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 scalars or ndarrays
            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      s    z%_Tabular.evaluate.<locals>.<listcomp>Nz"This model requires scipy >= v0.14)r.   r-   r/   r   c                s   g | ]}|  qS r   )reshape)r   r)r'   r   r   r      s    )r!   r"   r#   r+   r'   Zn_inputsr   ZarrayT	has_scipyImportErrorr   r,   r   r.   r-   r/   r   Z	n_outputsrF   )r   r9   resultr   )r'   r   evaluate   s"    



z_Tabular.evaluate)r2   
__module____qualname____doc__r   ZfittableZstandard_broadcastingr:   propertyabcabstractmethodr   Z_is_dynamic_idr   nanr   r3   r=   r@   rA   rE   rL   __classcell__r   r   )r1   r   r   *   s"   ',r   c             C   s   | dk rt dtdg|  }tdd t|jD }||d}| dkrTd|d< nd	|d< |d
krtj}t jd7  _d|}t	t
|tf|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 'abc.Tabular2D'>
    Name: Tabular2D
    Inputs: (u'x0', u'x1')
    Outputs: (u'y',)

    >>> 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.   c             s   s   | ]}d  |V  qdS )zx{0}N)r%   )r   idxr   r   r   r     s    z tabular_model.<locals>.<genexpr>)r   r9   TZ
_separableFNz
Tabular{0})r    r   Zzerosr&   ranger$   r   rS   r%   typestr)Zdimr8   tabler9   membersZmodel_idr   r   r   r      s    '


)r8   rV   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.
aQ  
    Tabular model in 2D.
    Returns an interpolated lookup table value.

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

)N)rO   rQ   Znumpyr   Zcorer   Zastropyr   r"   Zastropy.utilsr   r
   Zscipy.interpolater   rI   rJ   __all__Z__doctest_requires__r   r   r   r	   Z	_tab_docsr   r   r   r   <module>   s,   


 F
;
