
    HR-eMB                         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e          Z G d d	          Z G d
 de          Zd Zd Zd Z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                       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__     Blib/python3.11/site-packages/astropy/io/fits/scripts/fitsheader.pyr   r   T   s        JJDr   r   c                   4    e Zd ZdZd
dZddZd Zd Z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                 T    || _         || _        t          j        |          | _        d S N)filenameverboser   open_hdulist)selfr   r   s      r   __init__zHeaderFormatter.__init__p   s%     	(++r   NFc                    |"t          t          | j                            }ng }|D ]}	 |                    t	          |                     &# t
          $ r |                    d          }t          |          dk    rJd                    |dd                   }t	          |d                   }|                    ||f           n|                    |           Y w xY w|                     |||          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partsextnameextvers	            r   parsezHeaderFormatter.parseu   s    4 C..//GGG! , ,,NN3s88,,,,! , , ,IIcNNE5zzA~~"%((52;"7"7!$U2Y'89999s+++, ##GXzBBBs   "ABC#"C#c                 ^   g }t          |          D ]\  }}	 |                     |||          }n# t          $ r Y *w xY w|dk    r|                    d           |                    d| d| j         d           |D ]}|                    | d           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cs	            r   r$   zHeaderFormatter._parse_internal   s    !'** 
	( 
	(HCXzBB-    Qwwd###MM>3>>DM>>>??? ( (hhh''''(wwvs   0
==c           
      4   	 |r| j         |         j        }n| j         |         j        }nL# t          t          f$ r8 | j         d| d}| j        rt          j        |           t          |          w xY w|s|j
        }ng }|D ]}	 |j
        |         }t          |t          j        j                  r|                    |           n|                    |           [# t          $ r, | j        r"t          j        | j         d| d| d           Y w xY w|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.z (HDU z): Keyword )r   _headerheader
IndexErrorKeyErrorr   r   r   warningr   r6   
isinstancer   cardCardr   extend)	r   hdukeyr&   r'   r:   messager6   kwcrds	            r   r2   zHeaderFormatter._get_cards   sh   0	6 6 v.6v.5H% 	6 	6 	6GGFGGGG| %G$$$,W555		6  	LEEE  
 ,r*C!#ty~66 *S))))S)))   | #}VVFVVrVVV  
 s   '* A	A3AC3DDc                 8    | j                                          d S r   )r   close)r   s    r   rG   zHeaderFormatter.close   s    r   )T)NNF)	r   r	   r
   r   r   r-   r$   r2   rG   r   r   r   r   r   Z   sy         *, , , ,
-C -C -C -C^   5 5 5n    r   r   c                       e Zd ZdZ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           
         g }|D ]c}	 |                      |||          D ]8}|                    | j        ||j        t	          |j                  d           9T# t          $ r Y `w xY w|rddlm} |	                    |          S dS )z6Method called by the parse method in the parent class.)r   r5   keywordvaluer   tableN)
r2   r   r   rK   strrL   r   astropyrN   Table)r   r(   r&   r'   	tablerowsr5   r?   rN   s           r   r$   z$TableHeaderFormatter._parse_internal   s    	 	 	C OOC:FF  D$$(,#&'+|%(__	     .     	*%%%%%%;;y)))ts   AA
A&%A&N)r   r	   r
   r   r$   r   r   r   rI   rI      s-             r   rI   c                    t          | j                  D ]\  }}|dk    r| j        st                       d}	 t	          |          }t          |                    | j        | j        | j                  d           n8# t          $ r+}t          j
        t          |                     Y d}~nd}~ww xY w|r|                                 # |r|                                 w w xY wdS )zPrints FITS header(s) using the traditional 80-char format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    r   Nr0   )end)r1   r   rK   printr   r-   r%   r'   OSErrorr   errorrO   rG   )argsr4   r   	formatteres        r   print_headers_traditionalr[     s    #4=11 " "X774<7GGG			"'11ItOOUW      	 	 	Ic!ff	  "!!!  "!!!!"" "s0   AA=<C=
B2!B-(C-B22CC%c                 v   g }| j         D ]}d}	 t          |          }|                    | j        | j        | j                  }|r|                    |           n8# t          $ r+}t          j	        t          |                     Y d}~nd}~ww xY w|r|                                 # |r|                                 w w xY wt          |          dk    rdS t          |          dk    r	|d         }nddlm} |                    |          }|                    t"          j        | j                   dS )zPrints FITS header(s) in a machine-readable table format.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments passed from the command-line as defined below.
    Nr   Fr   rM   )format)r   rI   r-   r%   rK   r'   r   rV   r   rW   rO   rG   r   rP   rN   vstackwritesysstdout)rX   tablesr   rY   tblrZ   resulting_tablerN   s           r   print_headers_as_tablere   (  sf    FM " "			",X66I//$/4<QQC #c""" 	 	 	Ic!ff	  "!!!  "!!!!" 6{{au	V		 )!!!!!!,,v..#*TZ88888s0   AAB+
B&!BB+BB++Cc           	         ddl m} g }| j        D ]}d}	 t          |d          }|                    | j        | j        | j                  }|r%|t          j	        |d         dk                       }n|
                    |ggd	          }|                    |           n8# t          $ r+}t          j        t          |                     Y d}~nd}~ww xY w|r|                                 # |r|                                 w w xY wt#          |          dk    rdS t#          |          d
k    r	|d         }n|                    |          }|d         }t          j                            |          r|                                }t#          t          j        |                    d
k    r>|D ]8}	|                    d |	D                       }
|	                    |
d           9d}nd}g }|D ]}	|                    |	d         d         gd          g}d|	j        v rG|	D ]D}|d         dv r|                    |                    |d         g||                              E|                    |
                    |                     |                    |          }| j        r|                    | j                   |                    dd           dS )zPrints 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   rM   NF)r   rK   r0   )r   )namesr   r5   c                 4    g | ]}|d           d|d          S )r5   :rK   r   ).0rows     r   
<listcomp>z/print_headers_as_comparison.<locals>.<listcomp>y  s.    &W&W&WC#e*'G'Gs9~'G'G&W&W&Wr   zhdu+keyword)namer   rL   )COMMENTHISTORYr   )	max_lines	max_width)rP   rN   r   rI   r-   r%   rK   r'   npwhererQ   r   rV   r   rW   rO   rG   r   r^   maisMaskedArrayuniqueColumn
add_columncolnamessortpprint)rX   rN   rb   r   rY   rc   rZ   rd   hdustab
new_columnkeyword_column_namefinal_tablesfinal_tablerk   s                  r   print_headers_as_comparisonr   L  sC    FM " "		",XuEEEI//$/4<QQC E"(3y>R#7889kkH:,mkDDMM# 	 	 	Ic!ff	  "!!!  "!!!!" 6{{au	V		 ),,v.. 5!D	u4   !  
29T??a 	; 	;C&W&WSV&W&W&WXXJNN:MN::::+' L 	6 	6||S_Q%7$8z|JJKcl""  y>%;;;""LL#g,c:M6NLOO    	EKK445555,,|,,Ky $###r22222s0   BB"!C1"
C,!CC1CC11D
c                    t          j        t          t           j                  }|                    dddt
                      |                    dddd	d
d           |                    dddd	t          d           |                                }|                    dddddd           |                    dddd           |                    ddd d	t          d!           |                    d"d#dd$           |                    d%d&d'(           |                    |           } | j	        d*| _	        | j
        rEd+ | j
        D             | _
        | j        s(t          j        d,           t          j        d-           | j        rd. | j        D             | _        	 | j	        rt#          |            d)S | j        rt%          |            d)S t'          |            d)S # t(          $ r Y d)S w xY w)/z<This is the main function called by the `fitsheader` script.)descriptionformatter_classz	--versionversionz	%(prog)s )actionr   z-ez--extensionHDUr   r%   zdspecify the extension by name or number; this argument can be repeated to select multiple extensions)metavarr   desthelpz-kz	--keywordKEYWORDzespecify a keyword; this argument can be repeated to select multiple keywords; also supports wildcards)r   r   typer   z-tz--table?FFORMATzprint 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defaultr   r   z-fz	--fitsort
store_truezYprint the headers as a table with each unique keyword in a given column (fitsort format) )r   r   z-sz--sort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)r   r   Nzascii.fixed_widthc                 :    g | ]}|                     d d          S . replacerj   keys     r   rl   zmain.<locals>.<listcomp>  s&    @@@sS[[c**@@@r   zISorting with -s/--sort is only supported in conjunction with -f/--fitsort   c                 :    g | ]}|                     d d          S r   r   r   s     r   rl   zmain.<locals>.<listcomp>  s&    FFF#C--FFFr   )argparseArgumentParserDESCRIPTIONRawDescriptionHelpFormatteradd_argumentr   rO   add_mutually_exclusive_group
parse_argsrN   rz   fitsortr   rW   r`   exitrK   re   r   r[   rV   )rX   parser
mode_groups      r   mainr     s   $1U  F I/H;/H/H     8  
 
 
 9  
 
 
 4466J8     :     J  
 
 
 3     A    
 T""D z(
y @@di@@@	| 	I   
 HQKKK| GFFFFF
: 	,"4(((((\ 	,'-----%d+++++    	s   'G( ?G( G( (
G65G6r   )r   r   r`   numpyrr   rP   r   r   
astropy.ior   stripr   	Exceptionr   r   rI   r[   re   r   r   r   r   r   <module>r      sK  < <|  



     $ $ $ $ $ $ $ $      	 
EGG 	 	 	 	 	 	 	 	R R R R R R R Rj    ?   @" " "2!9 !9 !9HD3 D3 D3Nn n n n n nr   