
    HR-e                        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	m
Z
mZ d dlmZ d dlmZmZ ddlmZmZmZmZmZ g dZ G d	 d
e          Z G d d          Z G d de          Z G d dee          Z G d d          ZdS )    N)Header)_is_dask_array_is_int_is_pseudo_integer_pseudo_zero)VerifyWarning)
isiterablelazyproperty   )BITPIX2DTYPEDELAYEDDTYPE2BITPIXExtensionHDU	_ValidHDU)Section
PrimaryHDUImageHDUc                   t    e Zd ZdZdddddddd	Z	 	 	 	 	 	 d' fd	Zed             Zed             Z	ed             Z
ed             Zed             Zej        d             Zed             Zej        d             Zd Zd(dZd)dZ	 d*dZd+ fd	Zd Zd, fd	Zd  Zd! Zd" Zd# Zd$ Zd% Z fd&Z xZS )-_ImageBaseHDUz{FITS image HDU base class.

    Attributes
    ----------
    header
        image header

    data
        image data
    zconforms to FITS standardzImage extensionzarray data typeznumber of array dimensionsz
has groupsznumber of parametersznumber of groups)SIMPLEXTENSIONBITPIXNAXISGROUPSPCOUNTGCOUNTNFTc                     ddl m} t                                          ||           |t          u r|t          d          n<t           t                    rdd j        d         f}	ndd j        d         f}	|	d	d
 j        d	         fdd j        d         fg}
t           |          r#|
	                    dd j        d         f           t           t          |f          rF|
	                    dd j        d         f           |
	                    dd j        d         f           |=|
                                }t          |
          }|                    |ddd           nt          |
          }| _        | _        | _        | _        d j        v }d j        v } j                            dd           _         j                            dd           _         fdt)           j                            dd                    D              _         j                            d	           _         j                            dd           _         j                            dd           _        |rd n j                            d           _                                           j         _         j                            d           _         j         _         j         _        d|v r|d         r|d          _        d|v r|d         r|d          _         d _!        |t          u r!|s j        dk    s j        dk    rd _"        d S | _#         j                            d	           _         j                            d           _         j                            d           _        |s j         _        |s j         _        d S d S )Nr   )	GroupsHDU)dataheaderzNo header to setup HDU.r   IMAGEr   Tr      r   r   r   r   r   )stripupdateendBZEROBSCALEc           	      l    g | ]0}j                             d t          |dz             z   d          1S )r   r   r   )_headergetstr).0axisselfs     9lib/python3.11/site-packages/astropy/io/fits/hdu/image.py
<listcomp>z*_ImageBaseHDU.__init__.<locals>.<listcomp>o   sJ     
 
 
 LWs4!8}}4a88
 
 
    BLANKnameverF)$groupsr   super__init__r   
ValueError
isinstancer   standard_keyword_commentsappendcopyr   extendr)   _do_not_scale_image_data_uint_scale_backr*   _bzero_bscalerange_axes_bitpix_gcount_pcount_blank_verify_blank_orig_bitpix_orig_blank_orig_bzero_orig_bscaler3   r4   	_modified_data_needs_rescaler   )r.   r   r    do_not_scale_image_datauint
scale_backignore_blankkwargsr   c0cardsorigbzero_in_headerbscale_in_header	__class__s   `             r/   r7   z_ImageBaseHDU.__init__.   s    	&%%%%%d62227?? ~ !:;;;  $-- P '4+I*+UVd&DX&NO1d<XFG!T;GDEE $	** Yhd.LX.VWXXX$y 9:: Vh4+I(+STUUUh4+I(+STUUU!{{}}d$tFFFF!DL(?%
%
 "T\1#t|3l&&w22|''!44
 
 
 
dl..w::;;
 
 

 |''11|''!44|''!44*Idd0@0@0I0I L<++G44  ; L
 VvvDIF??ve}?e}DH 7??* 00A0AT[TUEUEU ,0(F
 DI
  <++H55DL ,**733DK<++H55DL  	+#{D 	- $D	- 	-r1   c                     t           )z
        _ImageBaseHDU is sort of an abstract class for HDUs containing image
        data (as opposed to table data) and should never be used directly.
        )NotImplementedError)clsr    s     r/   match_headerz_ImageBaseHDU.match_header   s
     "!r1   c                     dS NT r.   s    r/   is_imagez_ImageBaseHDU.is_image   s    tr1   c                      t          |           S )a  
        Access a section of the image array without loading the entire array
        into memory.  The :class:`Section` 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.

        Sections are useful for retrieving a small subset of data from a remote
        file that has been opened with the ``use_fsspec=True`` parameter.
        For example, you can use this feature to download a small cutout from
        a large FITS image hosted in the Amazon S3 cloud (see the
        :ref:`astropy:fits-cloud-files` section of the Astropy
        documentation for more details.)

        For local files, sections are mostly obsoleted by memmap support, but
        should still be used to deal with very large scaled images.

        Note that sections cannot currently be written to.  Moreover, any
        in-memory updates to the image's ``.data`` property may not be
        reflected in the slices obtained via ``.section``. See the
        :ref:`astropy:data-sections` section of the documentation for
        more details.
        )r   rb   s    r/   sectionz_ImageBaseHDU.section   s    2 t}}r1   c                 D    t          t          | j                            S )zX
        Shape of the image array--should be equivalent to ``self.data.shape``.
        )tuplereversedrD   rb   s    r/   shapez_ImageBaseHDU.shape   s     Xdj))***r1   c                     | j         S N)r)   rb   s    r/   r    z_ImageBaseHDU.header   s
    |r1   c                 J    || _         d| _        |                                  d S r`   )r)   rN   update_header)r.   r    s     r/   r    z_ImageBaseHDU.header   s(    r1   c                     t          | j                  dk     rdS |                     | j        | j                  }|                     |j                   |S )a  
        Image/array data as a `~numpy.ndarray`.

        Please remember that the order of axes on an Numpy array are opposite
        of the order specified in the FITS file.  For example for a 2D image
        the "rows" or y-axis are the first dimension, and the "columns" or
        x-axis are the second dimension.

        If the data is scaled using the BZERO and BSCALE parameters, this
        attribute returns the data scaled to its physical values unless the
        file was opened with ``do_not_scale_image_data=True``.
        r   N)lenrD   _get_scaled_image_data_data_offsetri   _update_header_scale_infodtype)r.   r   s     r/   r   z_ImageBaseHDU.data   sQ     tz??QF**4+<djII&&tz222r1   c                 f   d| j         v rE| j         d         8| j         d         |u rd S d| _        t          | j         d         j                  }n	d| _        d}|~t	          |t
          j                  sFt          |          s7	 t          j        |          }n!# t          $ r t          d|d          w xY w|j        dk    rt          d|d          || j         d<   d| _        | j        g | _        nct          |j        j                 | _        d| _        d	| _        d | _        t+          |j                  | _        | j                                         |                                  ||r|                     |j                   | j        | _        | j        | _        | j        | _        |S )
Nr   TFzdata object z% could not be coerced into an ndarrayra   z# should have at least one dimensionr   r   )__dict___data_replacedr   rs   r9   npndarrayr   array	Exception	TypeErrorri   rN   r   rD   r   r3   rE   rB   rA   rH   listreverserm   rr   rJ   rM   rL   )r.   r   was_unsigneds      r/   r   z_ImageBaseHDU.data   s   T]""t}V'<'H}V$,,&*#-dmF.C.IJJLL"&D LdBJ// t8L8L 8D>>DD    #XtXXX  
 zRN4NNN   !%f9DJJ (
8DLDLDKDKdj))DJJ   
 	**4:666 !L L; s   B B7c                    | j         s*| j        j         s| j        r| j        | j        j        k    sdS | j                            dd          }d| j        vr| j        d         }n| j        j        d         }| j                            d| j	        |d           | j        rL| j        | j        j        k    r7t          | j        j                  | _        | j                                         d| j        v r| j        j        d         }n| j        d         }| j                            dt          | j                  |d           t          | j                  D ]f\  }}dt          |dz             z   }|| j        v r|| j        |<   .|dk    rd}ndt          |          z   }| j                            |||           gt!          t          | j                  dz   |dz             D ]+}	 | j        dt          |          z   = # t"          $ r Y (w xY wd| j        v r| j        d         | _        |                                  d| _         dS )	zD
        Update the header keywords to agree with the data.
        Nr   r   r   afterr   r2   F)rN   r)   	_has_datari   r   r*   r:   commentssetrE   r|   rD   r}   ro   	enumerater+   rC   KeyErrorrH   !_update_pseudo_int_scale_keywords)r.   	old_naxisbitpix_commentnaxis_commentidxr-   naxisnr   s           r/   rm   z_ImageBaseHDU.update_headerB  sq   
 N	|%	 	 $(:#@#@ FL$$Wa00	4<''!;HENN!\28<N 	4<qIII
 > 	!djDIO;;dio..DJJ    dl"" L1':MM :7CM#dj//=QQQ #4:.. 		< 		<ICs37||+F%%'+V$$!88#EE#c#hh.E  U ;;;; TZ1,i!m<< 	 	CL3s88!344    dl"",w/DK 	..000s   +H
HHc                    | j         s| j        dk    r| j        dk    rdS ||                                 }||j        dk    r| j        s| j        dS dD ]4}	 | j        |= | j                                         %# t          $ r Y 1w xY w||                                 }|t          |j
                 | j        d<   d| _        d| _        | j        d         | _        | j                            dd          | _        dS )z?
        Delete BSCALE/BZERO from header if necessary.
        r   r   Nu)r'   r&   r   r2   )r>   rL   rM   _dtype_for_bitpixkindr@   r)   r;   r   r   r3   rA   rB   rE   poprH   )r.   rs   keywords      r/   rr   z'_ImageBaseHDU._update_header_scale_info  s6   & ( 	!!d&71&<&<F=**,,E 
c!!! "%)%5%=
 F* 	 	GL) ##%%%%    =**,,E%1%*%=DL"|H-l&&w55s   !A::
BBoldc                 :    |                      ||||d           dS )ao  
        Scale image data by using ``BSCALE``/``BZERO``.

        Call to this method will scale `data` and update the keywords of
        ``BSCALE`` and ``BZERO`` in the HDU's 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: ``"old"`` uses the original ``BSCALE`` and
            ``BZERO`` values from when the data was read/created (defaulting to
            1 and 0 if they don't exist). For integer data only, ``"minmax"``
            uses the minimum and maximum of the data to scale. User-specified
            ``bscale``/``bzero`` values always take precedence.

        bscale, bzero : int, optional
            User-specified ``BSCALE`` and ``BZERO`` values
        N)typeoptionbscalebzeroblank)_scale_internal)r.   r   r   r   r   s        r/   scalez_ImageBaseHDU.scale  s6    6 	fV5 	 	
 	
 	
 	
 	
r1   r   c                    | j         dS |t          | j                 }t          t          |          }|||}|}n[||}d}nS|d}|}nK|dk    r| j        | j        | j        }| j        }n'|dk    rt          |t          j                  st          | j                   rW| j         
                                                                }	| j                                                                         }
nRt          j                            | j         j                  }	t          j                            | j         j                  }
|t          j        k    r|	}|
|	z
  dz  }n-|
|	z   dz  }d |            j        z  }|
|	z
  d|z  d	z
  z  }nd}d}|dk    rRt          | j                   r| j         |z
  | _         n#t	          j        | j         | | j         d
           || j        d<   n	 | j        d= n# t*          $ r Y nw xY w|r |dk    r| j         |z  | _         || j        d<   n	 | j        d= n# t*          $ r Y nw xY w|Et          |t          j                  r+|| j         t	          j        | j                   <   || j        d<   | j         j        j        |k    r2t	          j        t	          j        | j                   |          | _         t8          | j         j        j                 | _        | j                            dd          | _        | j                            dd          | _         || _!        | j        | j        d<   | j        | _"        | j        | _        | j         | _        | j!        | _#        dS )a  
        This is an internal implementation of the `scale` method, which
        also supports handling BLANK properly.

        TODO: This is only needed for fixing #3865 without introducing any
        public API changes.  We should support BLANK better when rescaling
        data, and when that is added the need for this internal interface
        should go away.

        Note: the default of ``blank=0`` merely reflects the current behavior,
        and is not necessarily a deliberate choice (better would be to disallow
        conversion of floats to ints without specifying a BLANK if there are
        NaN/inf values).
        Nr   r   r   minmaxg     o@g       @r"      unsafe)outcastingr&   r'   r2   rs   r   )$r   r   rE   getattrrw   rM   rL   
issubclassfloatingr   mincomputemaxminimumreduceflatmaximumuint8itemsizeaddr)   r   integerisnanrs   r   ry   aroundr   r3   r*   rA   rB   rH   rJ   rK   )r.   r   r   r   r   r   _type_scale_zeror   r   nbytess               r/   r   z_ImageBaseHDU._scale_internal  s   " 9F <-DD!! %"3FEEFEEFEEeOO!- ,&F$EEx
5"+(F(Fdi(( 8immoo--//immoo--//j''	77j''	77  )
3sc) UUWW--)Va8FE A::di(( K I-		 ty5&diJJJJ$)DL!!L))     	fkk	F*DI%+DL""L**    E2:!>!> .3DIbhty))*$)DL!9?5((49!5!5UCCCDI $DIO$89l&&w22|''!44!%X
 !L; L;s$   1G: :
HH-H6 6
IIwarnc                     |                                   |                                  t                                          |          S rk   )rm   rI   r6   _verify)r.   r   rZ   s     r/   r   z_ImageBaseHDU._verifyQ  s?     	wwv&&&r1   c                 8   | j         d S g }t          | j                   s4|                    d                    | j                              d | _         | j        dk    s|                    d           d | _         |D ]}t          j        |t                     d S )Nz~Invalid value for 'BLANK' keyword in header: {!r} The 'BLANK' keyword must be an integer.  It will be ignored in the meantime.r   z|Invalid 'BLANK' keyword in header.  The 'BLANK' keyword is only applicable to integer data, and will be ignored in this HDU.)rH   r   r;   formatrE   warningsr   r   )r.   messagesmsgs      r/   rI   z_ImageBaseHDU._verify_blankY  s     ;F t{## 	OO++16$++>+>  
 DK|aOO  
 DK 	. 	.CM#}----	. 	.r1   c                     | j         r,|                     t          | j                 | j                   |                                  |s| j        r| j        }t                      	                    ||          S )N)r   )
r@   r   r   rJ   rK   rm   rO   r   r6   _prewriteto)r.   checksuminplace_rZ   s       r/   r   z_ImageBaseHDU._prewritetou  s     	  T./t7G !    	 	43 	 	Aww""8W555r1   c                 
   d}| j         |S t          | j                   r|                     |          S t          j        dk    rd}nd}t          | j         j                  rJt          j        | j         t          | j         j                  z
  d| j         j        j
                   }d}n| j         }|j        j        d         }||v }|r|j        j        r[|                    d           	 |                    |           |                    d           nX# |                    d           w xY w|                    |                    d                     n|                    |           ||j        |j
        z  z  }|S )	Nr   little<=r   z>ir   FT)r   r   _writeinternal_dasksys	byteorderr   rs   rw   ry   r   r   r+   flags	writeablebyteswap
writearraysize)r.   fileobjr   
swap_typesoutputshould_swapr   s          r/   _writedata_internalz!_ImageBaseHDU._writedata_internal  s   9KDI&& &	++G444 }(('

#
!$)/22 
6ITY_ = ==9ty799   $"L,Q/	':5 +<) 	?OOD))).**6222-------- &&vu'='=>>>>""6***FK&/11DKs   .D D0c                    t           j        dk    rd}nd}t          | j        j                  rt          d          | j        }|j        j        d         }||v }|r:ddlm} |	                    |j
        d          	                    |j        d          }|                                }|j        }|                    ||z   d	z
             |                    d
           |                                 |j        dvrt%          |j        d          }	d}
n	|j        }	d}
	 t+          j        |	                                ||z   t*          j                  }t1          j        |j        |j        ||          }|                    |dd           |
r|	                                 |                                 n/# |
r|	                                 |                                 w xY w|                    ||z              |S )Nr   r   r   z/This dtype isn't currently supported with dask.r   )MFSr       )rb+zwb+zab+r   )modeT)lengthaccess)ri   rs   offsetbuffer)lockr   )r   r   r   r   rs   r\   r+   
dask.utilsr   
map_blocksr   newbyteordertellr   seekwriteflushfileobj_modeopenr3   _filemmapfilenoACCESS_WRITErw   rx   ri   storeclose)r.   r   r   r   r   r   r   initial_positionn_bytesfpshould_closeoutmmapoutarrs                r/   r   z!_ImageBaseHDU._writeinternal_dask  s   =H$$#JJJdio.. 	2%&WXXXYF(+I#z1K 	$$$$$$
 &&qz599DD F #<<>>- 	%/!3444e'<<< gl///BLLB L	i		$4w$>tGX  G Zll'	  F LLdDL999 


MMOOOO  


MMOOOO
 	%/000s   "A0F= =,G)c                    | j         }| j        r| j        dk    r|dk    r| j        dk    rt	          j        d          S d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"   iint8   uint16    uint32@   uint64float64r   float32N)rJ   r?   rM   rL   rw   rs   )r.   bitpixbitsrs   s       r/   r   z_ImageBaseHDU._dtype_for_bitpix  s     ": 
	!$+q00{{t/477x''' RXh''(RXh''(RXh''(  ! !e
 T>>d&6!q/&I&I LLLB;;8I&&&aZZ8I&&& Zr1   c                     |                                  }|J|j        dk    rA|j        dz  }t          j        ||          }|t          j        d|dz
  z            z  }|S dS dS )aW  
        Handle "pseudo-unsigned" integers, if the user requested it.  Returns
        the converted data array if so; otherwise returns None.

        In this case case, we don't need to handle BLANK to convert it to NAN,
        since we can't do NaNs with integers, anyway, i.e. the user is
        responsible for managing blanks.
        Nr   r"   r   r   )r   r   r   rw   ry   r   )r.   r   rs   r  s       r/   _convert_pseudo_integerz%_ImageBaseHDU._convert_pseudo_integer
  sz     &&(( s!2!2
 >A%D8D...DBIaD1Ho...DK !2!2r1   c                    t           | j                 }|                     |||          }|j                            d          |_        | j        s| j        dk    r| j        dk    r	| j        |S 	 | j	        j
        rt          d          n# t          $ r Y nw xY wd}| j        dk    r| j        dk    s|                     |          }|/d}| j        W| j        dk    rL|j        | j        k    }|                                t#          |          dz  k     rt%          j        |          }|                                 }|t%          j        ||          }nK| j	        !| j	        j        r|                                }n#|j        j        s|                                }n|}~| j        dk    rt%          j        || j        |           | j        dk    r
|| j        z  }| j        rt$          j        |j        |<   |S )z
        Internal function for reading image data from a file and apply scale
        factors to it.  Normally this is used for the entire image, but it
        supports alternate offset/shape for Section support.
        >r   r   Nz`Cannot load a memory-mapped image: BZERO/BSCALE/BLANK header keywords present. Set memmap=False.r"   r   )r   rJ   _get_raw_datars   r   r>   rL   rM   rH   r   strict_memmapr8   AttributeErrorr  rE   r   sumro   rw   wherer   ry   memmapr<   r   r   multiplynan)r.   r   ri   coderaw_datar   blanks	new_dtypes           r/   rp   z$_ImageBaseHDU._get_scaled_image_data!  s%    D-.%%eT6::!44S99( 	!!d&71&<&<AT O	z'  (    	 	 	D	  A%%$*;q*@*@//99D< F{&4<!+;+;!$+5 ::<<#f++/11Xf--F..00I$x	::::)dj.?)#==??DD!1 $#==??DD $D A%%D$"3T:::1$$(({ +$&F	&!s   0B 
BBc                    | j         j        }| j        r<| j        d}n| j        j        j        }||                    d          dz   d         }ns| j        r't          | j                  rt          | j
                 }nd}|rA| j        s:| j        dk    s| j        dk    r$|                                 }||d|j         dz  }t          t!          | j                            }| j        | j        |t%          | j                  ||dfS )zC
        Summarize the HDU: name, dimensions, and formats.
        N .r   r   z (rescales to ))rZ   __name___data_loadedr   rs   r3   rfindri   allr   rE   r>   rM   rL   r   rg   rh   r4   ro   r)   )r.   
class_namer   r  ri   s        r/   _summaryz_ImageBaseHDU._summaryk  s(    ^,
  	Ay -S 1 1A 5 7 78z c$*oo  &dl3 A5A &!++t/?1/D/D 2244	(@y~@@@@F htz**++	48ZT\1B1BE6SUVVr1   c                 p   | j         r| j        }t          | j        j                  rGt	          j        | j        t          | j        j                  z
  d| j        j        j                   }|j        j        d         dk    rz|j	        j
        r7d}|                    d          }|j                            d          |_        n9|                    d          }|j                            d          |_        d}nd}|                     |                                                    t          j                            }|rMt          | j        j                  s4|                    d           |j                            d          |_        |S t#                                                      S )zJ
        Calculate the value for the ``DATASUM`` card in the HDU.
        ir   r   r  TFr   )r   r   r   rs   rw   ry   r   r   r+   r   r   r   r   _compute_checksumflattenviewr   r6   _calculate_datasum)r.   dbyteswappedcsrZ   s       r/   r"  z _ImageBaseHDU._calculate_datasum  s    > *	0	A "$)/22 HITY_ = ==8dio688   w{1~$$7$ 	("&K

4((Ag22377AGG 

5))Ag22377AG"'KK#''		(8(8(B(BCCB  4#5dio#F#F 4

4   '..s33I 77--///r1   )NNFTFFrk   )Nr   NN)Nr   NNr   r   )FF)r  
__module____qualname____doc__r:   r7   classmethodr^   propertyrc   re   ri   r    setterr
   r   rm   rr   r   r   r   rI   r   r   r   r   r  rp   r  r"  __classcell__rZ   s   @r/   r   r      s       	 	 .%#-($! !  %@- @- @- @- @- @-D " " ["   X   X4 + + X+   X ]  ]
   \* 
[@ @ [@DB B BH76 76 76 76r
 
 
 
@ GHq' q' q' q'f' ' ' ' ' '. . .86 6 6 6 6 6+ + +Z? ? ?B' ' '2  .H H HT!W !W !WF.0 .0 .0 .0 .0 .0 .0 .0 .0r1   r   c                   :    e Zd ZdZd Zed             Zd Zd ZdS )r   a  
    Class enabling subsets of ImageHDU 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                     || _         d S rk   )hdu)r.   r1  s     r/   r7   zSection.__init__  s    r1   c                     | j         j        S rk   )r1  ri   rb   s    r/   ri   zSection.shape  s     x~r1   c                    t          |t                    s|f}t          | j        j                  }t          d |D                       ot          |          |k    }t          d |D                       s|t          fz  }t          d |D                       }t          |          |z
  |k    s|dk    rt          d          t          d t          |t          fz             D                       }|d|         t          d          f|t          |          z
  dz   z  z   ||dz   d         z   }t          d |D                       ot          |          |k    }g }d	}t          |          D ]h}| j        j        |         }	t          ||         |	          }
||	z  |
j        z   }t          ||                   s|                    |
j                    ni|
j        }t          |dz   |          D ]^}| j        j        |         }	t          ||         |	          }
|                    |
j                   |
j        |	k    r|
j        r||	z  }\d
}_|r[t          |          pd}| j        j        }| j        j        |t+          |          z  dz  z   }| j                            ||          }n|                     |          }|r|                                }n|r|                                }|S )a@  Returns a slice of HDU data specified by `key`.

        If the image HDU is backed by a file handle, this method will only read
        the chunks of the file needed to extract `key`, which is useful in
        situations where the file is located on a slow or remote file system
        (e.g., cloud storage).
        c              3   X   K   | ]%}t          |t          t          j        f          V  &d S rk   r9   intrw   r   r,   ks     r/   	<genexpr>z&Section.__getitem__.<locals>.<genexpr>  3      >>Q
1sBJ/00>>>>>>r1   c              3   (   K   | ]}|t           u V  d S rk   Ellipsisr7  s     r/   r9  z&Section.__getitem__.<locals>.<genexpr>  s&      ..Q1=......r1   c                 $    g | ]}|t           u |S ra   r<  r7  s     r/   r0   z'Section.__getitem__.<locals>.<listcomp>  s    >>>AXar1   r   ztoo many indices for arrayc              3   2   K   | ]\  }}|t           u |V  d S rk   r<  )r,   r  r8  s      r/   r9  z&Section.__getitem__.<locals>.<genexpr>  s*      OOAh1OOr1   Nc              3   X   K   | ]%}t          |t          t          j        f          V  &d S rk   r5  r7  s     r/   r9  z&Section.__getitem__.<locals>.<genexpr>  r:  r1   r   F)r   r"   )r9   rg   ro   r1  ri   r  anyr=  
IndexErrornextr   slicerC   
_IndexInfor   r   r;   npts
contiguousrJ   rq   absrp   _getdataitemsqueeze)r.   keynaxisreturn_scalarellipsis_countr   return_0dimdimsr   r-   indxis_contiguousjdxr  r   s                  r/   __getitem__zSection.__getitem__  s    #u%% 	&CDHN##>>#>>>>>T3s88uCT 	 ..#..... 	 H;C>>>>>??s88n$u,,0B0B9:::OO3(+<!=!=OOOOO$3$i5;;.ECHH,<q,@AACa		NR>>#>>>>>T3s88uCT 	 << 	 	C8>#&Dc#h--Dd]T[0F3s8$$ DI&&& q%(( 	& 	&C8>#&Dc#h--DKK	"""yD  T_ $ % 	&;;&$DX*FX*Vc&kk-AQ-FFF 82264@@DD==%%D 	"99;;DD 	"<<>>Dr1   c                     t          t           j        j                            D ]m\  \  }}t	          |t
                    rt          |                    |           } n3t          |          r#t          j
        |t                    |         } nn fd|D             }t          d dz   d          D                       rt          j        |          S t          j        d |D                       S )Nr   c                 T    g | ]$}d          |fz   dz   d          z            %S )Nr   ra   )r,   r8  r   keysr.   s     r/   r0   z$Section._getdata.<locals>.<listcomp>#  s>    FFFaT$3$Z1$&cAgii89FFFr1   c              3   ^   K   | ](}t          |t                    pt          |          V  )d S rk   )r9   rD  r	   )r,   rL  s     r/   r9  z#Section._getdata.<locals>.<genexpr>%  s7      TTSz#u%%8CTTTTTTr1   r   c                 6    g | ]}t          j        |          S ra   )rw   
atleast_1d)r,   ry   s     r/   r0   z$Section._getdata.<locals>.<listcomp>*  s"    "J"J"JE2=#7#7"J"J"Jr1   )r   zipr1  ri   r9   rD  rC   indicesr	   rw   aranger6  rA  ry   concatenate)r.   rX  rL  r-   ksr   r   s   ``    @r/   rI  zSection._getdata  s    )#dDHN*C*C D D 	 	C#t#u%% CKK--.C Yt3///4 GFFFFF2FFFTTDqOTTTTT 	L8D>>! >"J"JT"J"J"JKKKr1   N)	r  r'  r(  r)  r7   r+  ri   rU  rI  ra   r1   r/   r   r     so              X
@ @ @DL L L L Lr1   r   c                   `     e Zd ZdZdZ	 	 	 	 	 	 d fd	Zed             Z fdZd fd
	Z	 xZ
S )r   z!
    FITS primary HDU class.
    PRIMARYNFTc                     t                                          ||||||           |D| j        d         }|dk    rd}| j                            dddt	          |          z              dS dS )	aA  
        Construct a primary HDU.

        Parameters
        ----------
        data : array or ``astropy.io.fits.hdu.base.DELAYED``, optional
            The data in the HDU.

        header : `~astropy.io.fits.Header`, optional
            The header to be used (as a template).  If ``header`` is `None`, a
            minimal header will be provided.

        do_not_scale_image_data : bool, optional
            If `True`, image data is not scaled using BSCALE/BZERO values
            when read. (default: False)

        ignore_blank : bool, optional
            If `True`, the BLANK header keyword will be ignored if present.
            Otherwise, pixels equal to this value will be replaced with
            NaNs. (default: False)

        uint : bool, optional
            Interpret signed integer data where ``BZERO`` is the
            central value and ``BSCALE == 1`` as unsigned integer
            data.  For example, ``int16`` data with ``BZERO = 32768``
            and ``BSCALE = 1`` would be treated as ``uint16`` data.
            (default: True)

        scale_back : bool, optional
            If `True`, when saving changes to a file that contained scaled
            image data, restore the data to the original type and reapply the
            original BSCALE/BZERO values.  This could lead to loss of accuracy
            if scaling back to integer values after performing floating point
            operations on the data.  Pseudo-unsigned integers are automatically
            rescaled unless scale_back is explicitly set to `False`.
            (default: None)
        )r   r    rP   rQ   rS   rR   Nr   r   r  EXTENDTr   )r6   r7   r)   r   r+   )	r.   r   r    rP   rS   rQ   rR   dimrZ   s	           r/   r7   zPrimaryHDU.__init__4  s    \ 	$;%! 	 	
 	
 	
 >,w'CaxxLXt7SXX3EFFFFF	 >r1   c                 \    |j         d         }|j        dk    od|vp	|d         duo|j        S )Nr   r   r   T)rV   r   value)r]   r    cards      r/   r^   zPrimaryHDU.match_headerr  sD    |A LH$ 'G6(+;4+G
	
r1   c                    t                                                       d| j        v rYt          | j                  r%dt          t          | j                            z   }nd}| j                            d|           d S d S )Nrd  r   r   )r6   rm   r)   ro   rD   r+   r   )r.   r   rZ   s     r/   rm   zPrimaryHDU.update_header}  s     t|##4:  #c$*oo"6"66LXU33333 $#r1   r   c                     t                                          |          }d| j        v r9| j                            dd          }|                     d|dz   d d||           |S )Nr   rd  r   r      c                 ,    t          | t                    S rk   )r9   boolvs    r/   <lambda>z$PrimaryHDU._verify.<locals>.<lambda>  s    z!T/B/B r1   Tr6   r   r)   r*   	req_cardsr.   r   errsrM  rZ   s       r/   r   zPrimaryHDU._verify  ss    wwf-- t|##L$$Wa00ENN%!)%B%BD&RV   r1   )NNFFTNr&  )r  r'  r(  r)  _default_namer7   r*  r^   rm   r   r-  r.  s   @r/   r   r   -  s          M  %<G <G <G <G <G <G| 
 
 [
	4 	4 	4 	4 	4         r1   r   c                   X     e Zd ZdZdZ	 	 	 	 	 	 	 d
 fd	Zed             Zd fd		Z xZ	S )r   z)
    FITS image extension HDU class.
    r!   NFTc           	      X    t                                          |||||||           dS )a  
        Construct an image HDU.

        Parameters
        ----------
        data : array
            The data in the HDU.

        header : `~astropy.io.fits.Header`
            The header to be used (as a template).  If ``header`` is
            `None`, a minimal header will be provided.

        name : str, optional
            The name of the HDU, will be the value of the keyword
            ``EXTNAME``.

        do_not_scale_image_data : bool, optional
            If `True`, image data is not scaled using BSCALE/BZERO values
            when read. (default: False)

        uint : bool, optional
            Interpret signed integer data where ``BZERO`` is the
            central value and ``BSCALE == 1`` as unsigned integer
            data.  For example, ``int16`` data with ``BZERO = 32768``
            and ``BSCALE = 1`` would be treated as ``uint16`` data.
            (default: True)

        scale_back : bool, optional
            If `True`, when saving changes to a file that contained scaled
            image data, restore the data to the original type and reapply the
            original BSCALE/BZERO values.  This could lead to loss of accuracy
            if scaling back to integer values after performing floating point
            operations on the data.  Pseudo-unsigned integers are automatically
            rescaled unless scale_back is explicitly set to `False`.
            (default: None)

        ver : int > 0 or None, optional
            The ver of the HDU, will be the value of the keyword ``EXTVER``.
            If not given or None, it defaults to the value of the ``EXTVER``
            card of the ``header`` or 1.
            (default: None)
        )r   r    r3   rP   rQ   rR   r4   N)r6   r7   )	r.   r   r    r3   rP   rQ   rR   r4   rZ   s	           r/   r7   zImageHDU.__init__  sF    n 	$;! 	 	
 	
 	
 	
 	
r1   c                     |j         d         }|j        }t          |t                    r|                                }|j        dk    o
|| j        k    S )Nr   r   )rV   rg  r9   r+   rstripr   
_extension)r]   r    rh  xtensions       r/   r^   zImageHDU.match_header  sN    |A:h$$ 	)((H|z)Hh#..HHr1   r   c                     t                                          |          }| j                            dd          }|                     d|dz   d d||           |S )z)
        ImageHDU verify method.
        rk  r   r   r   rl  c                 ,    t          |           o| dk    S )Nr   )r   ro  s    r/   rq  z"ImageHDU._verify.<locals>.<lambda>  s    GAJJ,A16 r1   rr  rt  s       r/   r   zImageHDU._verify  sg     wwf--  !,, 	eai!B!BAvt	
 	
 	
 r1   )NNNFTNNr&  )
r  r'  r(  r)  r{  r7   r*  r^   r   r-  r.  s   @r/   r   r     s          J  %?
 ?
 ?
 ?
 ?
 ?
B I I [I         r1   r   c                       e Zd Zd ZdS )rE  c                    t          |          rE|dk     r||z   }d|cxk    r|k     rn nd| _        || _        d| _        d S t	          d| d          t          |t                    r:|                    |          \  }}}||z
  |z  | _        || _        |dk    | _        d S t          |          r$t          |          | _        d| _        d| _        d S t	          d|           )Nr   r   TzIndex z out of range.FzIllegal index )
r   rF  r   rG  rB  r9   rD  r]  r	   ro   )r.   rR  rM  startstopsteps         r/   r7   z_IndexInfo.__init__  s   4== 	6axxe|D    5     	""& !>$!>!>!>???e$$ 
	6 $U 3 3E4$.DIDK"aiDOOO 	6D		DIDK#DOOO4d44555r1   N)r  r'  r(  r7   ra   r1   r/   rE  rE    s#        6 6 6 6 6r1   rE  )r   r   r   numpyrw   astropy.io.fits.headerr   astropy.io.fits.utilr   r   r   r   astropy.io.fits.verifyr   astropy.utilsr	   r
   baser   r   r   r   r   __all__r   r   r   r   rE  ra   r1   r/   <module>r     s    



      ) ) ) ) ) )            1 0 0 0 0 0 2 2 2 2 2 2 2 2 N N N N N N N N N N N N N N
/
/
/d0 d0 d0 d0 d0I d0 d0 d0NkL kL kL kL kL kL kL kL\g g g g g g g gT\ \ \ \ \}l \ \ \~6 6 6 6 6 6 6 6 6 6r1   