a
    ߙfbi                     @   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 g d
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ZG dd  d e Z!G d!d" d"e!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 _zdV  W |t _n|t _0 dS )av  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', 'parquet', 'ecsv', 'yaml'
    N)r   _serialize_context)contextZold_context r   6lib/python3.9/site-packages/astropy/utils/data_info.pyserialize_context_as0   s
    r   c                 C   sJ   t | } | jdv r@td| jd}td| jf }|| }n| j}|S )ah  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, `~numpy.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
   E   s    


r
   c                    s    fdd}|S )a4  
    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
    median = 2.5
    max = 4
    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 }t  D ]\}}z$t|tr0t| | }n|| }W n tyV   |d Y q0 z||d W q ttfy   |t| Y q0 qtt |S )Nz--g)	zip
isinstancer   getattr	Exceptionappend	TypeError
ValueErrorr   )datZoutsr!   funcr#   funcsnamesr   r   r-      s    
zdata_info_factory.<locals>.funcr   )r0   r/   r-   r   r.   r   r	   j   s    r	   c                 C   s.   i }|D ] }t | |d}|dur|||< q|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    
r5   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u rfd}t|S )zP
    Get a data object attribute for the ``attributes`` info summary method
    classr   shaper   N )type__name__r
   infor   r7   r'   r   )r,   r3   r4   Zdatshaper   r   r   _get_data_attribute   s    r<   c                   @   s&   e Zd ZdddZdd Zdd ZdS )	InfoAttributeNc                 C   s   || _ || _d S N)r3   default)selfr3   r?   r   r   r   __init__   s    zInfoAttribute.__init__c                 C   s   |d u r| S |j | j| jS r>   )_attrsgetr3   r?   r@   instance	owner_clsr   r   r   __get__   s    zInfoAttribute.__get__c                 C   s    |d u rt d||j| j< d S Ncannot set unbound descriptor)r+   rB   r3   r@   rE   valuer   r   r   __set__   s    zInfoAttribute.__set__)Nr:   
__module____qualname__rA   rG   rL   r   r   r   r   r=      s   
r=   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )ParentAttributec                 C   s
   || _ d S r>   r3   )r@   r3   r   r   r   rA      s    zParentAttribute.__init__c                 C   s   |d u r| S t |j| jS r>   )r'   _parentr3   rD   r   r   r   rG      s    zParentAttribute.__get__c                 C   s$   |d u rt dt|j| j| d S rH   )r+   setattrrR   r3   rJ   r   r   r   rL      s    zParentAttribute.__set__NrM   r   r   r   r   rP      s   rP   c                       s(   e Zd Z fddZ fddZ  ZS )DataInfoMetac                    s   | dg  t | |||S )N	__slots__)
setdefaultsuper__new__)mclsr!   basesdct	__class__r   r   rX      s    zDataInfoMeta.__new__c              	      s   t  ||| | jD ]n}||vrt| |d }|| jv r\d|v rt|tst| |t| q|rjt|trt| |t|| j	
| qd S )Nattrs_from_parent)rW   rA   
attr_namesr'   r^   r&   rP   rS   r=   _attr_defaultsrC   )clsr!   rZ   r[   r3   Zcls_attrr\   r   r   rA      s    

zDataInfoMeta.__init__)r:   rN   rO   rX   rA   __classcell__r   r   r\   r   rT      s   rT   c                       s   e Zd ZdZg dZe Zeg dZde	diZ
e ZdZg dZdZdZd	Zd%ddZedd Zdd Zdd Zdd Zdd Zd&ddZdd Zeeedd eD dZeeedd eD dZd'd!d"Z fd#d$Z  Z S )(r   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
    https://nbviewer.jupyter.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max)r!   unitr   formatdescriptionmetar   O)r   r7   re   rf   rg   r6   )_parent_cls_parent_refrB   r   NFc                 C   s   |r
i | _ d S r>   rB   r@   boundr   r   r   rA   3  s    zDataInfo.__init__c                 C   s6   z|   }W n ty    Y d S 0 |d u r2t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``.)rk   AttributeError)r@   parentr   r   r   rR   :  s    	zDataInfo._parentc                 C   sL   |d u r|| _ | S |jd}|d u r<| jdd }|jd< t||_|S )Nr;   Trn   )rj   __dict__rC   r]   weakrefrefrk   )r@   rE   rF   r;   r   r   r   rG   M  s    zDataInfo.__get__c                 C   s   |d u rt dt|tr| jdd }|jd< |j}|j| ju rR|t|j@ }n||j|j @ }||j	 |j D ]}t
t|||j|< qrntdd S )NrI   Trq   r;   z)info must be set with a DataInfo instance)r+   r&   r   r]   rr   r_   setrB   _attrs_no_copyr^   r   r'   r*   )r@   rE   rK   r;   r_   r3   r   r   r   rL   \  s    
zDataInfo.__set__c                 C   s   | j S r>   rl   r@   r   r   r   __getstate__s  s    zDataInfo.__getstate__c                 C   s
   || _ d S r>   rl   )r@   stater   r   r   __setstate__v  s    zDataInfo.__setstate__c                 C   s   |du r| j }t| j|S )z|Get the values for the parent ``attrs`` and return as a dict.

        By default, uses '_represent_as_dict_attrs'.
        N)_represent_as_dict_attrsr5   rR   )r@   r2   r   r   r   _represent_as_dicty  s    zDataInfo._represent_as_dictc                    s$    fdd| j D }| j|i  S )Nc                    s   g | ]}  |qS r   )pop.0r3   mapr   r   
<listcomp>      z1DataInfo._construct_from_dict.<locals>.<listcomp>)_construct_from_dict_argsrj   )r@   r   argsr   r   r   _construct_from_dict  s    zDataInfo._construct_from_dictc                 C   s   g | ]}t t|d qS )rQ   )r   r<   r~   r   r   r   r     s   zDataInfo.<listcomp>)r0   r/   c                 C   s   g | ]}t td | qS )nan)r'   r   )r   statr   r   r   r     s   
attributesr8   c              	   C   s  |dkrt j}| j}t }|jj}|dur2||d< t|ttfrD|n|g}|D ]}t|t	rt
| d| rzt| d| }ntd|t 8 tD ]}tjdi | q||| W d   qN1 s0    Y  qNt
|drt|j}n8ztt|t|B }W n ty(   d}Y n0 ||d	< zt||d
< W n ttfyZ   Y n0 |du rj|S | D ].\}	}
|
dkrr||	 d|
 tj  qrd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, callable, list of (str or callable)
            Info option, defaults to 'attributes'.
        out : file-like, None
            Output destination, defaults to sys.stdout.  If None then the
            OrderedDict with information attributes is returned

        Returns
        -------
        info : `~collections.OrderedDict` or None
            `~collections.OrderedDict` if out==None else None
        r8   Nr!   Zinfo_summary_z,option={} is not an allowed information typeignoremaskr   n_badr"   z = )r   ) sysstdoutrR   r   r;   r!   r&   listtupler   hasattrr'   r+   rf   warningscatch_warningsIGNORE_WARNINGSfilterwarningsupdater   Zcount_nonzeror   ZisinfZisnanr(   lenr*   
IndexErroritemswriteoslinesep)r@   Zoptionr#   r,   r;   r!   ZoptionsZignore_kwargsr   keyr4   r   r   r   __call__  sF    7

.



zDataInfo.__call__c                    s.   | j d u rt  S t }| j|d | S )N)r#   )rR   rW   __repr__r   r   getvalue)r@   r#   r\   r   r   r     s
    

zDataInfo.__repr__)F)N)r   r8   )!r:   rN   rO   __doc__Z_statsru   r^   r_   r   r   r`   rv   Z_info_summary_attrsrU   r{   r   Z_represent_as_dict_primary_datarA   propertyrR   rG   rL   rx   rz   r|   r   staticmethodr	   Zinfo_summary_attributesZinfo_summary_statsr   r   rb   r   r   r\   r   r     sH   


	
cr   )	metaclassc                       s   e Zd ZdZejddgZeddgZdZ	ddgZ
edd Zejd	d Zd fdd	Z fddZdd Zedd Zejdd Zdd Zdd Zedd Z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.
    parent_tableindicesN_format_funcs_copy_indicesc                 C   s   | j d}t|r| }|S Nr   )rB   rC   callable)r@   rK   r   r   r   r     s    zBaseColumnInfo.parent_tablec                 C   s0   |d u r| j dd  nt|}|| j d< d S r   )rB   r}   rs   rt   )r@   r   r   r   r   r     s    
Fc                    s   t  j|d |ri | _d S )Nrq   )rW   rA   r   rm   r\   r   r   rA   #  s    zBaseColumnInfo.__init__c                    s6   z|j sW d S W n ty"   Y n0 t || d S r>   )r7   ro   rW   rL   rJ   r\   r   r   rL   +  s    
zBaseColumnInfo.__set__c                 c   sL   | j }| jdu rddlm} n| jj}|j}||dddi D ]
}|V  q<dS )zG
        This is a mixin-safe version of Column.iter_str_vals.
        Nr   )	FORMATTERF)rR   r   Zastropy.table.columnr   	formatter_pformat_col_iter)r@   colr   r   Zstr_valr   r   r   iter_str_vals5  s    
zBaseColumnInfo.iter_str_valsc                 C   s   | j dg S Nr   )rB   rV   rw   r   r   r   r   C  s    zBaseColumnInfo.indicesc                 C   s   || j d< d S r   rl   )r@   r   r   r   r   r   K  s    c           	      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| }t||D ]$\}}| j D ]}||| j| qqd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&   slicer   ranger   ndarrayr   r   whereZ
atleast_1dsizer   r%   replacer!   )	r@   indexrK   col_lentkeysr   r4   Z	col_indexr   r   r   adjust_indicesO  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  t d| k}g |j_| jD ]@}|st||r|| }nt|}|  |jj| q|S )	a  
        Given a sliced object, modify its indices
        to correctly represent the slice.

        Parameters
        ----------
        col_slice : `~astropy.table.Column` or mixin
            Sliced object. If not a column, it must be a valid mixin, see
            https://docs.astropy.org/en/stable/table/mixin_columns.html
        item : slice, list, or ndarray
            Slice used to create col_slice
        col_len : int
            Length of original object
        r   )SortedArrayr   Tc                    s   g | ]}|  qS r   r   )r   xitemr   r   r     r   z0BaseColumnInfo.slice_indices.<locals>.<listcomp>r   g333333?)Zastropy.table.sorted_arrayr   r'   r;   r   r&   r   r   r   r   r   r   r   Z	get_slicer   Zreplace_rowsr)   )r@   Z	col_slicer   r   r   Zsmallr   Z	new_indexr   r   r   slice_indicesu  s$    


zBaseColumnInfo.slice_indicesc           
         s   ddl m} fdd} fdd}|| d }| dd D ]}tj|||||d	}q<t| |d
< tdd | D }	t|	dkr|d|	 |d< dur|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)rf   )r   leftrightr#   )r!   r   r   warn_str_func  s    
z;BaseColumnInfo.merge_cols_attributes.<locals>.warn_str_funcc                    s    fddD S )Nc                    s,   i | ]$}t  j|d d ur|t  j|qS r>   )r'   r;   r~   r   r   r   
<dictcomp>  s   zJBaseColumnInfo.merge_cols_attributes.<locals>.getattrs.<locals>.<dictcomp>r   r   )r2   r   r   getattrs  s    z6BaseColumnInfo.merge_cols_attributes.<locals>.getattrsr   N)metadata_conflictsr   r   c                 s   s   | ]}|j d d V  qdS )r   N)r7   )r   r   r   r   r   	<genexpr>  r   z7BaseColumnInfo.merge_cols_attributes.<locals>.<genexpr>zcolumns have different shapesr7   r!   )astropy.table.np_utilsr   r   mergeZcommon_dtyperu   r   r}   )
Zcolsr   r!   r2   r   r   r   r#   r   Zuniq_shapesr   )r2   r!   r   merge_cols_attributes  s     z$BaseColumnInfo.merge_cols_attributesc                 C   s   t d| j ddS )a
  
        Return a list of arrays which can be lexically sorted to represent
        the order of the parent column.

        The base method raises NotImplementedError and must be overridden.

        Returns
        -------
        arrays : list of ndarray
        zcolumn z is not sortableN)NotImplementedErrorr!   rw   r   r   r   get_sortable_arrays  s    z"BaseColumnInfo.get_sortable_arrays)F)r:   rN   rO   r   r   r_   unionru   rv   r   rU   r   r   setterrA   rL   r   r   r   r   r   r   r   rb   r   r   r\   r   r     s*   





&*
:r   c                   @   s&   e Zd Zedd Zejdd ZdS )r   c                 C   s   | j dS )Nr!   )rB   rC   rw   r   r   r   r!     s    zMixinInfo.namec                 C   s>   | j d ur0ddlm} ||}| j j| j| || jd< d S )Nr   )fix_column_namer!   )r   r   r   columnsZ_rename_columnr!   rB   )r@   r!   r   new_namer   r   r   r!     s
    
N)r:   rN   rO   r   r!   r   r   r   r   r   r     s   
r   c                   @   s   e Zd ZdZedgZdS )r   z&Mixin that gets info.dtype from parentr   N)r:   rN   rO   r   ru   r^   r   r   r   r   r     s   r   )N)&r   r   r   r   rs   r   ior   copyr   	functoolsr   collectionsr   
contextlibr   Znumpyr   r8   r   __all__dictRuntimeWarningr   r    r   r
   r	   r5   r<   r=   rP   r9   rT   r   r   r   r   r   r   r   r   <module>   sD   
%3
  y l