B
    q\Q[                 @   s  d Z ddlZddlZddlZddl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 ddlZdd	lmZ d
dddddgZeeddfZdddddZedd Zdd Zdd
 Zdd Zd"ddZG dd dZG dd deZG d d deZ G d!d de Z!dS )#a  This module contains functions and methods that relate to the DataInfo class
which provides a container for informational attributes as well as summary info
methods.

A DataInfo object is attached to the Quantity, SkyCoord, and Time classes in
astropy.  Here it allows those classes to be used in Tables and uniformly carry
table column attributes such as name, format, dtype, meta, and description.
    N)StringIO)deepcopy)partial)OrderedDict)contextmanager   )metadatadata_info_factorydtype_info_nameBaseColumnInfoDataInfo	MixinInfoParentDtypeInfozUAll-NaN|Mean of empty slice|Degrees of freedom <= 0|invalid value encountered in sqrt)categorymessagestrZunicodebytes))FS)FU)Tr   )Tr   c             c   s   t j}| t _dV  |t _dS )ak  Set context for serialization.

    This will allow downstream code to understand the context in which a column
    is being serialized.  Objects like Time or SkyCoord will have different
    default serialization representations depending on context.

    Parameters
    ----------
    context : str
        Context name, e.g. 'fits', 'hdf5', 'ecsv', 'yaml'
    N)r   _serialize_context)contextZold_context r   6lib/python3.7/site-packages/astropy/utils/data_info.pyserialize_context_as0   s    r   c             C   sJ   t | } | jdkr@td| jd}td| jf }|| }n| j}|S )ab  Return a human-oriented string name of the ``dtype`` arg.
    This can be use by astropy methods that present type information about
    a data object.

    The output is mostly equivalent to ``dtype.name`` which takes the form
    <type_name>[B] where <type_name> is like ``int`` or ``bool`` and [B] is an
    optional number of bits which gets included only for numeric types.

    For bytes, string and unicode types, the output is shown below, where <N>
    is the number of characters.  This representation corresponds to the Python
    type that matches the dtype::

      Numpy          S<N>      U<N>
      Python      bytes<N>   str<N>

    Parameters
    ----------
    dtype : str, np.dtype, type
        Input dtype as an object that can be converted via np.dtype()

    Returns
    -------
    dtype_info_name : str
        String name of ``dtype``
    )r   r   z(\d+)r   T)	npdtypekindresearchr   groupSTRING_TYPE_NAMESname)r   lengthZ	type_nameoutr   r   r   r
   C   s    


c                s    fdd}|S )a8  
    Factory to create a function that can be used as an ``option``
    for outputting data object summary information.

    Examples
    --------
    >>> from astropy.utils.data_info import data_info_factory
    >>> from astropy.table import Column
    >>> c = Column([4., 3., 2., 1.])
    >>> mystats = data_info_factory(names=['min', 'median', 'max'],
    ...                             funcs=[np.min, np.median, np.max])
    >>> c.info(option=mystats)
    min = 1.0
    median = 2.5
    max = 4.0
    n_bad = 0
    length = 4

    Parameters
    ----------
    names : list
        List of information attribute names
    funcs : list
        List of functions that compute the corresponding information attribute

    Returns
    -------
    func : function
        Function that can be used as a data info option
    c          	      s|   g }xht  D ]Z\}}y$t|tr2t| | }n|| }W n tk
rZ   |d Y qX |t| qW tt |S )Nz--)zip
isinstancer   getattr	Exceptionappendr   )datZoutsr!   funcr#   )funcsnamesr   r   r*      s    
zdata_info_factory.<locals>.funcr   )r,   r+   r*   r   )r+   r,   r   r	   h   s    c             C   s2   i }x(|D ] }t | |d}|dk	r
|||< q
W |S )a[  
    Get the values for object ``attrs`` and return as a dict.  This
    ignores any attributes that are None and in Py2 converts any unicode
    attribute names or values to str.  In the context of serializing the
    supported core astropy classes this conversion will succeed and results
    in more succinct and less python-specific YAML.
    N)r&   )objattrsr#   attrvalr   r   r   _get_obj_attrs_map   s    
r1   c             C   sn   |dkrt | j}nF|dkr*t| jj}n0|dkrN| jdd }|rH|nd}nt| j|}|dkrfd}t|S )zP
    Get a data object attribute for the ``attributes`` info summary method
    classr   shaper   N )type__name__r
   infor   r3   r&   r   )r)   r/   r0   Zdatshaper   r   r   _get_data_attribute   s    r8   c                   s
  e Zd ZdZddddgZe Zedddd	d
dgZe ZdZ	dZ
dZdZdZd/ddZedd Zejdd Zdd Zdd Zdd Zdd Z fddZ fdd Zd!d" Zd#d$ Zeee	d%d& e	D d'Zeeed(d& eD d'Zd0d+d,Z fd-d.Z  Z S )1r   a  
    Descriptor that data classes use to add an ``info`` attribute for storing
    data attributes in a uniform and portable way.  Note that it *must* be
    called ``info`` so that the DataInfo() object can be stored in the
    ``instance`` using the ``info`` key.  Because owner_cls.x is a descriptor,
    Python doesn't use __dict__['x'] normally, and the descriptor can safely
    store stuff there.  Thanks to http://nbviewer.ipython.org/urls/gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb
    for this trick that works for non-hashable classes.

    Parameters
    ----------
    bound : bool
        If True this is a descriptor attribute in a class definition, else it
        is a DataInfo() object that is bound to a data object instance. Default is False.
    ZmeanZstdminmaxr!   unitr   formatdescriptionmeta)r   r3   r;   r<   r=   r2   Nr   Fc             C   s   |rt dd | jD | _d S )Nc             s   s   | ]}|d fV  qd S )Nr   ).0r/   r   r   r   	<genexpr>   s    z$DataInfo.__init__.<locals>.<genexpr>)dict
attr_names_attrs)selfboundr   r   r   __init__   s    zDataInfo.__init__c             C   s.   | j d krd S |   }|d k	r"|S tdd S )Nax  failed access "info" attribute on a temporary object.

It looks like you have done something like ``col[3:5].info``, i.e.
you accessed ``info`` from a temporary slice object ``col[3:5]`` that
only exists momentarily.  This has failed because the reference to
that temporary object is now lost.  Instead force a permanent
reference with ``c = col[3:5]`` followed by ``c.info``.)_parent_refAttributeError)rD   parentr   r   r   _parent   s    
zDataInfo._parentc             C   s    |d krd | _ nt|| _ d S )N)rG   weakrefref)rD   valuer   r   r   rJ     s    c             C   sH   |d kr| }||_ n0|jd}|d kr>| jdd }|jd< ||_|S )Nr7   T)rE   )_parent_cls__dict__get	__class__rJ   )rD   instanceZ	owner_clsr7   r   r   r   __get__  s    zDataInfo.__get__c             C   sn   |d krt dt|trb| jdd }|jd< x8|j|j |j D ]}tt	|||j
|< qDW ntdd S )Nzcannot set unbound descriptorT)rE   r7   z)info must be set with a DataInfo instance)
ValueErrorr%   r   rQ   rO   rB   attrs_from_parent_attrs_no_copyr   r&   rC   	TypeError)rD   rR   rM   r7   r/   r   r   r   __set__  s    
zDataInfo.__set__c             C   s   | j S )N)rC   )rD   r   r   r   __getstate__!  s    zDataInfo.__getstate__c             C   s
   || _ d S )N)rC   )rD   stater   r   r   __setstate__$  s    zDataInfo.__setstate__c                s   | drt |S || jkr,t| j|S y| j| }W n  tk
rZ   t | Y nX |dkrrt|rr| }|dkr|d krt	
d}|S )N_parent_tabler   O)
startswithsuper__getattribute__rU   r&   rJ   rC   KeyErrorcallabler   r   )rD   r/   rM   )rQ   r   r   __getattr__'  s    


zDataInfo.__getattr__c                s   t | j|d }|| jkr4t|ts4t| j|| d S t|tr`|jd krPtd|| | d S |	dr|t
 || d S || jkrtd| j|dkr|d krd nt|}|| j|< d S )Nzcan't set attributer\   zattribute must be one of {0}r]   )r&   rQ   rU   r%   propertysetattrrJ   fsetrH   r_   r`   __setattr__rB   r<   rK   rL   rC   )rD   r/   rM   Zpropobj)rQ   r   r   rh   =  s"    



zDataInfo.__setattr__c             C   s   t | j| jS )z=Get the values for the parent ``attrs`` and return as a dict.)r1   rJ   _represent_as_dict_attrs)rD   r   r   r   _represent_as_dict\  s    zDataInfo._represent_as_dictc                s     fdd| j D }| j| S )Nc                s   g | ]}  |qS r   )pop)r?   r/   )mapr   r   
<listcomp>a  s    z1DataInfo._construct_from_dict.<locals>.<listcomp>)_construct_from_dict_argsrN   )rD   rl   argsr   )rl   r   _construct_from_dict`  s    zDataInfo._construct_from_dictc             C   s   g | ]}t t|d qS ))r/   )r   r8   )r?   r/   r   r   r   rm   f  s   zDataInfo.<listcomp>)r,   r+   c             C   s   g | ]}t td | qS )nan)r&   r   )r?   statr   r   r   rm   l  s   
attributesr4   c          
   C   s  |dkrt j}| j}t }|jj}|dk	r2||d< t|ttfrD|n|g}x~|D ]v}t|t	rt
| d| r|t| d| }ntd|t . xtD ]}tjd| qW ||| W dQ R X qPW t
|drt|j}n:ytt|t|B }W n tk
r   d}Y nX ||d	< yt||d
< W n tk
rJ   Y nX |dkrZ|S x8| D ],\}	}
|
dkrd|d|	|
tj  qdW dS )a  
        Write summary information about data object to the ``out`` filehandle.
        By default this prints to standard output via sys.stdout.

        The ``option`` argument specifies what type of information
        to include.  This can be a string, a function, or a list of
        strings or functions.  Built-in options are:

        - ``attributes``: data object attributes like ``dtype`` and ``format``
        - ``stats``: basic statistics: min, mean, and max

        If a function is specified then that function will be called with the
        data object as its single argument.  The function must return an
        OrderedDict containing the information attributes.

        If a list is provided then the information attributes will be
        appended for each of the options, in order.

        Examples
        --------

        >>> from astropy.table import Column
        >>> c = Column([1, 2], unit='m', dtype='int32')
        >>> c.info()
        dtype = int32
        unit = m
        class = Column
        n_bad = 0
        length = 2

        >>> c.info(['attributes', 'stats'])
        dtype = int32
        unit = m
        class = Column
        mean = 1.5
        std = 0.5
        min = 1
        max = 2
        n_bad = 0
        length = 2

        Parameters
        ----------
        option : str, function, list of (str or function)
            Info option, defaults to 'attributes'.
        out : file-like object, None
            Output destination, defaults to sys.stdout.  If None then the
            OrderedDict with information attributes is returned

        Returns
        -------
        info : OrderedDict if out==None else None
        r4   Nr!   Zinfo_summary_z-option={0} is not an allowed information typeignoremaskr   n_badr"   z	{0} = {1})rt   )sysstdoutrJ   r   r7   r!   r%   listtupler   hasattrr&   rT   r<   warningscatch_warningsIGNORE_WARNINGSfilterwarningsupdater   Zcount_nonzeroru   ZisinfZisnanr'   lenrW   itemswriteoslinesep)rD   Zoptionr#   r)   r7   r!   ZoptionsZignore_kwargsrv   keyr0   r   r   r   __call__o  sD    6







zDataInfo.__call__c                s.   | j d krt  S t }| j|d | S )N)r#   )rJ   r`   __repr__r   r   getvalue)rD   r#   )rQ   r   r   r     s
    

zDataInfo.__repr__)F)rs   r4   )!r6   
__module____qualname____doc__Z_statssetrU   rB   rV   Z_info_summary_attrsrG   ri   rn   Z_represent_as_dict_primary_datarF   re   rJ   setterrS   rX   rY   r[   rd   rh   rj   rp   staticmethodr	   Zinfo_summary_attributesZinfo_summary_statsr   r   __classcell__r   r   )rQ   r   r      s>   	

bc                   sd   e Zd ZdZejddgZedgZdZ	d fdd	Z
dd	 Zd
d Zdd Zedd Z  ZS )r   ag  
    Base info class for anything that can be a column in an astropy
    Table.  There are at least two classes that inherit from this:

      ColumnInfo: for native astropy Column / MaskedColumn objects
      MixinInfo: for mixin column objects

    Note that this class is defined here so that mixins can use it
    without importing the table package.
    r]   indicesNFc                s   t  j|d |ri | _d S )N)rE   )r`   rF   Z_format_funcs)rD   rE   )rQ   r   r   rF     s    zBaseColumnInfo.__init__c             c   sP   | j }| jdkrddlm} n| jj}|j}x||dddi D ]
}|V  q>W dS )zG
        This is a mixin-safe version of Column.iter_str_vals.
        Nr   )	FORMATTERF)rJ   r]   Zastropy.table.columnr   	formatter_pformat_col_iter)rD   colr   r   Zstr_valr   r   r   iter_str_vals  s    
zBaseColumnInfo.iter_str_valsc       	      C   s   | j s
dS t|tr,| |}tt| }n.t|tjrT|jjdkrTt	|d }n|g}t
|}|jdkr~t|t| }x6t||D ](\}}x| j D ]}||| j| qW qW dS )a  
        Adjust info indices after column modification.

        Parameters
        ----------
        index : slice, int, list, or ndarray
            Element(s) of column to modify. This parameter can
            be a single row number, a list of row numbers, an
            ndarray of row numbers, a boolean ndarray (a mask),
            or a column slice.
        value : int, list, or ndarray
            New value(s) to insert
        col_len : int
            Length of the column
        Nbr   r   )r   r%   slicery   ranger   ndarrayr   r   whereZ
atleast_1dsizer   r$   replacer!   )	rD   indexrM   col_lentkeysr   r0   Z	col_indexr   r   r   adjust_indices  s    



zBaseColumnInfo.adjust_indicesc       	         s   ddl m} t| dds$g |j_|S t trH fdd| jD |j_n| jrt tjrt j	j
dkrtt d  d}t d| k}g |j_xJ| jD ]@}|st||r|| }nt|}|  |jj| qW |S )	aX  
        Given a sliced object, modify its indices
        to correctly represent the slice.

        Parameters
        ----------
        col_slice : Column or mixin
            Sliced object
        item : slice, list, or ndarray
            Slice used to create col_slice
        col_len : int
            Length of original object
        r   )SortedArrayZ_copy_indicesTc                s   g | ]}|  qS r   r   )r?   x)itemr   r   rm   @  s    z0BaseColumnInfo.slice_indices.<locals>.<listcomp>r   g333333?)Zastropy.table.sorted_arrayr   r&   r7   r   r%   r   r   r   r   r   r   r   Z	get_slicer   Zreplace_rowsr(   )	rD   Z	col_slicer   r   r   Z	thresholdZsmallr   Z	new_indexr   )r   r   slice_indices,  s&    

zBaseColumnInfo.slice_indicesc       
         s   ddl m} fdd} fdd}|| d }x*| dd D ]}tj|||||d	}q>W t| |d
< tdd | D }	t|	dkr|d|	 |d< |S )a  
        Utility method to merge and validate the attributes ``attrs`` for the
        input table columns ``cols``.

        Note that ``dtype`` and ``shape`` attributes are handled specially.
        These should not be passed in ``attrs`` but will always be in the
        returned dict of merged attributes.

        Parameters
        ----------
        cols : list
            List of input Table column objects
        metadata_conflicts : str ('warn'|'error'|'silent')
            How to handle metadata conflicts
        name : str
            Output column name
        attrs : list
            List of attribute names to be merged

        Returns
        -------
        attrs : dict of merged attributes

        r   )TableMergeErrorc                s   d  | |||}|S )Nz_In merged column '{}' the '{}' attribute does not match ({} != {}).  Using {} for merged output)r<   )r   leftrightr#   )r!   r   r   warn_str_funcr  s    z;BaseColumnInfo.merge_cols_attributes.<locals>.warn_str_funcc                s    fddD S )Nc                s,   i | ]$}t  j|d d k	rt  j||qS )N)r&   r7   )r?   r/   )r   r   r   
<dictcomp>y  s    zJBaseColumnInfo.merge_cols_attributes.<locals>.getattrs.<locals>.<dictcomp>r   )r   )r.   )r   r   getattrsx  s    z6BaseColumnInfo.merge_cols_attributes.<locals>.getattrsr   N)metadata_conflictsr   r   c             s   s   | ]}|j d d V  qdS )r   N)r3   )r?   r   r   r   r   r@     s    z7BaseColumnInfo.merge_cols_attributes.<locals>.<genexpr>zcolumns have different shapesr3   )astropy.table.np_utilsr   r   mergeZcommon_dtyper   r   rk   )
Zcolsr   r!   r.   r   r   r   r#   r   Zuniq_shapesr   )r.   r!   r   merge_cols_attributesV  s    z$BaseColumnInfo.merge_cols_attributes)F)r6   r   r   r   r   rB   unionr   rV   r   rF   r   r   r   r   r   r   r   r   )rQ   r   r     s   

&*c                   s   e Zd Z fddZ  ZS )r   c                sJ   |dkr8| j d k	r8ddlm} ||}| j j| j| t || d S )Nr!   r   )fix_column_name)r]   r   r   columnsZ_rename_columnr!   r`   rh   )rD   r/   rM   r   new_name)rQ   r   r   rh     s
    zMixinInfo.__setattr__)r6   r   r   rh   r   r   r   )rQ   r   r     s   c               @   s   e Zd ZdZedgZdS )r   z&Mixin that gets info.dtype from parentr   N)r6   r   r   r   r   rU   r   r   r   r   r     s   )N)"r   r   r   rw   rK   r|   ior   copyr   	functoolsr   collectionsr   
contextlibr   Znumpyr   r4   r   __all__rA   RuntimeWarningr~   r    r   r
   r	   r1   r8   r   r   r   r   r   r   r   r   <module>   s>   
%0
  ! 4