
    HR-e~                     N   d 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	m
Z
 ddlmZmZ ddlmZmZ ddl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mZmZmZm Z m!Z! g dZ"d Z#ddddddZ$d Z%dddddddZ&d Z'	 	 	 	 d(dZ(d)dZ)d*dZ*d Z+d+dZ,d Z-d,dZ. e/e.j         e0          r)e.xj         ej1        2                    dd           z  c_         d+d!Z3 e/e3j         e0          r)e3xj         ej1        2                    dd           z  c_         dddd"d#Z4d$ Z5d% Z6d-d'Z7dS ).a  Convenience functions for working with FITS files.

Convenience functions
=====================

The functions in this module provide shortcuts for some of the most basic
operations on FITS files, such as reading and updating the header.  They are
included directly in the 'astropy.io.fits' namespace so that they can be used
like::

    astropy.io.fits.getheader(...)

These functions are primarily for convenience when working with FITS files in
the command-line interpreter.  If performing several operations on the same
file, such as in a script, it is better to *not* use these functions, as each
one must open and re-parse the file.  In such cases it is better to use
:func:`astropy.io.fits.open` and work directly with the
:class:`astropy.io.fits.HDUList` object and underlying HDU objects.

Several of the convenience functions, such as `getheader` and `getdata` support
special arguments for selecting which HDU to use when working with a
multi-extension FITS file.  There are a few supported argument formats for
selecting the HDU.  See the documentation for `getdata` for an
explanation of all the different formats.

.. warning::
    All arguments to convenience functions other than the filename that are
    *not* for selecting the HDU should be passed in as keyword
    arguments.  This is to avoid ambiguity and conflicts with the
    HDU arguments.  For example, to set NAXIS=1 on the Primary HDU:

    Wrong::

        astropy.io.fits.setval('myimage.fits', 'NAXIS', 1)

    The above example will try to set the NAXIS value on the first extension
    HDU to blank.  That is, the argument '1' is assumed to specify an
    HDU.

    Right::

        astropy.io.fits.setval('myimage.fits', 'NAXIS', value=1)

    This will set the NAXIS keyword to 1 on the primary HDU (the default).  To
    specify the first extension HDU use::

        astropy.io.fits.setval('myimage.fits', 'NAXIS', value=1, ext=1)

    This complexity arises out of the attempt to simultaneously support
    multiple argument formats that were used in past versions of PyFITS.
    Unfortunately, it is not possible to support all formats without
    introducing some ambiguity.  A future Astropy release may standardize
    around a single format and officially deprecate the other formats.
    N)AstropyUserWarning   )FITSDiffHDUDiff)
FILE_MODES_File)_BaseHDU	_ValidHDU)HDUListfitsopen)ImageHDU
PrimaryHDU)BinTableHDU)Header)_is_dask_array_is_intfileobj_closedfileobj_modefileobj_name	path_like)	getheadergetdatagetvalsetvaldelvalwritetoappendupdateinfo	tabledump	tableloadtable_to_hdu	printdiffc                     t          |           \  }}t          | |g|R i |\  }}	 ||         }|j        }|                    |           n# |                    |           w xY w|S )a,  
    Get the header from an HDU of a FITS file.

    Parameters
    ----------
    filename : path-like or file-like
        File to get header from.  If an opened file object, its mode
        must be one of the following rb, rb+, or ab+).

    ext, extname, extver
        The rest of the arguments are for HDU specification.  See the
        `getdata` documentation for explanations/examples.
    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.

    Returns
    -------
    header : `Header` object
    closed)_get_file_mode_getextheaderclose)	filenameargskwargsmoder&   hdulistextidxhdur)   s	            ;lib/python3.11/site-packages/astropy/io/fits/convenience.pyr   r   c   s    * "(++LD&h>t>>>v>>OGV%foV$$$$V$$$$Ms   A A&)r)   lowerupperviewc                   t          |           \  }}|                    d          }	|                    d          }
|                    d          }t          |          dk    o|	du o|
du o|du  }t          | |g|R i |\  }}	 ||         }|j        }|W|rt          d| d          t          |          dk    rt          d	          |d         }|j        }|t          d
          |r|j        }|                    |           n# |                    |           w xY wd|rt          j	        d          n|rt          j	        d          rN|j
        j        dS |j
        j        d         d         dk    rdS fd|j
        j        D             |j
        _        t          |t                    r/t          |t           j                  r|                    |          }|r||fS |S )a	  
    Get the data from an HDU of a FITS file (and optionally the
    header).

    Parameters
    ----------
    filename : path-like or file-like
        File to get data from.  If opened, mode must be one of the
        following rb, rb+, or ab+.

    ext
        The rest of the arguments are for HDU specification.
        They are flexible and are best illustrated by examples.

        No extra arguments implies the primary HDU::

            getdata('in.fits')

        .. note::
            Exclusive to ``getdata``: if ``ext`` is not specified
            and primary header contains no data, ``getdata`` attempts
            to retrieve data from first extension HDU.

        By HDU number::

            getdata('in.fits', 0)      # the primary HDU
            getdata('in.fits', 2)      # the second extension HDU
            getdata('in.fits', ext=2)  # the second extension HDU

        By name, i.e., ``EXTNAME`` value (if unique)::

            getdata('in.fits', 'sci')
            getdata('in.fits', extname='sci')  # equivalent

        Note ``EXTNAME`` values are not case sensitive

        By combination of ``EXTNAME`` and EXTVER`` as separate
        arguments or as a tuple::

            getdata('in.fits', 'sci', 2)  # EXTNAME='SCI' & EXTVER=2
            getdata('in.fits', extname='sci', extver=2)  # equivalent
            getdata('in.fits', ('sci', 2))  # equivalent

        Ambiguous or conflicting specifications will raise an exception::

            getdata('in.fits', ext=('sci',1), extname='err', extver=2)

    header : bool, optional
        If `True`, return the data and the header of the specified HDU as a
        tuple.

    lower, upper : bool, optional
        If ``lower`` or ``upper`` are `True`, the field names in the
        returned data object will be converted to lower or upper case,
        respectively.

    view : ndarray, optional
        When given, the data will be returned wrapped in the given ndarray
        subclass by calling::

           data.view(view)

    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.

    Returns
    -------
    array : ndarray or `~numpy.recarray` or `~astropy.io.fits.Group`
        Type depends on the type of the extension being referenced.

        If the optional keyword ``header`` is set to `True`, this
        function will return a (``data``, ``header``) tuple.

    Raises
    ------
    IndexError
        If no data is found in searched HDUs.
    extextnameextverr   NzNo data in HDU #.r   z2No data in Primary HDU and no extension HDU found.z2No data in either Primary or first extension HDUs.r%   r3   r4    c                 &    g | ]} |          S  r=   ).0ntranss     r2   
<listcomp>zgetdata.<locals>.<listcomp>   s!    ???EE!HH???    )r'   getlenr(   data
IndexErrorr)   r*   operatormethodcallerdtypenamesdescr
isinstancetype
issubclassnpndarrayr5   )r+   r)   r3   r4   r5   r,   r-   r.   r&   r7   r8   r9   	ext_givenr/   r0   r1   rE   hdrr@   s                     @r2   r   r      sA   ` "(++LD&
**U

Cjj##GZZ!!FD		QM3$;M7d?Mv~I h>t>>>v>>OGV%fox< ? !=F!=!=!=>>> 7||q   !UVVV!*C8D| !UVVV 	*CV$$$$V$$$$ E /%g..	 /%g.. @:#F:Aq!R''F????dj.>???
 $ *T2:">"> yy Sys   A1D D(c                 D    d|vrd|d<   t          | g|R i |}||         S )a	  
    Get a keyword's value from a header in a FITS file.

    Parameters
    ----------
    filename : path-like or file-like
        Name of the FITS file, or file object (if opened, mode must be
        one of the following rb, rb+, or ab+).

    keyword : str
        Keyword name

    ext, extname, extver
        The rest of the arguments are for HDU specification.
        See `getdata` for explanations/examples.
    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.
        *Note:* This function automatically specifies ``do_not_scale_image_data
        = True`` when opening the file so that values can be retrieved from the
        unmodified header.

    Returns
    -------
    keyword value : str, int, or float
    do_not_scale_image_dataT)r   )r+   keywordr,   r-   rR   s        r2   r   r     sA    6 !..,0()
H
.t
.
.
.v
.
.Cw<rB   F)valuecommentbeforeaftersavecommentc                0   d|vrd|d<   t          |           }	t          | dg|R i |\  }
}	 ||
|         j        v r|rd}|
|         j                            |||||           |
                    |	           dS # |
                    |	           w xY w)as  
    Set a keyword's value from a header in a FITS file.

    If the keyword already exists, it's value/comment will be updated.
    If it does not exist, a new card will be created and it will be
    placed before or after the specified location.  If no ``before`` or
    ``after`` is specified, it will be appended at the end.

    When updating more than one keyword in a file, this convenience
    function is a much less efficient approach compared with opening
    the file for update, modifying the header, and closing the file.

    Parameters
    ----------
    filename : path-like or file-like
        Name of the FITS file, or file object If opened, mode must be update
        (rb+).  An opened file object or `~gzip.GzipFile` object will be closed
        upon return.

    keyword : str
        Keyword name

    value : str, int, float, optional
        Keyword value (default: `None`, meaning don't modify)

    comment : str, optional
        Keyword comment, (default: `None`, meaning don't modify)

    before : str, int, optional
        Name of the keyword, or index of the card before which the new card
        will be placed.  The argument ``before`` takes precedence over
        ``after`` if both are specified (default: `None`).

    after : str, int, optional
        Name of the keyword, or index of the card after which the new card will
        be placed. (default: `None`).

    savecomment : bool, optional
        When `True`, preserve the current comment for an existing keyword.  The
        argument ``savecomment`` takes precedence over ``comment`` if both
        specified.  If ``comment`` is not specified then the current comment
        will automatically be preserved  (default: `False`).

    ext, extname, extver
        The rest of the arguments are for HDU specification.
        See `getdata` for explanations/examples.
    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.
        *Note:* This function automatically specifies ``do_not_scale_image_data
        = True`` when opening the file so that values can be retrieved from the
        unmodified header.
    rT   Tr   Nr%   )r   r(   r)   setr*   )r+   rU   rV   rW   rX   rY   rZ   r,   r-   r&   r/   r0   s               r2   r   r   -  s    @ !..,0()H%%FhB4BBB6BBOGV%gfo,,,,G""7E7FEJJJV$$$$$V$$$$s   7A= =Bc                     d|vrd|d<   t          |           }t          | dg|R i |\  }}	 ||         j        |= |                    |           dS # |                    |           w xY w)a  
    Delete all instances of keyword from a header in a FITS file.

    Parameters
    ----------
    filename : path-like or file-like
        Name of the FITS file, or file object If opened, mode must be update
        (rb+).  An opened file object or `~gzip.GzipFile` object will be closed
        upon return.

    keyword : str, int
        Keyword name or index

    ext, extname, extver
        The rest of the arguments are for HDU specification.
        See `getdata` for explanations/examples.
    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.
        *Note:* This function automatically specifies ``do_not_scale_image_data
        = True`` when opening the file so that values can be retrieved from the
        unmodified header.
    rT   Tr   r%   N)r   r(   r)   r*   )r+   rU   r,   r-   r&   r/   r0   s          r2   r   r   z  s    0 !..,0()H%%FhB4BBB6BBOGV%FO"7+V$$$$$V$$$$s   A A,	exceptionc                     t          ||          }|j        r&t          |t                    st          ||          }|                    | |||           dS )a  
    Create a new FITS file using the supplied data/header.

    Parameters
    ----------
    filename : path-like or file-like
        File to write to.  If opened, must be opened in a writable binary
        mode such as 'wb' or 'ab+'.

    data : array or `~numpy.recarray` or `~astropy.io.fits.Group`
        data to write to the new file

    header : `Header` object, optional
        the header associated with ``data``. If `None`, a header
        of the appropriate type is created for the supplied data. This
        argument is optional.

    output_verify : str
        Output verification option.  Must be one of ``"fix"``, ``"silentfix"``,
        ``"ignore"``, ``"warn"``, or ``"exception"``.  May also be any
        combination of ``"fix"`` or ``"silentfix"`` with ``"+ignore"``,
        ``+warn``, or ``+exception" (e.g. ``"fix+warn"``).  See
        :ref:`astropy:verify` for more info.

    overwrite : bool, optional
        If ``True``, overwrite the output file if it exists. Raises an
        ``OSError`` if ``False`` and the output file exists. Default is
        ``False``.

    checksum : bool, optional
        If `True`, adds both ``DATASUM`` and ``CHECKSUM`` cards to the
        headers of all HDU's written to the file.
    r)   )	overwriteoutput_verifychecksumN)_makehduis_imagerL   r   r   )r+   rE   r)   rb   ra   rc   r1   s          r2   r   r     so    R 4
 
 C
| .JsJ77 .f---KKI]X      rB   c                   % ddl m} ddlm}m} d}| j        rddlm} ddlm	} ddl
m} dd	lm}	 | j                            |||f          }
|
rd
 |
D             }t!          d|           | j                            |          }|r |	|           \  } }|                                 }t#          |t&          j        j                  rt&          j                            |j                  }|j        j                                        D ]\  }\  }}t'          j        |j        |         ||         k              r|j        r|j        d         j        n|j        }t=          |t&          j                  r-tA          t&          j!        t&          j!                  |j        |<   t=          |t&          j"                  rt&          j!        |j        |<   t=          |t&          j#                  r
d|j        |<   tI          j%        |&                                ||          }|j        D ]M%d}%j'        |v s%j'        j(        |v s|%j)                 j        }|*                    tV                    %_,        NntI          j%        |||          }|j        D ]f%| %j)                 j-        j'        K| %j)                 j-        j        t\          k    } || %j)                 j-        j'        |          }||%_/        | %j)                 j0        }|ddl
m1} ddl2m3} 	 |4                    d          %_0         |%j0        dd           # |$ r, |j5        } |d%j)         dtm          |           d          t           $ ru d|4                                 d}to          %fd| j8        9                    dg           D                       r|dz  }n|dz  }tu          j;        |tx                     Y bw xY wh| j8        =                    di           }|                                D ][\  }}|j        |         %d D ]'} t}          %| |9                    | d                     (|9                    d!d          }!|!|!%_?        \| j8                                        D ]\  }"}# ||"@                                          s|"@                                |v rtu          j;        d"|" d#tx                     X|"dk    rd$}"t#          |#t                    ra|#D ]]}$	 |jB        C                    |"|$f            # t           $ r1 tu          j;        d%|" d&t;          |#           d'tx                     Y Zw xY w	 |#|jB        |"<   # t           $ r2 tu          j;        d%|" d&t;          |#           d'tx                     Y w xY w|S )(a  
    Convert an `~astropy.table.Table` object to a FITS
    `~astropy.io.fits.BinTableHDU`.

    Parameters
    ----------
    table : astropy.table.Table
        The table to convert.
    character_as_bytes : bool
        Whether to return bytes for string columns when accessed from the HDU.
        By default this is `False` and (unicode) strings are returned, but for
        large tables this may use up a lot of memory.

    Returns
    -------
    table_hdu : `~astropy.io.fits.BinTableHDU`
        The FITS binary table HDU.
    r   )python_to_tdisp)REMOVE_KEYWORDSis_column_keywordNr   )
BaseColumn)Time)Quantity)time_to_fitsc                 &    g | ]}|j         j        S r=   )r   name)r>   cols     r2   rA   z table_to_hdu.<locals>.<listcomp>  s     K K K3 K K KrB   z(cannot write table with mixin column(s) r;   )r)   character_as_bytes)BIJK)logical_dtype)Unit)UnitScaleErrorfits)formatwarn)rz   parse_strictzThe column 'z>' could not be stored in FITS format because it has a scale '(zZ)' that is not recognized by the FITS standard. Either scale the data or change the units.z
The unit 'z+' could not be saved in native FITS format c              3   8   K   | ]}d |v odj         z   |v V  dS )SerializedColumnzname: N)ro   )r>   itemrp   s     r2   	<genexpr>ztable_to_hdu.<locals>.<genexpr>P  sM         '$.N8ch3F$3N     rB   commentszand hence will be lost to non-astropy fits readers. Within astropy, the unit can roundtrip using QTable, though one has to enable the unit before reading.zand cannot be recovered in reading. It can roundtrip within astropy by using QTable both to write and read back, though one has to enable the unit before reading.__coordinate_columns__)
coord_type
coord_unittime_ref_poszMeta-data keyword z@ will be ignored since it conflicts with a FITS reserved keywordrW   zAttribute `z
` of type z* cannot be added to FITS Header - skipping)Dcolumnrg   connectrh   ri   has_mixin_columnsastropy.table.columnrj   astropy.timerk   astropy.unitsrl   fitstimerm   columnsnot_isinstance
ValueErrorrL   as_arrayrO   maMaskedArraydefault_fill_valuerI   fieldsitemsall
fill_valuesubdtyperM   rN   complexfloatingcomplexnaninexact	characterr   from_columnsfilledrz   p_formatro   astypeintnullr   booldispunitrw   astropy.units.format.fitsrx   	to_stringscalestranymetarC   warningsr{   r   popsetattrr   r4   listr)   r   )&tablerq   rg   rh   ri   rR   rj   rk   rl   rm   unsupported_colsunsupported_names	time_colstarrayr   colnamecoldtype_coltype	table_hduint_formatsr   logicaltdisp_formatr   rw   rx   r   warning
coord_metacol_namecol_infoattrtrposkeyrV   r   rp   s&                                        @r2   r"   r"     sj   ( (''''';;;;;;;; C  - 	433333%%%%%%************ !=77Xt8TUU 	 K K:J K K KN;LNN   M,,T22	 	-%e,,JE3 ^^F&"%+,, (
  U55flCC&,l&9&?&?&A&A 	4 	4"G]hvf'04Fw4OOPP 4 2:1BUH%a(--  gr'9:: 4181H1HF%g..44 413F%g..66 413F%g.  ,MMOOC<N
 
 
	 $ 		. 		.C /KJ+--1D1S1S)4J!((--CHH		.  ,33E
 
 
	
   8C 8C?&2CHo*0D8G*?ch$+7  L ''SX# +*****@@@@@@&C>>>88J SXf6BBBBBI "   
$n438 4 47:5zz4 4 4    ; ; ;
*!1!1 * * *       %
z2 > >      LGG RG
 g'9:::::/;! ^  8"==J(..00 % %() / 	9 	9DCx||D$778888^T22$Cj&&((  
USYY[[)) 	SYY[[O-K-KM/S / / /"  
  *CeT"" 	  $++S$K8888!   M:c : :T%[[ : : :*    (-	 %%   6# 6 6e 6 6 6&     s7   MB*O:9O:T::8U54U5:
V8W WTc                    t          | t                    rt          j                            |           } t          |           \  }}}|rt          | ||fd|i| dS t          ||          }	t          |	t                    rt          ||          }	|s|s_t          | fddi|}
	 |
                    |	           ||	_        |
                    |           dS # |
                    |           w xY wt          | d          }
	 ||	_        |	                    |
           |
                                 dS # |
                                 w xY w)a  
    Append the header/data to FITS file if filename exists, create if not.

    If only ``data`` is supplied, a minimal header is created.

    Parameters
    ----------
    filename : path-like or file-like
        File to write to.  If opened, must be opened for update (rb+) unless it
        is a new file, then it must be opened for append (ab+).  A file or
        `~gzip.GzipFile` object opened for update will be closed after return.

    data : array, :class:`~astropy.table.Table`, or `~astropy.io.fits.Group`
        The new data used for appending.

    header : `Header` object, optional
        The header associated with ``data``.  If `None`, an appropriate header
        will be created for the data object supplied.

    checksum : bool, optional
        When `True` adds both ``DATASUM`` and ``CHECKSUM`` cards to the header
        of the HDU when written to the file.

    verify : bool, optional
        When `True`, the existing FITS file will be read in to verify it for
        correctness before appending.  When `False`, content is simply appended
        to the end of the file.  Setting ``verify`` to `False` can be much
        faster.

    **kwargs
        Additional arguments are passed to:

        - `~astropy.io.fits.writeto` if the file does not exist or is empty.
          In this case ``output_verify`` is the only possible argument.
        - `~astropy.io.fits.open` if ``verify`` is True or if ``filename``
          is a file object.
        - Otherwise no additional arguments can be used.

    rc   r.   r   r%   r.   N)rL   r   ospath
expanduser_stat_filename_or_fileobjr   rd   r   r   r   r   _output_checksumr*   r   _writeto)r+   rE   r)   rc   verifyr-   ro   r&   noexist_or_emptyr1   fs              r2   r   r     sl   P (I&& 07%%h//%>x%H%H"D&"  	$DDDVDDDDDtV$$c:&& 	)4((C 	 	;;;F;;A' (0$v&&&&&v&&&&hX...A'/$Q									s   &C C2D9 9Ec                 j   |r.t          |d         t                    r|d         }|dd         }nd}|                    d|          }t          ||          }t	          |           }t          | dg|R i |\  }}	 |||<   |                    |           dS # |                    |           w xY w)a  
    Update the specified HDU with the input data/header.

    Parameters
    ----------
    filename : path-like or file-like
        File to update.  If opened, mode must be update (rb+).  An opened file
        object or `~gzip.GzipFile` object will be closed upon return.

    data : array, `~astropy.table.Table`, or `~astropy.io.fits.Group`
        The new data used for updating.

    header : `Header` object, optional
        The header associated with ``data``.  If `None`, an appropriate header
        will be created for the data object supplied.

    ext, extname, extver
        The rest of the arguments are flexible: the 3rd argument can be the
        header associated with the data.  If the 3rd argument is not a
        `Header`, it (and other positional arguments) are assumed to be the
        HDU specification(s).  Header and HDU specs can also be
        keyword arguments.  For example::

            update(file, dat, hdr, 'sci')  # update the 'sci' extension
            update(file, dat, 3)  # update the 3rd extension HDU
            update(file, dat, hdr, 3)  # update the 3rd extension HDU
            update(file, dat, 'sci', 2)  # update the 2nd extension HDU named 'sci'
            update(file, dat, 3, header=hdr)  # update the 3rd extension HDU
            update(file, dat, header=hdr, ext=5)  # update the 5th extension HDU

    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.
    r   r   Nr)   r   r%   )rL   r   r   rd   r   r(   r*   )	r+   rE   r,   r-   r)   new_hdur&   r/   _exts	            r2   r   r     s    L  
47F++ aABBx ZZ&))FtV$$GH%%FHh@@@@@@MGT%V$$$$$V$$$$s   =B B2c                     t          | d          \  }}d|vrd|d<   t          | fd|i|}	 |                    |          }|r|                                 n# |r|                                 w w xY w|S )a  
    Print the summary information on a FITS file.

    This includes the name, type, length of header, data shape and type
    for each HDU.

    Parameters
    ----------
    filename : path-like or file-like
        FITS file to obtain info from.  If opened, mode must be one of
        the following: rb, rb+, or ab+ (i.e. the file must be readable).

    output : file, bool, optional
        A file-like object to write the output to.  If ``False``, does not
        output to a file and instead returns a list of tuples representing the
        HDU info.  Writes to ``sys.stdout`` by default.
    **kwargs
        Any additional keyword arguments to be passed to
        `astropy.io.fits.open`.
        *Note:* This function sets ``ignore_missing_end=True`` by default.
    readonlydefaultignore_missing_endTr.   )output)r'   r   r   r*   )r+   r   r-   r.   r&   r   rets          r2   r   r     s    , "(J???LD&6))'+#$/////AffFf## 	GGIII  	GGIIII	 Js   A A4c                    fddD             }|p|}t          | t                    r|rt          |           \  }}t          |          \  }}	t          | |g|R i |\  }
}	 t          ||g|R i |\  }}n%# t          $ r |
                    |            w xY w	 |
|         }||         }t          t          ||fi                                            |
                    |           |                    |	           dS # |
                    |           |                    |	           w xY wt          | t                    r|rt          d          t          | t                    r1|s/t          t          | |fi                                            dS t          | t                    r|rt          d          t          t          | |fi                                            dS )a`	  
    Compare two parts of a FITS file, including entire FITS files,
    FITS `HDUList` objects and FITS ``HDU`` objects.

    Parameters
    ----------
    inputa : str, `HDUList` object, or ``HDU`` object
        The filename of a FITS file, `HDUList`, or ``HDU``
        object to compare to ``inputb``.

    inputb : str, `HDUList` object, or ``HDU`` object
        The filename of a FITS file, `HDUList`, or ``HDU``
        object to compare to ``inputa``.

    ext, extname, extver
        Additional positional arguments are for HDU specification if your
        inputs are string filenames (will not work if
        ``inputa`` and ``inputb`` are ``HDU`` objects or `HDUList` objects).
        They are flexible and are best illustrated by examples.  In addition
        to using these arguments positionally you can directly call the
        keyword parameters ``ext``, ``extname``.

        By HDU number::

            printdiff('inA.fits', 'inB.fits', 0)      # the primary HDU
            printdiff('inA.fits', 'inB.fits', 2)      # the second extension HDU
            printdiff('inA.fits', 'inB.fits', ext=2)  # the second extension HDU

        By name, i.e., ``EXTNAME`` value (if unique). ``EXTNAME`` values are
        not case sensitive:

            printdiff('inA.fits', 'inB.fits', 'sci')
            printdiff('inA.fits', 'inB.fits', extname='sci')  # equivalent

        By combination of ``EXTNAME`` and ``EXTVER`` as separate
        arguments or as a tuple::

            printdiff('inA.fits', 'inB.fits', 'sci', 2)    # EXTNAME='SCI'
                                                           # & EXTVER=2
            printdiff('inA.fits', 'inB.fits', extname='sci', extver=2)
                                                           # equivalent
            printdiff('inA.fits', 'inB.fits', ('sci', 2))  # equivalent

        Ambiguous or conflicting specifications will raise an exception::

            printdiff('inA.fits', 'inB.fits',
                      ext=('sci', 1), extname='err', extver=2)

    **kwargs
        Any additional keyword arguments to be passed to
        `~astropy.io.fits.FITSDiff`.

    Notes
    -----
    The primary use for the `printdiff` function is to allow quick print out
    of a FITS difference report and will write to ``sys.stdout``.
    To save the diff report to a file please use `~astropy.io.fits.FITSDiff`
    directly.
    c                 D    i | ]}|v |                     |          S r=   )r   )r>   r   r-   s     r2   
<dictcomp>zprintdiff.<locals>.<dictcomp>}  s1       !$vVZZ__rB   r7   r8   r9   r%   z;Cannot use extension keywords when providing an HDU object.z=Extension specification with HDUList objects not implemented.N)rL   r   r'   r(   	Exceptionr*   printr   reportr
   r   r   NotImplementedErrorr   )inputainputbr,   r-   	extensionhas_extensionsmodeaclosedamodebclosedbhdulistaextidxahdulistbextidxbhduahdubs      `            r2   r#   r#   @  ss   z   (D  I &YN&# (;> (; (//w'//w#FEFDFFFIFF'	 ' J J J J	 J JHgg 	 	 	NN'N***		+G$DG$D'$////6688999 NN'N***NN'N***** NN'N***NN'N**** 
FI	&	& ;> ;VWWW	FI	&	& ;~ ;gff////668899999	FG	$	$ ; ;!K
 
 	
 	hvv00007799:::::s   &A; ;"B!=D .D:c                    t          | d          \  }}t          | |          }	 |sDt          j                            |j        j                  \  }	}
|	dz   t          |          z   dz   }||                             ||||           |r|	                                 dS dS # |r|	                                 w w xY w)a  
    Dump a table HDU to a file in ASCII format.  The table may be
    dumped in three separate files, one containing column definitions,
    one containing header parameters, and one for table data.

    Parameters
    ----------
    filename : path-like or file-like
        Input fits file.

    datafile : path-like or file-like, optional
        Output data file.  The default is the root name of the input
        fits file appended with an underscore, followed by the
        extension number (ext), followed by the extension ``.txt``.

    cdfile : path-like or file-like, optional
        Output column definitions file.  The default is `None`,
        no column definitions output is produced.

    hfile : path-like or file-like, optional
        Output header parameters file.  The default is `None`,
        no header parameters output is produced.

    ext : int
        The number of the extension containing the table HDU to be
        dumped.

    overwrite : bool, optional
        If ``True``, overwrite the output file if it exists. Raises an
        ``OSError`` if ``False`` and the output file exists. Default is
        ``False``.

    Notes
    -----
    The primary use for the `tabledump` function is to allow editing in a
    standard text editor of the table data and parameters.  The
    `tableload` function can be used to reassemble the table from the
    three ASCII files.
    r   r   r   r   z.txtN)
r'   r   r   r   splitext_filero   reprdumpr*   )r+   datafilecdfilehfiler7   ra   r.   r&   r   roottails              r2   r    r      s    X "(J???LD&%%%A	 	7))!',77JD$czDII-6H 	
#HfeY777 	GGIIIII	 	6 	GGIIII	s   A$B% %B>
z
    c                 2    t          j        | ||d          S )a  
    Create a table from the input ASCII files.  The input is from up
    to three separate files, one containing column definitions, one
    containing header parameters, and one containing column data.  The
    header parameters file is not required.  When the header
    parameters file is absent a minimal header is constructed.

    Parameters
    ----------
    datafile : path-like or file-like
        Input data file containing the table data in ASCII format.

    cdfile : path-like or file-like
        Input column definition file containing the names, formats,
        display formats, physical units, multidimensional array
        dimensions, undefined values, scale factors, and offsets
        associated with the columns in the table.

    hfile : path-like or file-like, optional
        Input parameter definition file containing the header
        parameter definitions to be associated with the table.
        If `None`, a minimal header is constructed.

    Notes
    -----
    The primary use for the `tableload` function is to allow the input of
    ASCII data that was edited in a standard text editor of the table
    data and parameters.  The tabledump function can be used to create the
    initial ASCII files.
    T)replace)r   load)r   r   r   s      r2   r!   r!     s    > HfeTBBBBrB   r   c                h   d                     ||||d          }t          |          dk    rt          |d                   s(t          |t                    r1t          |          dk    r|||t          |          |d         }nt          |d         t                    r||t          |          |d         }nd|d         }n[t          |          dk    r&|||t          |          |d         }|d         }n"t          |          dk    rt          d          |vt          |          sgt          |t                    rCt          |          dk    r0t          |d         t                    rt          |d                   st          d          |$t          |t                    st          d	          |t          |          st          d
          |||d}n6|||t          |          |r|r||f}n|df}n|r|t          d          t          | fd|i|}||fS )z
    Open the input file, return the `HDUList` and the extension.

    This supports several different styles of extension selection.  See the
    :func:`getdata()` documentation for the different possibilities.
    z0Redundant/conflicting extension arguments(s): {})r,   r7   r8   r9   r   r      NzToo many positional arguments.z_The ext keyword must be either an extension number (zero-indexed) or a (extname, extver) tuple.z&The extname argument must be a string.z'The extver argument must be an integer.z)extver alone cannot specify an extension.r.   )	rz   rD   r   rL   tuple	TypeErrorr   r   r   )	r+   r.   r7   r8   r9   r,   r-   err_msgr/   s	            r2   r(   r(     s    AGGcgHH G 4yyA~~ 47 	
3 6 6 	3s88q=='"59K(((q'CCQ%% 		 '"5(((1gGG q'CC	Ta?g1V5GG$$$q'a	TQ8999
  sE""  CA3q63'' A 
 ;
 
 	
 :gs#;#;ABBB'&//BCCC
{w6>	g1V5G   	 E 	F#CCA,CC	 EGOCDDDx55d5f55GC<rB   c                    |t                      }t          j        | |          }|j        t          t          fv rt          | t          j                  r| j        j	        t          | t          j
                  rt          | |          }nJt          | t          j                  st          |           rt          | |          }nt          d          |S )Nr`   zData must be a numpy array.)r   r	   
_from_data	__class__r
   rL   rO   rP   rI   r   recarrayr   r   r   KeyError)rE   r)   r1   s      r2   rd   rd   ^  s    ~

dF
+
+C
}9--- tRZ((	:-1Z->-Jbk** .Kd6222CCbj)) 	:^D-A-A 	:4///CC8999JrB   c                    t          | t          j                  rt          j        |           } t	          |           }t          |           pd}	 |                                 }n# t          $ r d}Y nw xY w|oBt          j        	                    |           p"t          j        
                    |          dk    p| o|dk    }|||fS )Nr;   r   )rL   r   PathLikefspathr   r   tellAttributeErrorr   existsgetsize)r+   r&   ro   locr   s        r2   r   r   p  s    (BK(( '9X&&H%%F!!'RDmmoo    	KbgnnT***Jrwt/D/D/I!(
sax  )))s   A% %A43A4r   c                     |}t          |           }t          |           }|8t          j        |          }|"t	          d                    |                    ||fS )z
    Allow file object to already be opened in any of the valid modes and
    and leave the file in the same state (opened or closed) as when
    the function was called.
    NzRFile mode of the input file object ({!r}) cannot be used to read/write FITS files.)r   r   r   rC   OSErrorrz   )r+   r   r.   r&   fmodes        r2   r'   r'     sk     DH%%F""E~e$$<))/  
 <rB   )Nr^   FF)F)NFT)N)NNNr   F)r   )8__doc__rG   r   r   numpyrO   astropy.utils.exceptionsr   diffr   r   filer   r   hdu.baser	   r
   hdu.hdulistr   r   	hdu.imager   r   	hdu.tabler   r)   r   utilr   r   r   r   r   r   __all__r   r   r   r   r   r   r"   r   r   r   r#   r    rL   r   _tdump_file_formatr   r!   r(   rd   r   r'   r=   rB   r2   <module>r     ss  5 5n  				      7 7 7 7 7 7 # # # # # # # # # # # # # # # # ) ) ) ) ) ) ) ) * * * * * * * * + + + + + + + + " " " " " "                       "  @ %)Dt E E E E EP  L 
J% J% J% J% J%Z %  %  %L . . . .bD D D DNI I I IX7% 7% 7%t" " " "Jj; j; j;Z9 9 9 9x :i%% P7??hOOOC C C CD :i%% P7??hOOO (,T$ H H H H HV  $* * *$     rB   