
    HR-ee                       d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlZ	d dl
mZ d dlmZmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZ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# d dl$m%Z% d dl&m'Z' d dl(m)Z)m*Z* d dl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 dZ6dZ7dZ8dZ9e7de8de9diZ:d Z;dZ<dZ=dZ>dZ?e7Z@e;ZAd ZBd ZCdZDdZEddiZFh d ZG G d! d"e          ZH G d# d$e5          ZI G d% d&          ZJdS )'    N)suppress)conf)compress_hdudecompress_hdu_section)_data_shape_n_tiles_tile_shape)Card)KEYWORD_NAMES)TDEF_REColDefsColumn)FITS_rec)Header)_get_array_mmap_is_int_is_pseudo_integer_pseudo_zero)lazyproperty)deprecated_renamed_argument)AstropyDeprecationWarningAstropyUserWarning)simplify_basic_index   )BITPIX2DTYPEDELAYEDDTYPE2BITPIXExtensionHDU)ImageHDU)BinTableHDUT   	NO_DITHERSUBTRACTIVE_DITHER_1SUBTRACTIVE_DITHER_2)
NOCOMPRESSRICE_1GZIP_1GZIP_2PLIO_1HCOMPRESS_1r'   g      0@       RICE_ONE>   ZIMAGEZNAXISZBITPIXZEXTENDZSIMPLEZCMPTYPEZMASKCMPZTENSIONc                   P    e Zd ZdZdddddddd	d
dd
Z ej        d          Z ee	                                          
                    g d          Zh dZd fd	Zd Z fdZ fdZd  fd	Zd! fd	Z fdZd" fd	Zed#d            Zed             Zd Z fdZ xZS )$CompImageHeadera  
    Header object for compressed image HDUs designed to keep the compression
    header and the underlying image header properly synchronized.

    This essentially wraps the image header, so that all values are read from
    and written to the image header.  However, updates to the image header will
    also update the table header where appropriate.

    Note that if no image header is passed in, the code will instantiate a
    regular `~astropy.io.fits.Header`.
    r3   r6   r1   r0   r2   ZBLOCKEDZPCOUNTZGCOUNTZHECKSUMZDATASUM)
SIMPLEXTENSIONBITPIXNAXISEXTENDBLOCKEDPCOUNTGCOUNTCHECKSUMDATASUMz0(?P<label>^[Zz][a-zA-Z]*)(?P<num>[1-9][0-9 ]*$)?)r/   r4   r5   ZQUANTIZZDITHER0>   ZVALZNAMEZTILEr0   Nc                 h    |t          |          S t                                          |           S N)r   super__new__)clstable_headerimage_header	__class__s      >lib/python3.11/site-packages/astropy/io/fits/hdu/compressed.pyrP   zCompImageHeader.__new__}   s/     ,'''77??3'''    c                 t    |j         | _         |j        | _        |j        | _        |j        | _        || _        d S rN   )_cards_keyword_indices_rvkc_indices	_modified_table_header)selfrR   rS   s      rU   __init__zCompImageHeader.__init__   s:    ") , =)7%/)rV   c                    |                      |||           rd S t          |t                    r|                     |          \  }}nt          |t                    r|\  }}n|d }}|                     |          rd S t                                          ||           |#|                     |          }|| j	        ||f<   d S d S rN   )

_set_slice
isinstanceint_keyword_from_indextuple_is_reserved_keywordrO   __setitem___remap_keywordr\   )r]   keyvaluekeywordindexremapped_keywordrT   s         rU   rf   zCompImageHeader.__setitem__   s     ??3t,, 	Fc3 	'!55c::NGUUU## 	' NGUU !$UG$$W-- 	FC'''#227;;:?D/6777 rV   c                    t          |t                    s|                     |          r!t                                          |          S t          |t
                    r|                     |          \  }}nt          |t                    r|\  }}n|d }}|| vrt          d|d          t                                          |           | 	                    |          }|| j
        v r|| j
        ||f= d S | j
        |= d S d S )NzKeyword z not found.)ra   slice_haswildcardrO   __delitem__rb   rc   rd   KeyErrorrg   r\   )r]   rh   rj   rk   rl   rT   s        rU   rp   zCompImageHeader.__delitem__   s)   c5!! 	,T%6%6s%;%; 	, 77&&s+++c3 	'!55c::NGUUU## 	' NGUU $UGd??8c888999C   ..w77t111 &(8%'@AAA&'7888	 21rV   TFc                    t          |t                    rt          |          }ngt          |t                    r
t          | }nH|t                      }n7t          |t                    s"t	          d                    |                    |                     |j                  rd S t                      	                    ||||           | 
                    |j                  }t          |                              d          r|                    d          sd|z   }t          ||j        |j                  }| j        	                    |d||           d S )NzgThe value appended to a Header must be either a keyword or (keyword, value, [comment]) tuple; got: {!r})card	useblanksbottomendz	HIERARCH F)ra   strr
   rd   
ValueErrorformatre   rj   rO   appendrg   
startswithri   commentr\   )r]   rs   rt   ru   rv   rl   rT   s         rU   rz   zCompImageHeader.append   s^    dC   
	::DDe$$ 	;DD\66DDD$'' 	??Evd||  
 $$T\22 	FDIf#NNN..t|<< t99,, 	>5E5P5P6
 6
 	>  +-==$dj$,?? 	!!tuVQT!UUUUUrV   c                     t          |t                    rS|r |dk    rt          | j                  }n|dz  }|t          | j                  k    r|                     |d           d S t          |t
                    rt          |          }nVt          |t                    r
t          | }n7t          |t                    s"t          d	                    |                    | 
                    |j                  rd S |                     |          }|                     |j                  }t                                          ||||           t          ||j        |j                  }| j                            ||d|           d S )Nr!   r   T)rv   ziThe value inserted into a Header must be either a keyword or (keyword, value, [comment]) tuple; got: {!r})rt   afterF)ra   rb   lenrX   rz   rw   r
   rd   rx   ry   re   rj   _remap_indexrg   rO   insertri   r|   r\   )r]   rh   rs   rt   r~   remapped_indexrl   rT   s          rU   r   zCompImageHeader.insert   s   c3 
	 "99dk**CC1HCc$+&&&&Dd+++dC   	::DDe$$ 	;DDD$'' 	??Evd||  
 $$T\22 	F **3//..t|<<sDIUCCC$dj$,?? 	!!.$%u!UUUUUrV   c                    |d         }|                      |          rd S t                                          |           |t          j        v rd S |                     |          }| j                            |f|dd          z              d S )Nr   r   )re   rO   _updater
   _commentary_keywordsrg   r\   )r]   rs   rj   rl   rT   s       rU   r   zCompImageHeader._update  s    q'$$W-- 	Fd///F..w77""$4#6abb#ABBBBBrV   c                 >   |d         }|                      |          rd S |Ct          |t                    r|                     |          }n|                     |          }d }nBt          |t                    r|                     |          }n|                     |          }d }t                                          ||||           |                     |          }t          ||d         |d                   }| j                            ||||           d S )Nr   )beforer~   replacer   r"   )	re   ra   rb   r   rg   rO   _relativeinsertr
   r\   )
r]   rs   r   r~   r   rj   remapped_afterremapped_beforerl   rT   s
            rU   r   zCompImageHeader._relativeinsert0  s0   q'$$W-- 	F >%%% <!%!2!25!9!9!%!4!4U!;!;"OO&#&& >"&"3"3F";";"&"5"5f"="=!NV5'RRR..w77$d1gtAw77** 	+ 	
 	
 	
 	
 	
rV   c                 \   d                     |          }|dk    r|rt          j        |           dS t          j        |          }|rF|                    d                                          t          v r|rt          j        |           dS | j                            |          }|r|                    d                                          }|                    d          }|!|| j	        v r|rt          j        |           dS || j
        v r|rt          j        |           dS dS )NzKeyword {!r} is reserved for use by the FITS Tiled Image Convention and will not be stored in the header for the image being compressed.TFIELDSTlabelnumF)ry   warningswarnr   matchgroupupperTABLE_KEYWORD_NAMES_zdef_re_indexed_compression_keywords_compression_keywords)rQ   rj   r   msgmr   r   s          rU   re   z$CompImageHeader._is_reserved_keywordM  s@   &&,fWoo 	 i #c"""4M'"" 	!!''))-@@@ #c"""4Lw'' 
	GGG$$**,,E''%..C5C,M#M#M 'M#&&&t#333 'M#&&&turV   c                     d}|d d         dk    rIt          t                    5  t          |dd                    }|dk    }d d d            n# 1 swxY w Y   |rd| S | j                            ||          S )NF   rA   r   r0   )r   rx   rb   _keyword_remapsget)rQ   rj   	is_naxisnrk   s       rU   rg   zCompImageHeader._remap_keywordq  s     	2A2;'!!*%% & &GABBK((!AI	& & & & & & & & & & & & & & &  	$#E### "&&w888s   AAAc                 P   t          |t                    s|                     |          }|                     |          \  }}|                     |          }t          t          t                    5  | j                            ||f          }d d d            n# 1 swxY w Y   |S rN   )	ra   rb   
_cardindexrc   rg   r   
IndexErrorrq   r\   )r]   idxrj   repeatremapped_insert_keywords        rU   r   zCompImageHeader._remap_index  s     #s## 	'//#&&C22377"&"5"5g">">j(++ 	S 	S$//1H&0QRRC	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 
s   2BB"Bc                 z    | j                                          t                                                       dS )z3
        Remove all cards from the header.
        N)r\   clearrO   )r]   rT   s    rU   r   zCompImageHeader.clear  s/     	  """rV   rN   )NTFF)TF)NNFT)__name__
__module____qualname____doc__r   recompiler   setvaluesunionr   r   rP   r^   rf   rp   rz   r   r   r   classmethodre   rg   r   r   __classcell__rT   s   @rU   r8   r8   W   s       
 
   O rzMNNHC 6 6 8 899??BBB  %I$H$H!

( 
( 
( 
( 
( 
(* * *@ @ @ @ @89 9 9 9 96$V $V $V $V $V $VL-V -V -V -V -V -V^C C C C C"
 
 
 
 
 
: ! ! ! [!F 9 9 [9&  $        rV   r8   c                       e Zd ZdZdZ	 dZ	 dZ edddd	          dddede	e
eeeddddf fd
	            Zd Zed             Zej        d             Zed             Z	 	 	 	 	 	 	 	 d'dZd Zed             Zej        d             Ze fd            Zej        d             Zed             Zed             Zd Zd Zd(dZd) fd	Z d Z! fdZ"d* fd 	Z#d! Z$d+d"Z%d# Z&ed$             Z'ed%             Z(ed&             Z) xZ*S ),CompImageHDUz%
    Compressed Image HDU class.
    TFCOMPRESSED_IMAGE	tile_sizeNz5.3zThe tile_size argument has been deprecated. Use tile_shape instead, but note that this should be given in the reverse order to tile_size (tile_shape should be in Numpy C order).)sincemessagec                 4    t                               ||          }||t          |ddd                   }n||t          d          |t          u r$t                                          ||           nHt                                          d|           | _                             ||||||||	|
	  	         | _	        | _
        | _         fdt           j                            dd                    D              _        |rd _        d	 _        n@ j                            d
d           _         j                            dd	           _         j        d          _         j         _         j         _         j         _        dS )a0  
        Parameters
        ----------
        data : array, optional
            Uncompressed image data

        header : `~astropy.io.fits.Header`, optional
            Header to be associated with the image; when reading the HDU from a
            file (data=DELAYED), the header read from the file

        name : str, optional
            The ``EXTNAME`` value; if this value is `None`, then the name from
            the input image header will be used; if there is no name in the
            input image header then the default name ``COMPRESSED_IMAGE`` is
            used.

        compression_type : str, optional
            Compression algorithm: one of
            ``'RICE_1'``, ``'RICE_ONE'``, ``'PLIO_1'``, ``'GZIP_1'``,
            ``'GZIP_2'``, ``'HCOMPRESS_1'``, ``'NOCOMPRESS'``

        tile_shape : tuple, optional
            Compression tile shape, which should be specified using the default
            Numpy convention for array shapes (C order). The default is to
            treat each row of image as a tile.

        hcomp_scale : float, optional
            HCOMPRESS scale parameter

        hcomp_smooth : float, optional
            HCOMPRESS smooth parameter

        quantize_level : float, optional
            Floating point quantization level; see note below

        quantize_method : int, optional
            Floating point quantization dithering method; can be either
            ``NO_DITHER`` (-1; default), ``SUBTRACTIVE_DITHER_1`` (1), or
            ``SUBTRACTIVE_DITHER_2`` (2); see note below

        dither_seed : int, optional
            Random seed to use for dithering; can be either an integer in the
            range 1 to 1000 (inclusive), ``DITHER_SEED_CLOCK`` (0; default), or
            ``DITHER_SEED_CHECKSUM`` (-1); see note below

        Notes
        -----
        The astropy.io.fits package supports 2 methods of image compression:

            1) The entire FITS file may be externally compressed with the gzip
               or pkzip utility programs, producing a ``*.gz`` or ``*.zip``
               file, respectively.  When reading compressed files of this type,
               Astropy first uncompresses the entire file into a temporary file
               before performing the requested read operations.  The
               astropy.io.fits package does not support writing to these types
               of compressed files.  This type of compression is supported in
               the ``_File`` class, not in the `CompImageHDU` class.  The file
               compression type is recognized by the ``.gz`` or ``.zip`` file
               name extension.

            2) The `CompImageHDU` class supports the FITS tiled image
               compression convention in which the image is subdivided into a
               grid of rectangular tiles, and each tile of pixels is
               individually compressed.  The details of this FITS compression
               convention are described at the `FITS Support Office web site
               <https://fits.gsfc.nasa.gov/registry/tilecompression.html>`_.
               Basically, the compressed image tiles are stored in rows of a
               variable length array column in a FITS binary table.  The
               astropy.io.fits recognizes that this binary table extension
               contains an image and treats it as if it were an image
               extension.  Under this tile-compression format, FITS header
               keywords remain uncompressed.  At this time, Astropy does not
               support the ability to extract and uncompress sections of the
               image without having to uncompress the entire image.

        The astropy.io.fits package supports 3 general-purpose compression
        algorithms plus one other special-purpose compression technique that is
        designed for data masks with positive integer pixel values.  The 3
        general purpose algorithms are GZIP, Rice, and HCOMPRESS, and the
        special-purpose technique is the IRAF pixel list compression technique
        (PLIO).  The ``compression_type`` parameter defines the compression
        algorithm to be used.

        The FITS image can be subdivided into any desired rectangular grid of
        compression tiles.  With the GZIP, Rice, and PLIO algorithms, the
        default is to take each row of the image as a tile.  The HCOMPRESS
        algorithm is inherently 2-dimensional in nature, so the default in this
        case is to take 16 rows of the image per tile.  In most cases, it makes
        little difference what tiling pattern is used, so the default tiles are
        usually adequate.  In the case of very small images, it could be more
        efficient to compress the whole image as a single tile.  Note that the
        image dimensions are not required to be an integer multiple of the tile
        dimensions; if not, then the tiles at the edges of the image will be
        smaller than the other tiles.  The ``tile_shape`` parameter may be
        provided as a list of tile sizes, one for each dimension in the image.
        For example a ``tile_shape`` value of ``(100,100)`` would divide a 300 X
        300 image into 9 100 X 100 tiles.

        The 4 supported image compression algorithms are all 'lossless' when
        applied to integer FITS images; the pixel values are preserved exactly
        with no loss of information during the compression and uncompression
        process.  In addition, the HCOMPRESS algorithm supports a 'lossy'
        compression mode that will produce larger amount of image compression.
        This is achieved by specifying a non-zero value for the ``hcomp_scale``
        parameter.  Since the amount of compression that is achieved depends
        directly on the RMS noise in the image, it is usually more convenient
        to specify the ``hcomp_scale`` factor relative to the RMS noise.
        Setting ``hcomp_scale = 2.5`` means use a scale factor that is 2.5
        times the calculated RMS noise in the image tile.  In some cases it may
        be desirable to specify the exact scaling to be used, instead of
        specifying it relative to the calculated noise value.  This may be done
        by specifying the negative of the desired scale value (typically in the
        range -2 to -100).

        Very high compression factors (of 100 or more) can be achieved by using
        large ``hcomp_scale`` values, however, this can produce undesirable
        'blocky' artifacts in the compressed image.  A variation of the
        HCOMPRESS algorithm (called HSCOMPRESS) can be used in this case to
        apply a small amount of smoothing of the image when it is uncompressed
        to help cover up these artifacts.  This smoothing is purely cosmetic
        and does not cause any significant change to the image pixel values.
        Setting the ``hcomp_smooth`` parameter to 1 will engage the smoothing
        algorithm.

        Floating point FITS images (which have ``BITPIX`` = -32 or -64) usually
        contain too much 'noise' in the least significant bits of the mantissa
        of the pixel values to be effectively compressed with any lossless
        algorithm.  Consequently, floating point images are first quantized
        into scaled integer pixel values (and thus throwing away much of the
        noise) before being compressed with the specified algorithm (either
        GZIP, RICE, or HCOMPRESS).  This technique produces much higher
        compression factors than simply using the GZIP utility to externally
        compress the whole FITS file, but it also means that the original
        floating point value pixel values are not exactly preserved.  When done
        properly, this integer scaling technique will only discard the
        insignificant noise while still preserving all the real information in
        the image.  The amount of precision that is retained in the pixel
        values is controlled by the ``quantize_level`` parameter.  Larger
        values will result in compressed images whose pixels more closely match
        the floating point pixel values, but at the same time the amount of
        compression that is achieved will be reduced.  Users should experiment
        with different values for this parameter to determine the optimal value
        that preserves all the useful information in the image, without
        needlessly preserving all the 'noise' which will hurt the compression
        efficiency.

        The default value for the ``quantize_level`` scale factor is 16, which
        means that scaled integer pixel values will be quantized such that the
        difference between adjacent integer values will be 1/16th of the noise
        level in the image background.  An optimized algorithm is used to
        accurately estimate the noise in the image.  As an example, if the RMS
        noise in the background pixels of an image = 32.0, then the spacing
        between adjacent scaled integer pixel values will equal 2.0 by default.
        Note that the RMS noise is independently calculated for each tile of
        the image, so the resulting integer scaling factor may fluctuate
        slightly for each tile.  In some cases, it may be desirable to specify
        the exact quantization level to be used, instead of specifying it
        relative to the calculated noise value.  This may be done by specifying
        the negative of desired quantization level for the value of
        ``quantize_level``.  In the previous example, one could specify
        ``quantize_level = -2.0`` so that the quantized integer levels differ
        by 2.0.  Larger negative values for ``quantize_level`` means that the
        levels are more coarsely-spaced, and will produce higher compression
        factors.

        The quantization algorithm can also apply one of two random dithering
        methods in order to reduce bias in the measured intensity of background
        regions.  The default method, specified with the constant
        ``SUBTRACTIVE_DITHER_1`` adds dithering to the zero-point of the
        quantization array itself rather than adding noise to the actual image.
        The random noise is added on a pixel-by-pixel basis, so in order
        restore each pixel from its integer value to its floating point value
        it is necessary to replay the same sequence of random numbers for each
        pixel (see below).  The other method, ``SUBTRACTIVE_DITHER_2``, is
        exactly like the first except that before dithering any pixel with a
        floating point value of ``0.0`` is replaced with the special integer
        value ``-2147483647``.  When the image is uncompressed, pixels with
        this value are restored back to ``0.0`` exactly.  Finally, a value of
        ``NO_DITHER`` disables dithering entirely.

        As mentioned above, when using the subtractive dithering algorithm it
        is necessary to be able to generate a (pseudo-)random sequence of noise
        for each pixel, and replay that same sequence upon decompressing.  To
        facilitate this, a random seed between 1 and 10000 (inclusive) is used
        to seed a random number generator, and that seed is stored in the
        ``ZDITHER0`` keyword in the header of the compressed HDU.  In order to
        use that seed to generate the same sequence of random numbers the same
        random number generator must be used at compression and decompression
        time; for that reason the tiled image convention provides an
        implementation of a very simple pseudo-random number generator.  The
        seed itself can be provided in one of three ways, controllable by the
        ``dither_seed`` argument:  It may be specified manually, or it may be
        generated arbitrarily based on the system's clock
        (``DITHER_SEED_CLOCK``) or based on a checksum of the pixels in the
        image's first tile (``DITHER_SEED_CHECKSUM``).  The clock-based method
        is the default, and is sufficient to ensure that the value is
        reasonably "arbitrary" and that the same seed is unlikely to be
        generated sequentially.  The checksum method, on the other hand,
        ensures that the same seed is used every time for a specific image.
        This is particularly useful for software testing as it ensures that the
        same image will always use the same seed.
        Nr!   ztCannot specify both tile_size and tile_shape. Note that tile_size is deprecated and tile_shape alone should be used.dataheader)compression_type
tile_shapehcomp_scalehcomp_smoothquantize_levelquantize_methoddither_seedc           	      l    g | ]0}j                             d t          |dz             z   d          1S )r0   r   r   )_headerr   rw   ).0axisr]   s     rU   
<listcomp>z)CompImageHDU.__init__.<locals>.<listcomp>  sJ     
 
 
 LXD1H5q99
 
 
rV   r0   r   r   BZEROBSCALEr1   )CMTYPE_ALIASESr   rd   rx   r   rO   r^   r   _update_header_data_do_not_scale_image_data_uint_scale_backranger   _axes_bzero_bscale_bitpix_orig_bzero_orig_bscale_orig_bitpix)r]   r   r   namer   r   r   r   r   r   r   do_not_scale_image_datauint
scale_backr   rT   s   `              rU   r^   zCompImageHDU.__init__  s   F *--.>@PQQ)"7y2//JJ#	(=(   7??GG$v6666 GG$v666 DI $$!1%')- /' % 
 
 
 )@%
%
 
 
 
dl..x;;<<
 
 

 # 	9DKDLL,**7A66DK<++Ha88DL|I.; L LrV   c                     dv r{j         d         }t          |          }|dk    r[ fd|D             }t          |          |k    r|                    d           t          t	          |                    D ]	}|= dS dS dS )a$  Remove default EXTNAME values if they are unnecessary.

        Some data files (eg from CFHT) can have the default EXTNAME and
        an explicit value.  This method removes the default if a more
        specific header exists. It also removes any duplicate default
        values.
        EXTNAMEr   c                 6    g | ]}|         j         k    |S  )_default_name)r   rk   r   r]   s     rU   r   zECompImageHDU._remove_unnecessary_default_extnames.<locals>.<listcomp>  s1     & & &#&-4CU2U2UE2U2U2UrV   r   N)rY   r   popreversedsorted)r]   r   indices	n_extnameextnames_to_removerk   s   ``    rU   $_remove_unnecessary_default_extnamesz1CompImageHDU._remove_unnecessary_default_extnames  s     -i8GGI1}}& & & & &'.& & &" )**i77&**1---%f-?&@&@AA & &Eu  }& &rV   c                 \    t          | j                            d| j                            S )Nr   )rw   r   r   r   r]   s    rU   r   zCompImageHDU.name  s%    
 4;??9d.@AABBBrV   c                     t          |t                    st          d          t          j        s|                                }d| j        v r|| j        d<   d S |df| j        d<   d S )Nz!'name' attribute must be a stringr   zextension name)ra   rw   	TypeErrorr   extension_name_case_sensitiver   r   )r]   ri   s     rU   r   zCompImageHDU.name  su     %%% 	A?@@@1 	"KKMME##%*DK	"""&+-=%>DK	"""rV   c                     |j         d         }|j        dk    rdS |j        }t          |t                    r|                                }|dvrdS d|vs|d         sdS t          S )Nr   r?   F)BINTABLEA3DTABLEr/   )cardsrj   ri   ra   rw   rstripCOMPRESSION_ENABLED)rQ   r   rs   xtensions       rU   match_headerzCompImageHDU.match_header  sx    |A<:%%5:h$$ 	)((H33356!!)9!5""rV   c
           
      !   |                      | j                   t          | j        | j                  }
t	          | j        |
j                  | _        |
j        | _        ~
| j        r| j        j	        dk    }nd}|s-d| j        vr$| j        
                    d| j        dd           n	|r|| _        |r|t          vret          j        d                    d	                    t%          t&          t                              t(                    t*                     t(          }| j        
                    d
|dd           n"| j        }t.                              ||          }|rv|                    dd          }|                    dd          }d}|dk    r| j        
                    d||           d}|dk    r| j        
                    d||           	 |j        d         }n# t4          t6          f$ r d}Y nw xY w	 |j        d         }n# t4          t6          f$ r d}Y nw xY w| j        
                    dddd           |dk    r|rdnd}n|rdnd}| j        
                    d|dd           t9          | j        d         |          }| j        d         }|dk     r:|dk    r3d }d!}|rdnd}| j        
                    d"|d#d           | j        
                    d$|dd"           t9          ||          }| j        
                    d%d&d'd$           | j        
                    d(d)d*d%           t9          | j        d%         | j        d(                   }| j        
                    d+d,d-d(           | j        
                    d.d)d*d+           d.}t9          | j        d+         | j        d.                   }t;          ||||g          }n6d/}d}g d0}|D ]}	 | j        |= # t6          $ r Y w xY wt;          |g          }| j        
                    d1|j        j        d2           | j        
                    d|d3d4           | j        
                    d5d6d7|           | j        
                    d8||d5           | j        
                    d9| j        d         |d8           tA          j!        d/          D ]D}	 | j        d9tE          |          z   = | j        d:tE          |          z   = 4# t6          $ r Y  nw xY w| j        d         }|sg }n/tG          |          |k    rt          j        d;t*                     g }|d<k    r| j        d1         d k     s| j        d=         d k     rtI          d>          |rU|d?         d k     s|d@         d k     rtI          dA          tG          dB |D                       } | dCk    rtI          dD          |rQ|d?         dk    rE|d@         dk    r9| j        d1         |d?<   | j        d=         |d@<   tK          dC|          D ]}!d/||!<   n|s| j        d1         g}| j        d=         dEk    r"|&                    d| j        d1                    nR| j        d=         }"dFD ],}#|"|#z  dk    s	|"|#z  dGk    r|&                    d|#            n-|&                    ddH           tK          dC|          D ]}!|&                    dd/           | j        d1         |d?         z  }$|dIdI         }%|$dk    rG|$d k     rA|d?xx         d/z  cc<   | j        d1         |d?         z  }$|$dk    r|$d k     rtI          dJ          | j        d=         |d@         z  }$|$dk    rG|$d k     rA|d@xx         d/z  cc<   | j        d=         |d@         z  }$|$dk    r|$d k     rtI          dK          ||%k    r!t          j        dL|% dM| dNtN                     d9}&| j        d         dk    rdO}'nd9}'d}(tQ          | j                  D ]I\  }})dtE          |d/z             z   }d9tE          |d/z             z   }*d:tE          |d/z             z   }+|r7tG          |          |d/z   k    r!|tG          | j                  d/z
  |z
           },n?|+| j        vr|s| j        d1         },nd/},n| j        |+         },|&                    d|,           |(s|)d/z
  |,z  d/z   }(n|(|)d/z
  |,z  d/z   z  }(|r.||v r*| j        
                    |*|)|j        |         |&           n| j        
                    |*|)dP|&           | j        
                    |+|,dQ|'           |*}&|+}'K| j        
                    d=|(dR           || _)        tA          j!        d/          D ]}dStE          |          z   }-|-| j        vr nsdTtE          |          z   }.| j        |-         dUk    r|| j        |.         }| j        |-         dVk    r|| j        |.         }| j        |-         dWk    r|| j        |.         }|tT          }|tV          }|tV          }tA          j!        d/          D ]A}dStE          |          z   }-|-| j        vr n#dTtE          |          z   }.| j        |-= | j        |.= Bd
}d/}|dXk    r| j        
                    dYdZd[|           | j        
                    d\tX          d]dY           | j        
                    d^d_d`d\           | j        d8         dak    rd/}/n| j        d8         dbk    rdC}/ntZ          }/| j        
                    dc|/d`d^           dc}dG}n|d<k    r|| j        
                    dYddde|           | j        
                    d\|dedY           | j        
                    d^dfdgd\           | j        
                    dc|dgd^           dc}dG}| j        d         dk     r	| j        
                    dStE          |          z   dUdh|           | j        
                    dTtE          |          z   |dhdStE          |          z              |r|t\          t^          t`          fvr@tb          td                   }t          j        di                    |                     td          }|t\          k    rdj}0ndk}0| j        
                    dltb          |         |0dTtE          |          z              nw| j                            dlt\                    }tg          |tD                    rBtb          4                                D ]!\  }}1|15                                |k    r|} n"t\          }|t\          k    rdm| j        v r| j        dm= ng|	r| 6                    |	          }	n1dm| j        v r| j        dm         }	n| 6                    tn                    }	| j        
                    dm|	dndl           |rdo|v r/| j        
                    dp|do         |j        do         d8q           dr|v r-| j        
                    ds|dr         |j        dr                    dt|v r-| j        
                    du|dt         |j        dt                    dv|v r)| j        
                    dwdx|j        dv         d8q           dy|v r/| j        
                    dz|dy         |j        dy         |&           d4|v r/| j        
                    d{|d4         |j        d4         dz           d||v r-| j        
                    d}|d|         |j        d|                    d~|v r-| j        
                    d|d~         |j        d~                    ndv| j        v r.| j        
                    dwdx| j        j        dv         d8q           dy| j        v r9| j        
                    dz| j        dy         | j        j        dy         |&           d4| j        v r9| j        
                    d{| j        d4         | j        j        d4         dz           d}| j        v r|8                                }2| j        8                                }3| j        8                                }4tK          |2|3z
            D ] }5| j        9                                 |4d/z  }4!tK          |2|4z
            D ]}5| j        9                                 dIS dIS )a	  
        Update the table header (`_header`) to the compressed
        image format and to match the input data (if any).  Create
        the image header (`_image_header`) from the input image
        header (if any) and ensure it matches the input
        data. Create the initially-empty table data array to hold
        the compressed data.

        This method is mainly called internally, but a user may wish to
        call this method after assigning new data to the `CompImageHDU`
        object that is of a different type.

        Parameters
        ----------
        image_header : `~astropy.io.fits.Header`
            header to be associated with the image

        name : str, optional
            the ``EXTNAME`` value; if this value is `None`, then the name from
            the input image header will be used; if there is no name in the
            input image header then the default name 'COMPRESSED_IMAGE' is used

        compression_type : str, optional
            compression algorithm 'RICE_1', 'PLIO_1', 'GZIP_1', 'GZIP_2',
            'HCOMPRESS_1', 'NOCOMPRESS'; if this value is `None`, use value
            already in the header; if no value already in the header, use
            'RICE_1'

        tile_shape : tuple of int, optional
            compression tile shape (in C order); if this value is `None`, use
            value already in the header; if no value already in the header,
            treat each row of image as a tile

        hcomp_scale : float, optional
            HCOMPRESS scale parameter; if this value is `None`, use the value
            already in the header; if no value already in the header, use 1

        hcomp_smooth : float, optional
            HCOMPRESS smooth parameter; if this value is `None`, use the value
            already in the header; if no value already in the header, use 0

        quantize_level : float, optional
            floating point quantization level; if this value is `None`, use the
            value already in the header; if no value already in header, use 16

        quantize_method : int, optional
            floating point quantization dithering method; can be either
            NO_DITHER (-1), SUBTRACTIVE_DITHER_1 (1; default), or
            SUBTRACTIVE_DITHER_2 (2)

        dither_seed : int, optional
            random seed to use for dithering; can be either an integer in the
            range 1 to 1000 (inclusive), DITHER_SEED_CLOCK (0; default), or
            DITHER_SEED_CHECKSUM (-1)
        r   l        Fr   z#name of this binary table extensionr   r~   z\Unknown compression type provided (supported are {}). Default ({}) compression will be used.z, r4   zcompression algorithmr   g        r   g      ?r@   zdata type of original imagerA   zdimension of original imageTTYPE1COMPRESSED_DATAzlabel for field 1r*   1QI1PI1QB1PBTFORM1z+data format of field: variable length array)r   ry   r   r-   GZIP_COMPRESSED_DATATTYPE2zlabel for field 2TFORM2TTYPE3ZSCALEzlabel for field 3TFORM31Dz#data format of field: 8-byte DOUBLETTYPE4ZZEROzlabel for field 4TFORM4r   )r  r  r  r  r  r	  NAXIS1zwidth of table in bytesznumber of fields in each rowrE   r/   Tz#extension contains compressed imager1   r0   rL   zQProvided tile size not appropriate for the data.  Default tile size will be used.r+   NAXIS2z-Hcompress minimum image dimension is 4 pixelsr!   z,Hcompress minimum tile dimension is 4 pixelsc                     g | ]
}|d k    |S )r   r   )r   tss     rU   r   z4CompImageHDU._update_header_data.<locals>.<listcomp>?  s    !D!D!DR!VV"VVVrV   r"   znHCOMPRESS can only support 2-dimensional tile sizes.All but two of the tile_shape dimensions must be set to 1.   )	         r                       Nz4Last tile along 1st dimension has less than 4 pixelsz4Last tile along 2nd dimension has less than 4 pixelszyThe tile shape should be such that no tiles have fewer than 4 pixels. The tile shape has automatically been changed from z to za, but in future this will raise an error and the correct tile shape should be specified directly.ZNAXIS1zlength of original image axiszsize of tiles to be compressedznumber of rows in tablerK   rJ   NOISEBITzSCALE   zSMOOTH  r'   ZNAME1	BLOCKSIZEzcompression block sizeZVAL1zpixels per blockZNAME2BYTEPIXzbytes per pixel (1, 2, 4, or 8)   r  ZVAL2SCALEzHCOMPRESS scale factorSMOOTHzHCOMPRESS smooth optionz!floating point quantization levelz@Unknown quantization method provided.  Default method ({}) used.z No dithering during quantizationzPixel Quantization AlgorithmrH   rI   z'dithering offset when quantizing floatsr>   r3   r   rB   r2   rC   r9   r?   r6   IMAGErD   r:   r;   rF   r<   rG   r=   ):r   r   r   r   r8   r   _image_headerr   	_has_datanbytesr   r   r   COMPRESSION_TYPESr   r   ry   joinmapreprDEFAULT_COMPRESSION_TYPEr   r   r   r   commentsAttributeErrorrq   r   r   dtypeitemsize	itertoolscountrw   r   rx   r   r   r   	enumeratecolumnsDEFAULT_QUANTIZE_LEVELDEFAULT_HCOMP_SCALEDEFAULT_BLOCK_SIZEDEFAULT_BYTE_PIXr#   r$   r%   QUANTIZE_METHOD_NAMESDEFAULT_QUANTIZE_METHODra   itemsr   _generate_dither_seedDEFAULT_DITHER_SEED_countblanksrz   )6r]   rS   r   r   r   r   r   r   r   r   	image_hduhuge_hdubzerobscaleafter_keywordbitpix_commentnaxis_commenttform1col1zbitpixncolsttype2tform2col2col3r~   col4cols	to_removekr   naxis
major_dimsinaxis2dimremainoriginal_tile_shapelast_znaxisafter1nrowsr   znaxisztiler  znamezvalbytepixzquantiz_commentvrequired_blanksimage_blankstable_blanks_s6                                                         rU   r   z CompImageHDU._update_header_data  s8   H 	11$,???$)DLAAA	,T\9;KLL_
 > 	y'%/HHH  		55 L"5	       	DI  	V'888==CV		#d,=">">??0> > '   $< L,.EY       $4-112BDTUU
  
	F $$Wc22E!%%h44F%M}}  6 GGG (||  %} EEE	;)28<NN) 	; 	; 	;:NNN	;	:(1':MM) 	: 	: 	:9MMM	:
 	')<I 	 	
 	
 	
 x''&1UUEFF&1UUEF9	 	 	
 	
 	
 4<1&AAA
 $X.Q;;>S00 E ,F '1UUEF LXv/B(SSSL=	     vf555D LXx1DHUUUL$ EX     t|H5dl8>TUUUD LXw0C8TTTL$ EX     Et|H5dl8>TUUUD D$d344DD EE UTTI  Q   D D6??D 	4:#68QRRRu<H 	 	
 	
 	
 	dA 	 	
 	
 	
 	G^8LLLd(1=	 	 	
 	
 	
 ?1%% 	 	CLCHH!45L3s88!344    "7+ 	JJ__%%M2"  
 J },,!(+a//43Eh3ORS3S3S !PQQQ 
b>A%%B!););$%STTT !D!Dz!D!D!DEE
>>$     &,z"~22z"~7J7J!%!3H!=
2!%!3H!=
2q% & &A$%JqMM&   , #0:;
%h/255%%a);H)EFFFF "/9FC 1 1!C<1,,q0@0@&--a555!E 1A #))!R000q% , ,A%%a++++
 '1JrNBF",QQQ-zzfqjj2!#+H5
2FA::&1**$N   '1JrNBFzzfqjj2!#+H5
2FA::&1**$N   000!7J! ! %! ! ! .   g&**FFF "4:.. "	 "	ICc#'ll*EC!G,Fc#'ll*E )c*ooq88DJ! 3c 9:,, !/9e,B!!!R((( .b(1,$(r)A--  5 5  D,"7">k !       D"A !    LUB(HPVWWW KFF 	5*CDDD ?1%% 	6 	6Cc#hh&EDL((CHH$D|E"j00!)%)\$%7N|E"j00&"&,t"4K|E"j00'#'<#5L!3N-K.L ?1%% 	# 	#Cc#hh&EDL((CHH$DU#T""
 #x''L+'?}     L+-?x     L)%Fg     |I&!++i(B..*L"C8     $MCC..L'#;=     L&>h     L($=W     L'@     $MCh'!++L#c(("3#	     LS!3C(	      $4"((+  
 11HIDM44:F4LL   '>O"i//'I$$'E$  )/:$ 3s88+	 !     #',"2"2:y"I"Ios33 4 5 ; ; = = 4 41779977./O!E 8 +4)++-- Z0 R"&"<"<["I"IKK4<//"&,z":KK"&"<"<=P"Q"QK  =$	 !     o	 <''   * )(3$	 !    <''  |H5|7LX7V   L((   + ))4   \))   )*5$	 !    <''   * )(3%	 !    <''   * )(3#	 !    \))   , )*5   L((   + ))4   T///  &/
;$	 !    4---  &x0&/9%	 !    4---  &x0&/9#	 !    %%*7799O-::<<L<4466L?\9:: " ""))+++!?\9:: & &##%%%% &%& &sH   G, ,HHH H*)H*3O<<
P	P	0T
TTc                    | j         dk    s| j        dk    r|                                 }t          j        ||          }d| j        v r&|t          j        | j        d         d          k    }nd }| j        dk    rt          j        || j        |           | j         dk    rt          j        || j         |d           | t          j        |t          j	        |          }|S )Nr   r   r1  BLANKint32unsafeoutcasting)
r   r   _dtype_for_bitpixnparrayr   multiplyaddwherenan)r]   r   	new_dtypeblankss       rU   _scale_datazCompImageHDU._scale_data  s    q  D$5$:$:..00I8D	222D$,&&$,w*?w!O!O!OO A%%D$"3T:::1$$
 tT-4JJJJ!x55rV   c                     t          | j                  dk    rdS | j        d         }|                     |j                   |S )aE  
        The decompressed data array.

        Note that accessing this will cause all the tiles to be loaded,
        decompressed, and combined into a single data array. If you do
        not need to access the whole array, consider instead using the
        :attr:`~astropy.io.fits.CompImageHDU.section` property.
        r   N.)r   compressed_datasection_update_header_scale_infor1  r]   r   s     rU   r   zCompImageHDU.data  sJ     t#$$))4
 |C  	&&tz222rV   c                     |`t          |t          j                  r|j        j        <t          d                    t          |          |j        j                            d S d S )Nz:CompImageHDU data has incorrect type:{}; dtype.fields = {})ra   rr  ndarrayr1  fieldsr   ry   typer  s     rU   r   zCompImageHDU.data  sj    4,, 04
0A0MLSSJJ
 1    0M0MrV   c                     t                      j        }t          |t          j        j                  r
| j        d= |S |                                  | j        S )Nr   )	rO   r   ra   rr  recrecarray__dict___update_compressed_datar|  )r]   r|  rT   s     rU   r|  zCompImageHDU.compressed_data(  sU      '',orv77 
	+ f%""
 ((***##rV   c                 F    d| j         v r| j         d         `| j         d= d S d S )Nr|  )r  _coldefsr   s    rU   r|  zCompImageHDU.compressed_data;  s:     --/09
 /000 .-rV   c                 D    t          t          | j                            S )zX
        Shape of the image array--should be equivalent to ``self.data.shape``.
        )rd   r   r   r   s    rU   shapezCompImageHDU.shapeI  s     Xdj))***rV   c                 V   t          | d          r| j        S |                     | j                   | j                                        }t          |          D ]!}t                              |d          r||= "| j        j        }d| j        v r.|                    d| j        d         |d         d           |d= nld	| j        v rK| j        d	         d
k    rt          j
        dt                     |                    dd
|d	         d           n|                    dd
d           |                    d| j        d         |d         d           |                    d| j        d         |d         d           d}t          |d                   D ]M}dt          |dz             z   }|dd          }|                    || j        |         ||         |           |}N|d         }t          |d                   D ]4}	 t          |dd                    }n# t           $ r Y 'w xY w||k    r||= 5d| j        v r+|                    d| j        d         |d         |           n|                    dd|           d| j        v r+|                    d| j        d         |d         d           n|                    ddd           d| j        v r(|                    d| j        d         |d                    d| j        v r(|                    d| j        d         |d                    d| j        v r(|                    d| j        d         |d                    d| j        v r(|                    d | j        d         |d                    d!|v r|d!         | j        k    r|d!= d|v r|d= |d= | j                                        }	|                                }
t          |	|
z
            D ]}|                                 t          | j        |          | _        | j        S )"Nr'  F)r   r3   r>   r   r%  r?   r6   r&  z3ZTENSION keyword in compressed extension != 'IMAGE'r@   r1   r   rA   r0   r"   r   zNAXIS?*r   r:   rD   r;   rE   r2   rB   r9   rC   r<   rF   r=   rG   r   )hasattrr'  r   r   copyr   r8   re   r/  r   r   r   r   rw   listrb   	Exceptionr   r@  rz   )r]   rS   rj   	hcomments
last_naxisr   r^  rT  nrg  rf  rh  s               rU   r   zCompImageHDU.headerQ  s    4)) 	&%%
 	11$,??? |((** <(( 	* 	*G33G%3HH * )L)	$$$,y19Y3GPQ     Z((4<''|J'722I&   Z)J2GPQRRRRZ;;;dl9-y/CA 	 	
 	
 	
 	$,x"8)H:MVWXXX
g.// 	 	CC!G,F122JEt|F+Yv->j     JJ W%L344 	* 	*G$$    5yy )
 $$Y')$ 	      Xq
;;;$$$,y19Y3Gx      Xq999$$Xt|I'>	)@TUUU%%YZ(@)JBWXXX %%DL4i
6K   %%YZ(@)JBWXXX $$i)@DDV)V)VY' |##X&X& |0022#0022|l233 	" 	"A!!!!
 -T\<HH!!s   H
H)(H)c                    | j         j        }| j        r{| j        d\  }}nt	          | j        j                  }| j        j        j        }|                                 t          |          }||
                    d          dz   d         }n[d}t          | j        d                   D ]&}|| j        dt          |dz             z            fz  }'t          | j        d                  }| j        | j        |t!          | j                  ||fS )zC
        Summarize the HDU: name, dimensions, and formats.
        N)r    .r   r   rA   r@   )rT   r   _data_loadedr   r  r  r1  r   reverserd   rfindr   r   rw   r   verr   )r]   
class_name_shape_formatr   s        rU   _summaryzCompImageHDU._summary  s	    ^,
  	:y "( dio..)/.   v!'--"4"4q"8":":; FT[122 A A4;wS1W'=>@@"4;x#89G	48ZT[1A1A67SSrV   c                    t           | j        j        j                 }|| j        k    s| j        j        | j        k    r|                     | j                   | j        }t          | j        j                  rLt          j
        | j        t          | j        j                  z
  d| j        j        j                   | _        	 | j        d         }| j        d         |z  }d| j        d<   d| j        v r| j        d= || _        | `t!          |           \  }| _        || _        n# || _        w xY w| j        j                            d          }| j        }|d	| j                                     |t          j        j        
          }|                    t,                    | _        | j        | j        _        | j        | j        _        || j        _        d	S )zN
        Compress the image data so that it may be written to a file.
        z=irj  r  r
  r   rD   THEAP>N)r1  r  )r   r   r1  r   r   r  r   r   r   rr  rs  r   r2  r   _theapr|  r   r6  newbyteorderviewr  r  r   r  _heapoffset	_heapsize)	r]   image_bitpixold_datar]  tbsizeheapsizer1  bufr|  s	            rU   r  z$CompImageHDU._update_compressed_data  s   
 $DIO$894,,,	4:0M0M$$T[111 9dio.. 		L999549?355  DI
	!L*E\(+e3F%&DL"$,&&L) DK $
 .:$-?-?*Hd* DIIDI     "//44"mm,11BFO1TT.33H==(,%+/;()1&&&s   AD$ $	D-oldr   r   c                    | j         dS |t          | j                 }t          t          |          }|dk    s|dk    r|}|}n|dk    r| j        }| j        }n|dk    rt          |t          j                  rd}d}nt          j	        
                    | j         j                  }t          j        
                    | j         j                  }	|t          j        k    r|}|	|z
  dz  }n|	|z   dz  }|	|z
  dd|j        z  z  d	z
  z  }|dk    r-t	          j        | j         || j         d
           || j        d<   n@| j        | j        fD ]1}
t%          t&                    5  |
d= ddd           n# 1 swxY w Y   2|dk    r| xj         |z  c_         || j        d<   n@| j        | j        fD ]1}
t%          t&                    5  |
d= ddd           n# 1 swxY w Y   2| j         j        j        |k    r2t	          j        t	          j        | j                   |          | _         t0          | j         j        j                 | _        | j                            dd          | _        | j                            dd          | _        | j        | j        d<   |                     | j                   | j        | _        | j        | _        | j        | _        dS )ab  
        Scale image data by using ``BSCALE`` and ``BZERO``.

        Calling this method will scale ``self.data`` and update the keywords of
        ``BSCALE`` and ``BZERO`` in ``self._header`` and ``self._image_header``.
        This method should only be used right before writing to the output
        file, as the data will be scaled and is therefore not very usable after
        the call.

        Parameters
        ----------
        type : str, optional
            destination data type, use a string representing a numpy dtype
            name, (e.g. ``'uint8'``, ``'int16'``, ``'float32'`` etc.).  If is
            `None`, use the current data type.

        option : str, optional
            how to scale the data: if ``"old"``, use the original ``BSCALE``
            and ``BZERO`` values when the data was read/created. If
            ``"minmax"``, use the minimum and maximum of the data to scale.
            The option will be overwritten by any user-specified bscale/bzero
            values.

        bscale, bzero : int, optional
            user specified ``BSCALE`` and ``BZERO`` values.
        Nr   r   r  minmaxg     o@g       @r!  r"   rm  rn  r   r   rj  r@   )r   r   r   getattrrr  r   r   ra   floatingminimumreduceflatmaximumuint8bytessubtractr   r   r   rq   r1  r  rs  aroundr   r   r   r   r   r   r   )r]   r  optionrD  rC  _type_scale_zero_min_maxr   s              rU   scalezCompImageHDU.scale)  sN   6 9F <-DD!! Q;;%1**FEE*(8##eR[11 PFEE:,,TY^<<D:,,TY^<<D(( $"&+*!=!% 3 #'+#!ek/2JQ2N!O A::
 K	5diJJJJ#(DK    ;5 ( (h'' ( (w( ( ( ( ( ( ( ( ( ( ( ( ( ( ( Q;;IIII$*DK!!;5 ) )h'' ) )x() ) ) ) ) ) ) ) ) ) ) ) ) ) ) 9?5((49!5!5UCCCDI $DIO$89koogq11{x33
 !%H 	  ---
 !L; Ls$    E00E4	7E4	GG	G	c                    | j         r%|                     t          | j                            | j        r|                                  |                                  t          | j        | j	                  }|
                    |           d|j	        v r7| j                            d|j	        d         |j	        j        d                    d|j	        v r7| j                            d|j	        d         |j	        j        d                    | j        | _        | j        | j        d<   t#                                          ||          S )Nr   rF   rG   r   )checksuminplace)r   r  r   r   r(  r  !_update_pseudo_int_scale_keywordsr   r   r   _update_checksumr'  r   r/  
_imagedatar|  r  rO   _prewriteto)r]   r  r  rA  rT   s       rU   r  zCompImageHDU._prewriteto  sK    	8JJ|D$56777>  	9((*** 22444 !diDDDI&&x000Y--- "&&$Z0$-j9  
 I,,,"&&$Y/$-i8   #iDO
 %)$8DM&!ww""Hg"FFFrV   c                 ,    t          j        | |          S )z
        Bypasses `BinTableHDU._writeheader()` which updates the header with
        metadata about the data that is meaningless here; another reason
        why this class maybe shouldn't inherit directly from BinTableHDU...
        )r   _writeheader)r]   fileobjs     rU   r  zCompImageHDU._writeheader  s     (w777rV   c                     	 t                                          |          t          | d          r| j        | j        d<   | `S | `S # t          | d          r| j        | j        d<   | `n| `w xY w)z
        Wrap the basic ``_writedata`` method to restore the ``.data``
        attribute to the uncompressed image data in the case of an exception.
        r  r   )rO   
_writedatar  r  r  r   )r]   r  rT   s     rU   r  zCompImageHDU._writedata  s    
	77%%g.. t\** (,f%OOII	 t\** (,f%OOIs    A &A.c                     t                                          |           |r| j        rt          | j                  | `d S d S d S d S )N)closed)rO   _closer  r   r|  )r]   r  rT   s     rU   r  zCompImageHDU._close  sl    f%%% 	%!	%   455A$$$	% 	% 	% 	% BArV   c                 d   | j         }| j        rm| j        dk    rbdt          j        d          fdt          j        d          fdt          j        d          ffD ] \  }}||k    r| j        d|dz
  z  k    r|c S !|dk    rt          j        d          S |d	k    rt          j        d
          S dS )z
        Determine the dtype that the data should be converted to depending on
        the BITPIX value in the header, and possibly on the BSCALE value as
        well.  Returns None if there should not be any change.
        r   r  uint16r,   uint32@   uint64float64r   float32N)r   r   r   rr  r1  r   )r]   bitpixbitsr1  s       rU   rq  zCompImageHDU._dtype_for_bitpix  s     ": 	!$+q00RXh''(RXh''(RXh''(  ! !e
 T>>d&6!q/&I&I LLLB;;8I&&&aZZ8I&&& ZrV   c                    | j         s| j        dk    r| j        dk    sdD ]V}| j        | j        fD ]E}t          t                    5  ||= |                                 d d d            n# 1 swxY w Y   FW||                                 }|t          |j
                 | j        d<   d| _        d| _        | j        d         | _        d S d S d S )Nr   r   )r   r   r@   )r   r   r   r   r   r   rq   rz   rq  r   r   r   r   r   )r]   r1  rj   r   s       rU   r~  z&CompImageHDU._update_header_scale_info  s1   , 	1!!d&71&<&<. 	( 	(  ${DL9 ( (F!(++ ( ("7O ( ( ( ( ( ( ( ( ( ( ( ( ( ( (( }..00 (4UZ(@H%DKDL;x0DLLL+	1 	1&<&<s   A**A.1A.c                 X   t          |          st          d          d|cxk    rdk    s$n t          d                    |                    |t          k    rr| j        }| j        t          d |D                                }|                    d          	                                }t          j        |          j        dz  dz   S |t          k    rRt          d	 t          j        t!          j                              D                       t#          |           z   dz  dz   S |S )
NzSeed must be an integerr!   i'  zSeed for random dithering must be either between 1 and 10000 inclusive, 0 for autogeneration from the system clock, or -1 for autogeneration from a checksum of the first image tile (got {})c              3   4   K   | ]}t          |          V  d S rN   )rn   )r   ds     rU   	<genexpr>z5CompImageHDU._generate_dither_seed.<locals>.<genexpr>   s(      (E(Eaq(E(E(E(E(E(ErV   r  rj  r   c              3   4   K   | ]}t          |          V  d S rN   )rb   )r   xs     rU   r  z5CompImageHDU._generate_dither_seed.<locals>.<genexpr>3  s(      <<SVV<<<<<<rV   )r   r   rx   ry   DITHER_SEED_CHECKSUMr   r   rd   r  sumctypesc_ulongri   DITHER_SEED_CLOCKmathmodftimeid)r]   seed	tile_dims
first_tilecsums        rU   r>  z"CompImageHDU._generate_dither_seed  s8   t}} 	75666T""""U""""& '-fTll	   '''I 5(E(E9(E(E(E#E#EFJ
 ???115577D
 N4((.6!;;&&& <<TYty{{%;%;<<<<<r$xxG5P  KrV   c                      t          |           S )a  
        Efficiently access a section of the image array

        This property can be used to access a section of the data without
        loading and decompressing the entire array into memory.

        The :class:`~astropy.io.fits.CompImageSection` object returned by this
        attribute is not meant to be used directly by itself. Rather, slices of
        the section return the appropriate slice of the data, and loads *only*
        that section into memory. Any valid basic Numpy index can be used to
        slice :class:`~astropy.io.fits.CompImageSection`.

        Note that accessing data using :attr:`CompImageHDU.section` will always
        load tiles one at a time from disk, and therefore when accessing a large
        fraction of the data (or slicing it in a way that would cause most tiles
        to be loaded) you may obtain better performance by using
        :attr:`CompImageHDU.data`.
        )CompImageSectionr   s    rU   r}  zCompImageHDU.section8  s    (  %%%rV   c                 t     t           fdt           j        d         dz
  dd          D                       S )zn
        The tile shape used for the tiled compression.

        This shape is given in Numpy/C order
        c                 6    g | ]}j         d |dz             S )rL   r   )r   )r   r   r]   s     rU   r   z+CompImageHDU.tile_shape.<locals>.<listcomp>V  s=        .S1W../  rV   r0   r   r!   )rd   r   r   r   s   `rU   r   zCompImageHDU.tile_shapeN  sU         h!7!!;RDD  
 
 	
rV   c                 B    | j                             dt                    S )z8
        The name of the compression algorithm.
        r4   )r   r   r.  r   s    rU   r   zCompImageHDU.compression_type\  s    
 |
,DEEErV   )NNNNNNNN)Nr  r   r   )FFr   rN   )+r   r   r   r   _manages_own_heap_load_variable_length_datar   r   r.  r8  DEFAULT_HCOMP_SMOOTHr7  r<  r?  r^   r   propertyr   setterr   r   r   rz  r   r   r|  deleterr  r   r  r  r  r  r  r  r  rq  r~  r>  r}  r   r   r   r   s   @rU   r   r     sW          "'
 'M  F	   1')-/' %Y) Y) Y) Y) Y) Y)v& & &. C C XC 
[
? 
? [
? # # [#( U& U& U& U&n  0   \, 
[  [ $ $ $ $ \$$ 1 1 1 + + X+ E" E" \E"NT T T<02 02 02dh) h) h) h)T&G &G &G &G &G &GP8 8 8    	% 	% 	% 	% 	% 	%' ' ',1 1 1 10( ( (T & & X&* 
 
 X
 F F XF F F F FrV   r   c                   `    e Zd ZdZd Zed             Zed             Zed             Zd Z	dS )r  a  
    Class enabling subsets of CompImageHDU data to be loaded lazily via slicing.

    Slices of this object load the corresponding section of an image array from
    the underlying FITS file, and applies any BSCALE/BZERO factors.

    Section slices cannot be assigned to, and modifications to a section are
    not saved back to the underlying file.

    See the :ref:`astropy:data-sections` section of the Astropy documentation
    for more details.
    c                 .   || _         t          | j         j                  | _        t          | j         j                  | _        t	          | j                  | _        t          j        t          | j        | j                  t                    | _        d S )Nrj  )
hdur   r   r	   r   _n_dimrr  rs  r   rb   )r]   r  s     rU   r^   zCompImageSection.__init__r  sv    &tx'788&tx'788$*++T%t'788
 
 
rV   c                 *    t          | j                  S rN   )rd   r   r   s    rU   r  zCompImageSection.shape{  s    T%&&&rV   c                 &    | j         j        d         S )Nr0   )r  r   r   s    rU   ndimzCompImageSection.ndim  s    x))rV   c                 <    t           | j        j        d                  S )Nr1   )r   r  r   r   s    rU   r1  zCompImageSection.dtype  s    DH,Y788rV   c           
      B   |t           u rZt          j        | j        t                    }| j        dz
  }t          | j        ||          }| j                            |          S t          || j
                  }t          j        | j        t                    }t          j        | j        t                    }g }t          |          D ]\  }}t          |t                    r+|j        dk    r4|j        | j        |         z  ||<   |j        dz
  | j        |         z  ||<   nL|j        dnt%          |j        dz
  d          }|| j        |         z  ||<   |j        | j        |         z  ||<   t          j        ||          }|j        dk     r|j        |                    |           |                    t          |j        | j        |         ||         z  z
  |j        | j        |         ||         z  z
  |j                             G|| j        |         z  ||<   ||         ||<   |                    || j        |         ||         z  z
             t          | j        ||          }| j                            |t+          |                             S )Nrj  r   )r  r   )Ellipsisrr  zerosr  rb   r   r   r  rz  r   r   r5  ra   rn   stepstartr	   stopmaxr  rz   rd   )	r]   rk   first_tile_indexlast_tile_indexr   final_array_indexrX  r   r  s	            rU   __getitem__zCompImageSection.__getitem__  s    H!x3???"ma/O)$(4DoVVD8''---$U$2BCCC 8DKs;;;(4;c:::!%(( 	 	HC#u%% 8a<<,/I9I#9N,N$S),/HqLT=Mc=R+ROC(( # 011c#(Q,6J6JD,0D4DS4I,I$S)+.98H8M+MOC(
 #%*_>N"O"O8a<<CH$4%,,S1111%,,I(8(=@PQT@U(UUHt'7'<?OPS?T'TTH     ),t/?/D(D %'7'<$!(($*3/2B32GGG    &dh0@/RRx##D/@)A)A$BCCCrV   N)
r   r   r   r   r^   r  r  r  r1  r
  r   rV   rU   r  r  d  s         
 
 
 ' ' X' * * X* 9 9 X94D 4D 4D 4D 4DrV   r  )Kr  r3  r  r   r  r   
contextlibr   numpyrr  astropy.io.fitsr   "astropy.io.fits._tiled_compressionr   r   (astropy.io.fits._tiled_compression.utilsr   r   r	   astropy.io.fits.cardr
   astropy.io.fits.columnr   r   r   r   r   astropy.io.fits.fitsrecr   astropy.io.fits.headerr   astropy.io.fits.utilr   r   r   r   astropy.utilsr   astropy.utils.decoratorsr   astropy.utils.exceptionsr   r   astropy.utils.shapesr   baser   r   r   r   imager   tabler    r   r#   r$   r%   r;  r  r  r*  r.  r7  r<  r?  r8  r  r9  r:  r   COMPRESSION_KEYWORDSr8   r   r  r   rV   rU   <module>r     s,         				                         S S S S S S S S W W W W W W W W W W % % % % % % G G G G G G ; ; ; ; ; ; ; ; ; ; , , , , , , ) ) ) ) ) )            ' & & & & & @ @ @ @ @ @ R R R R R R R R 5 5 5 5 5 5 C C C C C C C C C C C C               	  {00 
     $  # '     h'	 	 	 E E E E Ef E E ET
@F @F @F @F @F; @F @F @FF6WD WD WD WD WD WD WD WD WD WDrV   