U
    e»{jC  ã                   @   s”   d Z ddlZddlZddlZddlmZmZ ddlm	Z	 d 
¡ ZG dd„ deƒZG dd	„ d	ƒZG d
d„ deƒZdd„ Zdd„ Zdd„ Zddd„ZdS )aÏ  
``fitsheader`` is a command line script based on astropy.io.fits for printing
the header(s) of one or more FITS file(s) to the standard output in a human-
readable format.

Example uses of fitsheader:

1. Print the header of all the HDUs of a .fits file::

    $ fitsheader filename.fits

2. Print the header of the third and fifth HDU extension::

    $ fitsheader --extension 3 --extension 5 filename.fits

3. Print the header of a named extension, e.g. select the HDU containing
   keywords EXTNAME='SCI' and EXTVER='2'::

    $ fitsheader --extension "SCI,2" filename.fits

4. Print only specific keywords::

    $ fitsheader --keyword BITPIX --keyword NAXIS filename.fits

5. Print keywords NAXIS, NAXIS1, NAXIS2, etc using a wildcard::

    $ fitsheader --keyword NAXIS* filename.fits

6. Dump the header keywords of all the files in the current directory into a
   machine-readable csv file::

    $ fitsheader --table ascii.csv *.fits > keywords.csv

7. Specify hierarchical keywords with the dotted or spaced notation::

    $ fitsheader --keyword ESO.INS.ID filename.fits
    $ fitsheader --keyword "ESO INS ID" filename.fits

8. Compare the headers of different fits files, following ESO's ``fitsort``
   format::

    $ fitsheader --fitsort --extension 0 --keyword ESO.INS.ID *.fits

9. Same as above, sorting the output along a specified keyword::

    $ fitsheader -f -s DATE-OBS -e 0 -k DATE-OBS -k ESO.INS.ID *.fits

10. Sort first by OBJECT, then DATE-OBS::

    $ fitsheader -f -s OBJECT -s DATE-OBS *.fits

Note that compressed images (HDUs of type
:class:`~astropy.io.fits.CompImageHDU`) really have two headers: a real
BINTABLE header to describe the compressed data, and a fake IMAGE header
representing the image that was compressed. Astropy returns the latter by
default. You must supply the ``--compressed`` option if you require the real
header that describes the compression.

With Astropy installed, please run ``fitsheader --help`` to see the full usage
documentation.
é    N)Ú__version__Úlog)Úfitsa•  
Print the header(s) of a FITS file. Optional arguments allow the desired
extension(s), keyword(s), and output format to be specified.
Note that in the case of a compressed image, the decompressed header is
shown by default.

This script is part of the Astropy package. See
https://docs.astropy.org/en/latest/io/fits/usage/scripts.html#module-astropy.io.fits.scripts.fitsheader
for further documentation.
c                   @   s   e Zd ZdZdS )ÚExtensionNotFoundExceptionz@Raised if an HDU extension requested by the user does not exist.N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r
   r
   úa/var/www/html/bwave/python/venv/lib/python3.8/site-packages/astropy/io/fits/scripts/fitsheader.pyr   T   s   r   c                   @   s<   e Zd ZdZddd„Zddd„Zd	d
„ Zdd„ Zdd„ ZdS )ÚHeaderFormattera:  Class to format the header(s) of a FITS file for display by the
    `fitsheader` tool; essentially a wrapper around a `HDUList` object.

    Example usage:
    fmt = HeaderFormatter('/path/to/file.fits')
    print(fmt.parse(extensions=[0, 3], keywords=['NAXIS', 'BITPIX']))

    Parameters
    ----------
    filename : str
        Path to a single FITS file.
    verbose : bool
        Verbose flag, to show more information about missing extensions,
        keywords, etc.

    Raises
    ------
    OSError
        If `filename` does not exist or cannot be read.
    Tc                 C   s   || _ || _t |¡| _d S ©N)ÚfilenameÚverboser   ÚopenÚ_hdulist)Úselfr   r   r
   r
   r   Ú__init__p   s    zHeaderFormatter.__init__NFc           	   	   C   sª   |dkrt t| jƒƒ}n„g }|D ]z}z| t|ƒ¡ W q  tk
r˜   | d¡}t|ƒdkrŠd |dd… ¡}t|d ƒ}| ||f¡ n
| |¡ Y q X q |  |||¡S )aÎ  Returns the FITS file header(s) in a readable format.

        Parameters
        ----------
        extensions : list of int or str, optional
            Format only specific HDU(s), identified by number or name.
            The name can be composed of the "EXTNAME" or "EXTNAME,EXTVER"
            keywords.

        keywords : list of str, optional
            Keywords for which the value(s) should be returned.
            If not specified, then the entire header is returned.

        compressed : bool, optional
            If True, shows the header describing the compression, rather than
            the header obtained after decompression. (Affects FITS files
            containing `CompImageHDU` extensions only.)

        Returns
        -------
        formatted_header : str or astropy.table.Table
            Traditional 80-char wide format in the case of `HeaderFormatter`;
            an Astropy Table object in the case of `TableHeaderFormatter`.
        Nú,é   r   éÿÿÿÿ)	ÚrangeÚlenr   ÚappendÚintÚ
ValueErrorÚsplitÚjoinÚ_parse_internal)	r   Ú
extensionsÚkeywordsÚ
compressedÚhdukeysÚextÚpartsZextnameZextverr
   r
   r   Úparseu   s    
zHeaderFormatter.parsec           	   	   C   s’   g }t |ƒD ]z\}}z|  |||¡}W n tk
r>   Y qY nX |dkrR| d¡ | d|› d| j› d�¡ |D ]}| |› d�¡ qpqd |¡S )zEThe meat of the formatting; in a separate method to allow overriding.r   Ú
z# HDU z in z:
Ú )Ú	enumerateÚ
_get_cardsr   r   r   r   )	r   r"   r    r!   ÚresultÚidxÚhduÚcardsÚcr
   r
   r   r   ¤   s    

zHeaderFormatter._parse_internalc           	      C   sê   z"|r| j | j}n| j | j}W nB ttfk
rd   | j› d|› d�}| jrXt |¡ t	|ƒ‚Y nX |sr|j
}ntg }|D ]j}z2|j
| }t|tjjƒr¤| |¡ n
| |¡ W qz tk
râ   | jrÞt dj| j||d�¡ Y qzX qz|S )a§  Returns a list of `astropy.io.fits.card.Card` objects.

        This function will return the desired header cards, taking into
        account the user's preference to see the compressed or uncompressed
        version.

        Parameters
        ----------
        hdukey : int or str
            Key of a single HDU in the HDUList.

        keywords : list of str, optional
            Keywords for which the cards should be returned.

        compressed : bool, optional
            If True, shows the header describing the compression.

        Raises
        ------
        ExtensionNotFoundException
            If the hdukey does not correspond to an extension.
        z: Extension z not found.z2{filename} (HDU {hdukey}): Keyword {kw} not found.)r   ÚhdukeyÚkw)r   Z_headerÚheaderÚ
IndexErrorÚKeyErrorr   r   r   Úwarningr   r-   Ú
isinstancer   ÚcardZCardr   ÚextendÚformat)	r   r/   r    r!   r1   Úmessager-   r0   Zcrdr
   r
   r   r)   ´   s8    

  ÿÿzHeaderFormatter._get_cardsc                 C   s   | j  ¡  d S r   )r   Úclose)r   r
   r
   r   r:   í   s    zHeaderFormatter.close)T)NNF)	r   r   r   r	   r   r%   r   r)   r:   r
   r
   r
   r   r   Z   s   

/9r   c                   @   s   e Zd ZdZdd„ ZdS )ÚTableHeaderFormattera  Class to convert the header(s) of a FITS file into a Table object.
    The table returned by the `parse` method will contain four columns:
    filename, hdu, keyword, and value.

    Subclassed from HeaderFormatter, which contains the meat of the formatting.
    c              	   C   sx   g }|D ]P}z6|   |||¡D ]"}| | j||jt|jƒdœ¡ qW q tk
rV   Y qX q|rtddlm} | 	|¡S dS )z6Method called by the parse method in the parent class.)r   r,   ÚkeywordÚvaluer   ©ÚtableN)
r)   r   r   r<   Ústrr=   r   Úastropyr?   ÚTable)r   r"   r    r!   Z	tablerowsr,   r6   r?   r
   r
   r   r   ù   s"    üÿ

z$TableHeaderFormatter._parse_internalN)r   r   r   r	   r   r
   r
   r
   r   r;   ñ   s   r;   c                 C   sž   t | jƒD ]Ž\}}|dkr&| js&tƒ  d}z^z(t|ƒ}t| | j| j| j¡dd� W n0 t	k
r„ } zt
 t|ƒ¡ W 5 d}~X Y nX W 5 |r–| ¡  X q
dS )z¾Prints FITS header(s) using the traditional 80-char format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    r   Nr'   )Úend)r(   r   r<   Úprintr:   r   r%   r   r!   ÚOSErrorr   Úerrorr@   )Úargsr+   r   Ú	formatterÚer
   r
   r   Úprint_headers_traditional  s     ÿ
$rJ   c                 C   sÚ   g }| j D ]|}d}zdz.t|ƒ}| | j| j| j¡}|r@| |¡ W n0 tk
rr } zt	 
t|ƒ¡ W 5 d}~X Y nX W 5 |r„| ¡  X q
t|ƒdkr˜dS t|ƒdkr®|d }nddlm} | |¡}|jtj| jd� dS )z¼Prints FITS header(s) in a machine-readable table format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    Nr   Fr   r>   )r8   )r   r:   r;   r%   r   r<   r!   r   rE   r   rF   r@   r   rA   r?   ÚvstackÚwriteÚsysÚstdout)rG   Útablesr   rH   ÚtblrI   Úresulting_tabler?   r
   r
   r   Úprint_headers_as_table*  s&    
$

rR   c                 C   s  ddl m} g }| jD ]ª}d}z’z\t|dd�}| | j| j| j¡}|r^|t	 
|d dk¡ }n|j|ggdd	�}| |¡ W n0 tk
r¬ } zt t|ƒ¡ W 5 d}~X Y nX W 5 |r¾| ¡  X qt|ƒdkrÒdS t|ƒd
krè|d }n
| |¡}|d }t	j |¡�r| ¡ }tt	 |¡ƒd
k�rX|D ](}	| dd„ |	D ƒ¡}
|	j|
dd� �q(d}nd}g }|D ]x}	|j|	d d gdd�g}d|	jk�rÊ|	D ]6}|d dk�r¨�q’| |j|d g|| d�¡ �q’| | |¡¡ �qd| |¡}| j�rü| | j¡ |jddd� dS )zÞPrints FITS header(s) with keywords as columns.

    This follows the dfits+fitsort format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    r   r>   NF)r   r<   r'   )r   )Únamesr   r,   c                 S   s"   g | ]}|d  › d|d › �‘qS )r,   ú:r<   r
   )Ú.0Úrowr
   r
   r   Ú
<listcomp>{  s     z/print_headers_as_comparison.<locals>.<listcomp>zhdu+keyword)Únamer   r=   )ÚCOMMENTZHISTORYr   )Ú	max_linesÚ	max_width)rA   r?   r   r:   r;   r%   r   r<   r!   ÚnpÚwhererB   r   rE   r   rF   r@   r   rK   ÚmaZisMaskedArrayÚuniqueÚColumnÚ
add_columnZcolnamesÚsortÚpprint)rG   r?   rO   r   rH   rP   rI   rQ   ZhdusÚtabZ
new_columnZkeyword_column_nameZfinal_tablesZfinal_tablerV   r
   r
   r   Úprint_headers_as_comparisonN  sX    

$

ÿ
re   c                 C   sp  t jtt jd�}|jdddt› �d� |jdddd	d
dd� |jdddd	tdd� | ¡ }|jddddddd� |jddddd� |jddd d	td!d� |jd"d#dd$d� |jd%d&d'd(� | | ¡} | j	d)krÔd*| _	| j
�r
d+d,„ | j
D ƒ| _
| j�s
t d-¡ t d.¡ | j�r$d/d,„ | jD ƒ| _z0| j	�r8t| ƒ n| j�rJt| ƒ nt| ƒ W n tk
�rj   Y nX d)S )0z<This is the main function called by the `fitsheader` script.)ÚdescriptionÚformatter_classz	--versionÚversionz	%(prog)s )Úactionrh   z-ez--extensionZHDUr   r   zdspecify the extension by name or number; this argument can be repeated to select multiple extensions)Úmetavarri   ÚdestÚhelpz-kz	--keywordZKEYWORDzespecify a keyword; this argument can be repeated to select multiple keywords; also supports wildcards)rj   ri   Útyperl   z-tz--tableú?FZFORMATzžprint the header(s) in machine-readable table format; the default format is "ascii.fixed_width" (can be "ascii.csv", "ascii.html", "ascii.latex", "fits", etc))ÚnargsÚdefaultrj   rl   z-fz	--fitsortÚ
store_truezYprint the headers as a table with each unique keyword in a given column (fitsort format) )ri   rl   z-sz--sortZSORT_KEYWORDz|sort output by the specified header keywords, can be repeated to sort by multiple keywords; Only supported with -f/--fitsortz-cz--compressedzdfor compressed image data, show the true header which describes the compression rather than the datar   ú+z2path to one or more files; wildcards are supported)ro   rl   Nzascii.fixed_widthc                 S   s   g | ]}|  d d¡‘qS ©Ú.ú ©Úreplace©rU   Úkeyr
   r
   r   rW   ò  s     zmain.<locals>.<listcomp>zISorting with -s/--sort is only supported in conjunction with -f/--fitsorté   c                 S   s   g | ]}|  d d¡‘qS rs   rv   rx   r
   r
   r   rW   ü  s     )ÚargparseÚArgumentParserÚDESCRIPTIONÚRawDescriptionHelpFormatterÚadd_argumentr   r@   Úadd_mutually_exclusive_groupÚ
parse_argsr?   rb   Zfitsortr   rF   rM   Úexitr<   rR   re   rJ   rE   )rG   ÚparserZ
mode_groupr
   r
   r   Úmain•  sž     ÿ  ÿùùùû	ùû
ý

ÿ


r„   )N)r	   r{   rM   Únumpyr\   rA   r   r   Z
astropy.ior   Ústripr}   Ú	Exceptionr   r   r;   rJ   rR   re   r„   r
   r
   r
   r   Ú<module>   s   >  $G