B
    dl              	   @   sZ  d Z ddlZddlZddlmZ ddlmZmZm	Z	m
Z
 ddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ dddgZee	e
fZdd eD Zdd eD Zdadd Zdd ZG dd deZdddgZeddddgZ eddd d!gZ!d"d# Z"d*d'dZ#d+d(dZ$e%e4 e&d)ee# e'd)ee$ e(d)eej)j* W dQ R X dS ),z.This module implements the base CCDData class.    N   )NDDataArray)StdDevUncertaintyNDUncertaintyVarianceUncertaintyInverseVariance)fitsregistry)units)log)WCS)sharedmethodCCDDatafits_ccddata_readerfits_ccddata_writerc             C   s   i | ]}||j qS  )__name__).0clsr   r   c/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/astropy/nddata/ccddata.py
<dictcomp>   s    r   c             C   s   i | ]}|j |qS r   )r   )r   r   r   r   r   r      s    Tc                s    fdd}|S )a  Decorator factory which temporarly disables the need for a unit when
    creating a new CCDData instance. The final result must have a unit.

    Parameters
    ----------
    op : function
        The function to apply. Supported are:

        - ``np.add``
        - ``np.subtract``
        - ``np.multiply``
        - ``np.true_divide``

    Notes
    -----
    Should only be used on CCDData ``add``, ``subtract``, ``divide`` or
    ``multiply`` because only these methods from NDArithmeticMixin are
    overwritten.
    c                s&   d fdd	}d| j  d|_t|S )Nc                s$   da | j ||f|}da ||S )NFT)_config_ccd_requires_unitZ_prepare_then_do_arithmetic	__class__)selfoperandZoperand2kwargsresult)opr   r   inner3   s
    
z-_arithmetic.<locals>.decorator.<locals>.innerz&See `astropy.nddata.NDArithmeticMixin.z`.)N)r   __doc__r   )funcr   )r   r   r   	decorator2   s    z_arithmetic.<locals>.decoratorr   )r   r!   r   )r   r   _arithmetic   s    r"   c             C   sN   | t kr||kS | tkr$||d kS | tkr<|d|d  kS td|  d S )N   r   zunsupported uncertainty type: )r   r   r   
ValueError)Zuncertainty_typeunitZparent_unitr   r   r   &_uncertainty_unit_equivalent_to_parent@   s    r&   c                   s  e Zd ZdZ fddZdd Zedd Zejdd Zed	d
 Z	e	jdd
 Z	edd Z
e
jdd Z
edd Zejdd Zedd Zejdd Zd!ddZdd ZeejejZeejejZeejejZeejejZdd Zejej ejejd Z  ZS )"r   a?  A class describing basic CCD data.

    The CCDData class is based on the NDData object and includes a data array,
    uncertainty frame, mask frame, flag frame, meta data, units, and WCS
    information for a single CCD image.

    Parameters
    -----------
    data : `~astropy.nddata.CCDData`-like or array-like
        The actual data contained in this `~astropy.nddata.CCDData` object.
        Note that the data will always be saved by *reference*, so you should
        make a copy of the ``data`` before passing it in if that's the desired
        behavior.

    uncertainty : `~astropy.nddata.StdDevUncertainty`,             `~astropy.nddata.VarianceUncertainty`,             `~astropy.nddata.InverseVariance`, `numpy.ndarray` or             None, optional
        Uncertainties on the data. If the uncertainty is a `numpy.ndarray`, it
        it assumed to be, and stored as, a `~astropy.nddata.StdDevUncertainty`.
        Default is ``None``.

    mask : `numpy.ndarray` or None, optional
        Mask for the data, given as a boolean Numpy array with a shape
        matching that of the data. The values must be `False` where
        the data is *valid* and `True` when it is not (like Numpy
        masked arrays). If ``data`` is a numpy masked array, providing
        ``mask`` here will causes the mask from the masked array to be
        ignored.
        Default is ``None``.

    flags : `numpy.ndarray` or `~astropy.nddata.FlagCollection` or None,             optional
        Flags giving information about each pixel. These can be specified
        either as a Numpy array of any type with a shape matching that of the
        data, or as a `~astropy.nddata.FlagCollection` instance which has a
        shape matching that of the data.
        Default is ``None``.

    wcs : `~astropy.wcs.WCS` or None, optional
        WCS-object containing the world coordinate system for the data.
        Default is ``None``.

    meta : dict-like object or None, optional
        Metadata for this object. "Metadata" here means all information that
        is included with this object but not part of any other attribute
        of this particular object, e.g. creation date, unique identifier,
        simulation parameters, exposure time, telescope name, etc.

    unit : `~astropy.units.Unit` or str, optional
        The units of the data.
        Default is ``None``.

        .. warning::

            If the unit is ``None`` or not otherwise specified it will raise a
            ``ValueError``

    Raises
    ------
    ValueError
        If the ``uncertainty`` or ``mask`` inputs cannot be broadcast (e.g.,
        match shape) onto ``data``.

    Methods
    -------
    read(\*args, \**kwargs)
        ``Classmethod`` to create an CCDData instance based on a ``FITS`` file.
        This method uses :func:`fits_ccddata_reader` with the provided
        parameters.
    write(\*args, \**kwargs)
        Writes the contents of the CCDData instance into a new ``FITS`` file.
        This method uses :func:`fits_ccddata_writer` with the provided
        parameters.

    Attributes
    ----------
    known_invalid_fits_unit_strings
        A dictionary that maps commonly-used fits unit name strings that are
        technically invalid to the correct valid unit type (or unit string).
        This is primarily for variant names like "ELECTRONS/S" which are not
        formally valid, but are unambiguous and frequently enough encountered
        that it is convenient to map them to the correct unit.

    Notes
    -----
    `~astropy.nddata.CCDData` objects can be easily converted to a regular
     Numpy array using `numpy.asarray`.

    For example::

        >>> from astropy.nddata import CCDData
        >>> import numpy as np
        >>> x = CCDData([1,2,3], unit='adu')
        >>> np.asarray(x)
        array([1, 2, 3])

    This is useful, for example, when plotting a 2D image using
    matplotlib.

        >>> from astropy.nddata import CCDData
        >>> from matplotlib import pyplot as plt   # doctest: +SKIP
        >>> x = CCDData([[1,2,3], [4,5,6]], unit='adu')
        >>> plt.imshow(x)   # doctest: +SKIP

    c                sz   d|kr| dd |d< d|kr(tdt j|| | jd k	r`| jj}t|tsZtd|| _t	rv| j
d krvtdd S )Nmetaheaderz can't have both header and meta.zthe wcs must be a WCS instance.z%a unit for CCDData must be specified.)popr$   super__init___wcsZlow_level_wcs
isinstancer   	TypeErrorr   r%   )r   argskwdZllwcs)r   r   r   r+      s    

zCCDData.__init__c          
   C   sL   | j dkrdS y
| j | S  tk
rF } z| || W dd}~X Y nX dS )z|
        Override the WCS slicing behaviour so that the wcs attribute continues
        to be an `astropy.wcs.WCS`.
        N)wcs	ExceptionZ_handle_wcs_slicing_error)r   itemerrr   r   r   
_slice_wcs   s    

zCCDData._slice_wcsc             C   s   | j S )N)_data)r   r   r   r   data   s    zCCDData.datac             C   s
   || _ d S )N)r6   )r   valuer   r   r   r7      s    c             C   s   | j S )N)r,   )r   r   r   r   r1      s    zCCDData.wcsc             C   s   t |tstd|| _d S )Nzthe wcs must be a WCS instance.)r-   r   r.   r,   )r   r8   r   r   r   r1      s    
c             C   s   | j S )N)_unit)r   r   r   r   r%      s    zCCDData.unitc             C   s   t || _d S )N)uUnitr9   )r   r8   r   r   r   r%      s    c             C   s   | j S )N)_meta)r   r   r   r   r(      s    zCCDData.headerc             C   s
   || _ d S )N)r'   )r   r8   r   r   r   r(      s    c             C   s   | j S )N)_uncertainty)r   r   r   r   uncertainty   s    zCCDData.uncertaintyc             C   s   |d k	rt |tr8t|dd d k	r0|j|dd}|| _n>t |tjrn|j| jkrXtdt	|| _t
d ntd| | j_n|| _d S )NZ_parent_nddataF)copyz)uncertainty must have same shape as data.zCarray provided for uncertainty; assuming it is a StdDevUncertainty.zKuncertainty must be an instance of a NDUncertainty object or a numpy array.)r-   r   getattrr   r=   npZndarrayshaper$   r   r   infor.   Zparent_nddata)r   r8   r   r   r   r>      s    


MASKUNCERTNTUTYPEc             C   s  t | jtjr| j }n>tdgt dd}x"| j D ]\}}	|||	 q:W |j}| jt	j
k	rr| j |d< | jr| jj|d}
|j|
ddd t| j|g}|r| jd	k	rt| jd
stdtj| jtj|d}|| |r| jd	k	r| jj}|tkrtdtt| }t }|||< t| jdrl| jjd	k	rlt|| jj| jsltdtj| jj||d}|| |r| j rt!dt"|}|S )a1  Creates an HDUList object from a CCDData object.

        Parameters
        ----------
        hdu_mask, hdu_uncertainty, hdu_flags : str or None, optional
            If it is a string append this attribute to the HDUList as
            `~astropy.io.fits.ImageHDU` with the string as extension name.
            Flags are not supported at this time. If ``None`` this attribute
            is not appended.
            Default is ``'MASK'`` for mask, ``'UNCERT'`` for uncertainty and
            ``None`` for flags.

        wcs_relax : bool
            Value of the ``relax`` parameter to use in converting the WCS to a
            FITS header using `~astropy.wcs.WCS.to_header`. The common
            ``CTYPE`` ``RA---TAN-SIP`` and ``DEC--TAN-SIP`` requires
            ``relax=True`` for the ``-SIP`` part of the ``CTYPE`` to be
            preserved.

        key_uncertainty_type : str, optional
            The header key name for the class name of the uncertainty (if any)
            that is used to store the uncertainty type in the uncertainty hdu.
            Default is ``UTYPE``.

            .. versionadded:: 3.1

        Raises
        -------
        ValueError
            - If ``self.mask`` is set but not a `numpy.ndarray`.
            - If ``self.uncertainty`` is set but not a astropy uncertainty type.
            - If ``self.uncertainty`` is set but has another unit then
              ``self.data``.

        NotImplementedError
            Saving flags is not supported.

        Returns
        -------
        hdulist : `~astropy.io.fits.HDUList`
        r   adu)r'   r%   bunit)relaxFT)Z	useblanksupdateNrB   z'only a numpy.ndarray mask can be saved.)namez+only uncertainties of type {} can be saved.r%   zhsaving uncertainties with a unit that is not equivalent to the unit from the data unit is not supported.z8adding the flags to a HDU is not supported at this time.)#r-   r(   r   Headerr?   r   items_insert_in_metadata_fits_safer%   r:   Zdimensionless_unscaledZ	to_stringr1   	to_headerextendZ
PrimaryHDUr7   maskhasattrr$   ImageHDUastyperA   Zuint8appendr>   r   _known_uncertaintiesformat_unc_cls_to_namer&   arrayflagsNotImplementedErrorZHDUList)r   hdu_maskhdu_uncertainty	hdu_flagsZ	wcs_relaxkey_uncertainty_typer(   Z	dummy_ccdkv
wcs_headerhdusZhduMaskZuncertainty_clsZuncertainty_nameZhdr_uncertaintyZ	hduUncertZhdulistr   r   r   to_hdu  sL    +



zCCDData.to_hduc             C   s   | j | ddS )z6
        Return a copy of the CCDData object.
        T)r?   )r   )r   r   r   r   r?     s    zCCDData.copyc             C   s\   t |dkrNt |dkrN|dd }|d| f| jd|  < || j|< n
|| j|< dS )a  
        Insert key/value pair into metadata in a way that FITS can serialize.

        Parameters
        ----------
        key : str
            Key to be inserted in dictionary.

        value : str or None
            Value to be inserted.

        Notes
        -----
        This addresses a shortcoming of the FITS standard. There are length
        restrictions on both the ``key`` (8 characters) and ``value`` (72
        characters) in the FITS standard. There is a convention for handling
        long keywords and a convention for handling long values, but the
        two conventions cannot be used at the same time.

        This addresses that case by checking the length of the ``key`` and
        ``value`` and, if necessary, shortening the key.
           H   NzShortened name for z	HIERARCH )lenr'   upper)r   keyr8   Z
short_namer   r   r   rN     s
    z%CCDData._insert_in_metadata_fits_safe)zELECTRONS/SZ	ELECTRONSZ	electrons)rD   rE   NTrF   )r   
__module____qualname__r   r+   r5   propertyr7   setterr1   r%   r(   r>   rd   r?   r"   rA   addr   subtractmultiplyZtrue_dividedividerN   r:   Zelectronsknown_invalid_fits_unit_strings__classcell__r   r   )r   r   r   J   s0   j 
{!
zJD-OBSzMJD-OBSzDATE-OBSZPC1_1ZPC1_2ZPC2_1ZPC2_2ZCD1_1ZCD1_2ZCD2_1ZCD2_2c          
   C   sR  yt | }W nB tk
rN } z$tdt|jt| | dfS d}~X Y nX |jj	d sd| dfS | 
 }|jdd}x"|D ]}|tkr~|j|dd q~W tt|@ rtt|@ rxtD ]}|j|dd qW |jdk	rJd}dd	d
dg}x\|D ]T}	|j|	  d}
x8tjt|
ddD ]"\}}|j||	||dd q W qW ||fS )z
    Generate a WCS object from a header and remove the WCS-specific
    keywords from the header.

    Parameters
    ----------

    hdr : astropy.io.fits.header or other dict-like

    Returns
    -------

    new_header, wcs
    zOAn exception happened while extracting WCS informations from the Header.
{}: {}Nr   T)rI   )Zignore_missingz{}_{}_{}ABZAPZBP_orderr#   )repeat)r   r2   r   rC   rW   typer   strr1   ctyper?   rO   _KEEP_THESE_KEYWORDS_IN_HEADERremove_PCsset_CDssip__getattribute__lower	itertoolsproductrange)hdrr1   excZnew_hdrrb   r`   cdkeywordZpolynomialsZpolyorderijr   r   r   _generate_wcs_and_update_header  s2    


r   rE   rD   rF   c          	   K   sZ  ddd}x:|  D ].\}	}
|	|krd|	 d}td||
gqW tj| f|}|| j}|dk	r||kr|| }|j|d}t|t}||j	}nd}|dk	r||kr|| j	
tj}nd}|dk	r||krtd	|d
krz|| j	dkrzxztt|D ]j}||| d dkr||d d
kr|}|| j }|j|dd |}td| d P qW d|kr|d }|  dkr| }nd}|r|dkr
y&tj}||kr|| }t|}W n$ tk
r   td|Y nX ntd|| |p$|}t|\}}t|| j	|||||d}W dQ R X |S )a;  
    Generate a CCDData object from a FITS file.

    Parameters
    ----------
    filename : str
        Name of fits file.

    hdu : int, optional
        FITS extension from which CCDData should be initialized. If zero and
        and no data in the primary extension, it will search for the first
        extension with data. The header will be added to the primary header.
        Default is ``0``.

    unit : `~astropy.units.Unit`, optional
        Units of the image data. If this argument is provided and there is a
        unit for the image in the FITS header (the keyword ``BUNIT`` is used
        as the unit, if present), this argument is used for the unit.
        Default is ``None``.

    hdu_uncertainty : str or None, optional
        FITS extension from which the uncertainty should be initialized. If the
        extension does not exist the uncertainty of the CCDData is ``None``.
        Default is ``'UNCERT'``.

    hdu_mask : str or None, optional
        FITS extension from which the mask should be initialized. If the
        extension does not exist the mask of the CCDData is ``None``.
        Default is ``'MASK'``.

    hdu_flags : str or None, optional
        Currently not implemented.
        Default is ``None``.

    key_uncertainty_type : str, optional
        The header key name where the class name of the uncertainty  is stored
        in the hdu of the uncertainty (if any).
        Default is ``UTYPE``.

        .. versionadded:: 3.1

    kwd :
        Any additional keyword parameters are passed through to the FITS reader
        in :mod:`astropy.io.fits`; see Notes for additional discussion.

    Notes
    -----
    FITS files that contained scaled data (e.g. unsigned integer images) will
    be scaled and the keywords used to manage scaled data in
    :mod:`astropy.io.fits` are disabled.
    zImage data must be scaled.z#Scale information is not preserved.)Zdo_not_scale_image_dataZ
scale_backzunsupported keyword: . NNonez)loading flags is currently not supported.r      rS   ZdatSpanT)uniquez!first HDU with data is extension rH   rG   zThe Header value for the key BUNIT ({}) cannot be interpreted as valid unit. To successfully read the file as CCDData you can pass in a valid `unit` argument explicitly or change the header of the FITS file before reading it.zTusing the unit {} passed to the FITS reader instead of the unit {} in the FITS file.)r'   r%   rQ   r>   r1   )rM   r.   joinr   openr(   get_unc_name_to_clsr   r7   rT   rA   Zbool_r[   r   rg   rC   Zfileinfor?   rP   r   stripr   r   rs   r:   r;   r$   rW   r   )filenamehdur%   r]   r\   r^   r_   r0   Zunsupport_open_keywordsri   msgprefixrc   r   Zunc_hduZstored_unc_nameZunc_typer>   rQ   r   Zcomb_hdrZfits_unit_stringZkifusZuse_unitr1   ccd_datar   r   r   r     sh    7






c             K   s$   | j ||||d}|j|f| dS )a  
    Write CCDData object to FITS file.

    Parameters
    ----------
    filename : str
        Name of file.

    hdu_mask, hdu_uncertainty, hdu_flags : str or None, optional
        If it is a string append this attribute to the HDUList as
        `~astropy.io.fits.ImageHDU` with the string as extension name.
        Flags are not supported at this time. If ``None`` this attribute
        is not appended.
        Default is ``'MASK'`` for mask, ``'UNCERT'`` for uncertainty and
        ``None`` for flags.

    key_uncertainty_type : str, optional
        The header key name for the class name of the uncertainty (if any)
        that is used to store the uncertainty type in the uncertainty hdu.
        Default is ``UTYPE``.

        .. versionadded:: 3.1

    kwd :
        All additional keywords are passed to :py:mod:`astropy.io.fits`

    Raises
    -------
    ValueError
        - If ``self.mask`` is set but not a `numpy.ndarray`.
        - If ``self.uncertainty`` is set but not a
          `~astropy.nddata.StdDevUncertainty`.
        - If ``self.uncertainty`` is set but has another unit then
          ``self.data``.

    NotImplementedError
        Saving flags is not supported.
    )r\   r]   r_   r^   N)rd   Zwriteto)r   r   r\   r]   r^   r_   r0   r   r   r   r   r     s    )
r   )r   NrE   rD   NrF   )rD   rE   NrF   )+r   r   numpyrA   compatr   Znduncertaintyr   r   r   r   Z
astropy.ior   r	   Zastropyr
   r:   r   Zastropy.wcsr   Zastropy.utils.decoratorsr   __all__rV   r   rX   r   r"   r&   r   r|   r   r~   r   r   r   r   Zdelay_doc_updatesZregister_readerZregister_writerZregister_identifierconnectZis_fitsr   r   r   r   <module>   sF   

"
  wH  
  
-