
    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 d dlZ	d dlm
Z d dlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZm Z   G d	 d
          Z! G d de	j"                  Z#d Z$ G d de%          Z&ddZ'd Z(dS )    N)suppress)reduce)char)lazyproperty   )_VLFASCII2NUMPY	ASCII2STR
ASCIITNULL
FITS2NUMPYColDefsDelayed_AsciiColDefs_FormatP_FormatX
_get_index_makep_unwrapx_wrapx)_rstrip_inplacedecode_asciiencode_asciic                   \    e Zd ZdZ	 ddZd Zd Zd Zd Zd	 Z	d
 Z
ed             Zd ZdS )FITS_recorda  
    FITS record class.

    `FITS_record` is used to access records of the `FITS_rec` object.
    This will allow us to deal with scaled columns.  It also handles
    conversion/scaling of columns in ASCII tables.  The `FITS_record`
    class expects a `FITS_rec` object as input.
    r   Nc                     || _         || _        |rt          |          }n| j         j        }t	          |||                              |          }	|	\  | _        | _        | _        || _	        dS )a  
        Parameters
        ----------
        input : array
            The array to wrap.
        row : int, optional
            The starting logical row of the array.
        start : int, optional
            The starting column in the row associated with this object.
            Used for subsetting the columns of the `FITS_rec` object.
        end : int, optional
            The ending column in the row associated with this object.
            Used for subsetting the columns of the `FITS_rec` object.
        N)
arrayrowlen_nfieldssliceindicesstartendstepbase)
selfinputr   r"   r#   r$   r%   kwargswidthss
             7lib/python3.11/site-packages/astropy/io/fits/fitsrec.py__init__zFITS_record.__init__,   sm    " 
 	(IIEEJ'E%d##++E22*+'
DHdi			    c                    t          |t                    rGt          | j        j        |          }|| j        k     s|| j        dz
  k    rt          d| d          nt          |t                    r6 t          |           | j        | j
        |j        |j        |j        |           S |                     |          }|| j        j        dz
  k    rt          d          | j                            |          | j
                 S Nr   zKey 'z' does not exist.zIndex out of bounds)
isinstancestrr   r   namesr"   r#   KeyErrorr    typer   stopr$   r   
IndexErrorfield)r&   keyindxs      r+   __getitem__zFITS_record.__getitem__H   s    c3 	8dj.44Ddj  D48a<$7$7=s===>>> %8U## 	84::dj$(CIsxSWXXX??3''Ddj)A--- !6777z%%dh//r-   c                 n   t          |t                    rGt          | j        j        |          }|| j        k     s|| j        dz
  k    rt          d| d          nt          |t                    rjt          t          j        t          j
        t          j                  D ]9}|                     |          }|| j                            |          | j        <   :n7|                     |          }|| j        j        dz
  k    rt!          d          || j                            |          | j        <   d S r/   )r0   r1   r   r   r2   r"   r#   r3   r    ranger5   r$   	_get_indxr7   r   r   r6   )r&   r8   valuer9   s       r+   __setitem__zFITS_record.__setitem__X   s%   c3 	8dj.44Ddj  D48a<$7$7=s===>>> %8U## 	8ek5:uzBB 9 9~~d++38
  &&tx009 ??3''Ddj)A--- !6777+0
tx(((r-   c                 \    t          t          | j        | j        | j                            S N)r   r<   r"   r#   r$   r&   s    r+   __len__zFITS_record.__len__i   s"    5TXty99:::r-   c                     g }t          t          |                     D ]*}|                    t          | |                              +dd                    |           dS )z'
        Display a single row.
        (z, ))r<   r   appendreprjoin)r&   outlistidxs      r+   __repr__zFITS_record.__repr__l   sb     T## 	, 	,CNN4S	??++++(499W%%((((r-   c                 ,    |                      |          S )z3
        Get the field data of the record.
        )r:   )r&   r7   s     r+   r7   zFITS_record.fieldu   s     &&&r-   c                 2    |                      ||           dS )z3
        Set the field data of the record.
        N)r?   )r&   r7   r>   s      r+   setfieldzFITS_record.setfield{   s      	&&&&&r-   c                 ~    t          j        |           g}| j        }|r|                    |           |j        }||S rA   )weakrefproxyr%   rG   )r&   basesr%   s      r+   _baseszFITS_record._bases   sM    t$$%y 	LL9D  	 r-   c                    t           j        d | j        j                 }t	          | j                  D ]Q}|j        dk     rt          |j        d |j                  }n t          |j        |j	        |j                  }||         }R||         S )Nr   )
npogridr   r   reversedrT   r$   r    r"   r#   )r&   r9   r!   r%   r*   s        r+   r   zFITS_record._get_index   s    (0TZ001T[)) 	! 	!Dy1}}$*dDI66$*dh	::ajGGt}r-   )r   NNNN)__name__
__module____qualname____doc__r,   r:   r?   rC   rL   r7   rO   r   rT   r    r-   r+   r   r   "   s          CG   80 0 0 1 1 1"; ; ;) ) )' ' '' ' '   \    r-   r   c                       e Zd ZdZeZdZdZd Z fdZ	 fdZ
d Zd Zed)d
            Zd Z fdZ fdZ fdZd Zd* fd	Zed             Zed             Zej        d             Zej        d             Zd Zed             Zed             Zed             Zd Zd Zd Z d Z!d Z"d Z#d  Z$d! Z%d" Z&d# Z'd$ Z(d+d%Z)d& Z* fd'Z+d( Z, xZ-S ),FITS_recz
    FITS record array class.

    `FITS_rec` is the data part of a table HDU's data part.  This is a layer
    over the `~numpy.recarray`, so we can deal with scaled columns.

    It inherits all of the standard methods from `numpy.ndarray`.
    FTc                 p   |j         j        3t          j                            | |j        |j         |j                  }n8t          j                            | |j        |j         |j        |j                  }|                                 |j         j	        rt          |j         j	                  |_        |S )z@
        Construct a FITS record array from a recarray.
        N)buf)ra   strides)dtypesubdtyperV   recarray__new__shapedatarb   _initfieldsr   r   )subtyper'   r&   s      r+   rf   zFITS_rec.__new__   s    
 ;';&&ekuz '  DD ;&&ekuz5= '  D 	

: 	3
 122DMr-   c                     |d         }|d         }|d d         }t                                          |           t          j                    | _        t          ||          D ]\  }}t          | ||           d S )N)super__setstate__rQ   WeakSet_col_weakrefszipsetattr)r&   statemetacolumn_stateattrr>   	__class__s         r+   rp   zFITS_rec.__setstate__   s    RyRycrc
U###$_..t\22 	' 	'KD%D$&&&&	' 	'r-   c                    t                                                      \  }}}g }g }dD ]}t          t                    5  |dk    r.|                    | j                            d                     n#|                    t          | |                     |                    |           ddd           n# 1 swxY w Y   |||fz   }|||fS )z
        Return a 3-tuple for pickling a FITS_rec. Use the super-class
        functionality but then add in a tuple of FITS_rec-specific
        values that get used in __setstate__.
        )
_converted_heapoffset	_heapsizer   _gap_uintparnames_coldefsr   N)ro   
__reduce__r   AttributeErrorrG   r   __deepcopy__getattr)r&   reconst_funcreconst_func_argsru   rw   rv   attrsry   s          r+   r   zFITS_rec.__reduce__   s(    271C1C1E1E.' 	
 	# 	#E .)) # # J&& ''(B(B4(H(HIIII ''e(<(<===E"""# # # # # # # # # # # # # # # t,,.55s   A-B;;B?	B?	c                 >   |d S t          |t                    r|j        | _        t          |t                    rr|j        | j        k    rb|j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j	        | _	        |j
        | _
        |j        | _        d S | j        j        t          | j        j                  | _	        i | _        t          |dd          | _        t          |dd          | _        t          |dd          | _
        t          |dd          | _        t          j                    | _        t#          |           | _        | j        D ]}|`t          j        |           |_        d S |                                  d S )Nr|   r   r}   r~   r   F)r0   r_   _character_as_bytesrc   r{   r|   r}   rr   r   r   r~   r   rj   r   r   rQ   rq   r   r   ref_parent_fits_recri   )r&   objcols      r+   __array_finalize__zFITS_rec.__array_finalize__   st   ;Fc8$$ 	?'*'>D$c8$$ 	dj)@)@!nDO"D ]DN!$!2DLDMLDMDIDJJJZ*  
 122DM DO&sM1==D$S+q99DNVQ//DI gu55DJ!(!2!2D#DMMDM } 9 9I'.{4'8'8$$9 9 JJLLLLLr-   c                     d| _         i | _        d| _        d| _        t	          j                    | _        d| _        d| _        d| _	        dS )z6Initializes internal attributes specific to FITS-isms.r   NF)
r   r{   r|   r}   rQ   rq   rr   r   r~   r   rB   s    r+   ri   zFITS_rec._init  sH    $_..	


r-   r   c           
      `
   t          |t                    st          |          }|D ]V}|j        }t          |t                    r8|j        j        d|_        2t          |j        j        |j                  |_        W|`|dk    r$|j        D ]}||j	        d         }nd}||k    r|}t          j        |j        j        |z  t          j                  }|                    t!          |j                             t          j        ||j        |                              |           }	||	_        ||	_        |r|	S t-          |          D ]\  }
}|j        }|d}nt/          |          }t1          ||          }|s4t          |	|
          }|j        }|j        }|j        }|d|         }|d|         }t          |t8                    r/|j	        d         |j        k    rt=          |||j                   nt          |t>                    r(|	                     |tC          ||||                     |dd         tD          d         k    r|j        tF          k    rt!          d	          |dd<   t          j$        |j	        tF                    }||d|<   |	                     ||           t          j%        |t          j&        k    t!          d	          t!          d
                    }n||
         j'        re||
         j(        rX|j)        }t          j$        |j	        |j                  }||d|<   |	                     ||           ||k     r| ||d<   ||z
  }nt          |tT                    r|j+        r3|                    t          j        t          j,                  d|         }nR|j        j-        dvrD|	                     |t          j$        ||j                             |	j.        |         d|         }||dd<   |j	        |j	        k    r|j        j-        |j        j-        k    rW|j        j-        dv rI|j        |j        k    r9|d         j/        }|0                                                    |j                  }|j1        dk    r0|d         j/        }|2                    ||          }||ddd|f<   |3                                |d|<   ||dd<   ti          t/          |                    D ]}
|	                    |
          |j        |
<    |	S )a  
        Given a `ColDefs` object of unknown origin, initialize a new `FITS_rec`
        object.

        .. note::

            This was originally part of the ``new_table`` function in the table
            module but was moved into a class method since most of its
            functionality always had more to do with initializing a `FITS_rec`
            object than anything else, and much of it also overlapped with
            ``FITS_rec._scale_back``.

        Parameters
        ----------
        columns : sequence of `Column` or a `ColDefs`
            The columns from which to create the table data.  If these
            columns have data arrays attached that data may be used in
            initializing the new table.  Otherwise the input columns
            will be used as a template for a new table with the requested
            number of rows.

        nrows : int
            Number of rows in the new table.  If the input columns have data
            associated with them, the size of the largest input column is used.
            Otherwise the default is 0.

        fill : bool
            If `True`, will fill all cells with zeros or blanks.  If
            `False`, copy the data from input, undefined cells will still
            be filled with zeros/blanks.
        Nr   rc   )rc   ra   rm   )nrowsrn   LFTSU)r   r   r   )5r0   r   r   r   hdurh   _get_recarray_fieldr7   _arraysrg   rV   emptyrc   itemsizeuint8fillord_padding_bytere   viewr   r   	enumerater   minnameformat	recformatr   repeatr   r   _cache_fieldr   r   boolzeroswhereFalse__physical_values_pseudo_unsigned_intsbzeror   _pseudo_logicalndarraykindr{   sizeflattenndimreshaperavelr<   )clscolumnsr   r   character_as_bytescolumnarrdimraw_datarh   rK   
array_sizenr7   r   
fitsformatr   outarrinarr	convertedr   inarr_rowsizes                         r+   from_columnszFITS_rec.from_columns  s;   B '7++ 	'g&&G  	P 	PF,C#w'' P7<'#'FLL#6sw|SY#O#OFL O A::    ?)A,CCC;;E8GM2U:"(KKKc'/00111{58DDDII#NN#5   
  	K %W-- o	" o	"KC ,C{

 XX
J&&A   'c22E;DJ",I2A2YFGE)X.. 4;r?i&6665&)*:;;; 7 Ix00 /!!$ueYe(T(T(TUUU 233:c?22u{d7J7J s88aaa HU[===	 %	"1"!!$	222 ")!3SXXs3xxHH. 73<3U HU[DDD	 %	"1"!!$	222u99!&E!""IG]33  - 7
 #ZZ"*==bqbAFFY^:55 %%dBHU#),L,L,LMMM!_T22A26F!qqq	{fl**K$(999(J66v|33$)!HMM!MMOO00>>E ;??$)!HMM!MM!];;E05F111n}n,--
 "'F2A2JJ!qqq		 W&& 	3 	3C#'::c??GOC  r-   c                 @    t           j                            |           S rA   )rV   r   rL   rB   s    r+   rL   zFITS_rec.__repr__  s     z""4(((r-   c                     	 t                               | |          S # t          $ r Y nw xY w| j        #|| j        j        v r|                     |          S t                                          |          S rA   )object__getattribute__r   r   r   r2   r7   ro   )r&   rx   ry   s     r+   r   zFITS_rec.__getattribute__  s    	**4666 	 	 	D	
 =$1C)C)C::d### ww''---s    
++c                 $   | j         !t                                          |          S t          |t                    r|                     |          S |                     t          j                  |         }t          |          t          j        ur| 
                    | |          S |                    t          |                     }| j        |_        t          | j                   |_         g }i |_        t          | j         j                  D ]p\  }}|                    | j         j        |         |                    || j        v r7| j        |         }t          j                            ||          }||j        |<   q||j         _        |S rA   )r   ro   r:   r0   r1   r7   r   rV   re   r4   _record_typer   r   r{   r   r2   rG   r   r   )	r&   r8   outarraysrK   r   dummyr7   ry   s	           r+   r:   zFITS_rec.__getitem__  sZ   = 77&&s+++c3 	#::c??"
 ii$$S)99BK'' $$T3/// hhtDzz""J	t}--"4=#677 	- 	-IC MM$-/4S9:::
 t&&-
..uc::',t$%
r-   c                 8   | j         "t                                          ||          S t          |t                    r|| |         d d <   d S t          |t
                    rt          t          |           |j        pt          |                     }t          d|          }t          d|j
        pd          }t          ||t          |          z             }t          ||          D ]!}|                     ||||z
                      "d S t          |t                    rZt          | j                  D ]C}|                    | j        |                   |                     | j        |                   |<   Dd S t          |t           t"          t$          j        f          rg| j        t          |          k    r7t          | j                  D ] }||         |                     |          |<   !d S t)          d| j         d          t+          d          )Nr   z%Input tuple or list required to have z
 elements.z;Assignment requires a FITS_record, tuple, or list as input.)r   ro   r?   r0   r1   r    r   r   r5   maxr"   r<   r   r   r7   r2   tuplelistrV   void
ValueError	TypeError)r&   r8   r>   r#   r"   rK   ry   s         r+   r?   zFITS_rec.__setitem__#  s   = 77&&sE222c3 	 DIaaaLFc5!! 	c$ii!6SYY77Ca++C39>**Ec53u::-..CUC(( : :  eC%K&89999Fe[)) 	T]++ P P38;;tz#3O3O

4:c?++C00P PtRW566 	}E

** // 6 6C+0:DJJsOOC((6 6 !UDMUUU   M  r-   c                     | j         S rA   )r2   rB   s    r+   _ipython_key_completions_z"FITS_rec._ipython_key_completions_E  s
    zr-   Cc                     t                                          |          }t          j        | j                  |_        |S )a  
        The Numpy documentation lies; `numpy.ndarray.copy` is not equivalent to
        `numpy.copy`.  Differences include that it re-views the copied array as
        self's ndarray subclass, as though it were taking a slice; this means
        ``__array_finalize__`` is called and the copy shares all the array
        attributes (including ``._converted``!).  So we need to make a deep
        copy of all those attributes so that the two arrays truly do not share
        any data.
        )order)ro   copydeepcopy__dict__)r&   r   newry   s      r+   r   zFITS_rec.copyH  s4     gglll''}T]33
r-   c                     | j         S )z(A user-visible accessor for the coldefs.)r   rB   s    r+   r   zFITS_rec.columnsW  s     }r-   c                 6    | j                             d          S Nr   )r   getrB   s    r+   r   zFITS_rec._coldefs\  s    $ }  ,,,r-   c                     || j         d<   t          |t                    r$|j        D ]}| j                            |           d S d S r   )r   r0   r   r   rr   add)r&   colsr   s      r+   r   zFITS_rec._coldefsp  s_    $(j!dG$$ 	,| , ,"&&s++++	, 	,, ,r-   c                 p    	 | j         d= d S # t          $ r}t          |j        d                   d }~ww xY w)Nr   r   )r   r3   r   args)r&   excs     r+   r   zFITS_rec._coldefsw  sJ    	.j))) 	. 	. 	. !---	.s    
505c                     	 | ` | j        j        /| j        D ])}|j        |j                                        |_        (d S d S # t          t          f$ r Y d S w xY wrA   )r   rc   rj   rr   r   r   r   r   )r&   r   s     r+   __del__zFITS_rec.__del__~  s    		z ,- 5 5Cy,$'INN$4$4	 -,5 5
 	* 	 	 	DD	s   =A AAc                     | j         j        rt          | j         j                  S t	          | dd          | j        j        S dS )zList of column names.r   N)rc   rj   r   r2   r   r   rB   s    r+   r2   zFITS_rec.names  sF     : 	
()))T:t,,8=&&4r-   c                 @    t          | dd          | j        j        S dS )zList of column FITS formats.r   N)r   r   formatsrB   s    r+   r   zFITS_rec.formats  s&     4T**6=((tr-   c                     t          |           rMd}| j        j                                        D ]*}|d         j        }|d         j        dk    r|dz  }||z  }+|S | j        S )z
        Returns the size of row items that would be written to the raw FITS
        file, taking into account the possibility of unicode columns being
        compactified.

        Currently for internal use only.
        r   r      )_has_unicode_fieldsrc   rj   valuesr   r   )r&   total_itemsizer7   r   s       r+   _raw_itemsizezFITS_rec._raw_itemsize  s{     t$$ 
	!N*1133 + + 8,8=C'''1}H(*!! = r-   c                    | j         |         }|j        }|j        }|j        j        dk    rBt          j        d                    |                     t          j        g |j                  S | }t          |t                    rZt          |j        t          j                  r;|j        }t          |t                    rt          |j        t          j                  ;t          ||          }|| j        vrj|j        }t          |t                     r| j        r|                     |||          }n|                     |||          }|                     ||           |S | j        |         S )z:
        A view of a `Column`'s data as an array.
        r   zQField {!r} has a repeat count of 0 in its format code, indicating an empty field.r   )r   r   r   rc   r   warningswarnrV   r   r0   r_   r%   re   r   r{   r   r   _load_variable_length_data
_convert_p_convert_otherr   )	r&   r8   r   r   r   r%   r7   r   r   s	            r+   r7   zFITS_rec.field  sj    c"{< A%%M--3VC[[   8Bfl3333
 x(( 	Z	2;-O-O 	9D x(( 	Z	2;-O-O 	
 $D$//t&&(I )X.. J43R J OOFE9EE		 !//yII	 dI...t$$r-   c                     |}	 | }	 ||u rdS t          |dd          |j        }nn!t          |dd          |j        }nn?|| j        |<   dS )a  
        Do not store fields in _converted if one of its bases is self,
        or if it has a common base with self.

        This results in a reference cycle that cannot be broken since
        ndarrays do not participate in cyclic garbage collection.
        TNr%   )r   r%   r{   )r&   r   r7   r%   	self_bases        r+   r   zFITS_rec._cache_field  s     	I$$F9fd33? )II tVT**6y	  !&r-   c                 l    d| }t          | |          r t          | |          ||||           dS dS )a  
        Update how the data is formatted depending on changes to column
        attributes initiated by the user through the `Column` interface.

        Dispatches column attribute change notifications to individual methods
        for each attribute ``_update_column_<attr>``
        _update_column_N)hasattrr   )r&   r   rK   rx   	old_value	new_valuemethod_names          r+    _update_column_attribute_changedz)FITS_rec._update_column_attribute_changed  sX     /..4%% 	J 'GD+&&vsIyIIIII	J 	Jr-   c                 j    | j         }|j        d|         |fz   |j        |dz   d         z   |_        dS )z;Update the dtype field names when a column name is changed.Nr   )rc   r2   )r&   r   rK   old_namer   rc   s         r+   _update_column_namezFITS_rec._update_column_name  s:    
k$3$'4'1EKa		4JJr-   c                     t          j        | j        |j        fz   t           j                  }t          |||j                   |S )z]Convert a raw table column to a bit array as specified by the
        FITS X format.
        r   )rV   r   rg   r   bool_r   )r&   r7   r   r   s       r+   
_convert_xzFITS_rec._convert_x  sA     y'7&99JJJy/000r-   c                 
   |j         rgt          t          t          t          t          |j                             d                              d                                                  }t          dgt          |           z  |j	                  }| 
                                }|'t          d                    |j                            t          t          |                     D ]}||df         | j        z   }||df         }	|j	        dk    rt!          j	        |j	        t#          d          z             }
|	|
j        z  }||||z                                |
          }t           j                            |                    |
          |		          }t-          |          ||<   t!          j	        |j	                  }
|	|
j        z  }||||z                                |
          ||<   |j         rt          |          dk    r|d         dk    r3||                             dt          ||                             ||<   nc|dd         }t	          t          ||                   t!          j        |          z            }||                             |f|z             ||<   ||         j	                            d
          ||         _	        |                     |||         |          ||<   |S )zConvert a raw table column of FITS P or Q format descriptors
        to a VLA column with the array data returned from the heap.
        z(),Nr   zCCould not find heap data for the {!r} variable-length array column.r   r   a)r   >)r   r   rX   mapintstripsplitr   r   rc   _get_raw_dataOSErrorr   r   r<   r|   rV   r1   r   r   r   r   r   r   prodnewbyteorderr   )r&   r   r7   r   	vla_shaper   r   rK   offsetcountdtarr_lendavla_dim	vla_firsts                  r+   r   zFITS_rec._convert_p  s    : 	s3
(8(8(>(>(D(DS(I(IJJKKLL I dVc$ii'y???%%''  &v{ 3 3  
 T## !	P !	PC36]T%55F#q&ME#%%XioA677"+-fv'778==bAAW]]2777#4#4u]EE)"--c

Xio.."+-%fv/?&?@EEbIIc
: P#i..1"4"4 |q((%*3Z%7%73uSz??%K%Kc

"+ABB-$'E#J"'':J:J(J$K$K	%*3Z%7%7w8N%O%Oc
#(:#3#@#@#E#Ec
  "00sYOOc

r-   c                    |j         }t          |dt          |d                            }t          |j                                                                      d          }t          |          |j        k    r|d|j                 }t          j
                            ||j                  }t          j
                            |t          d          t          d                    }t          t          t                                        |j                            }t          j        t          j
                            |          |k    ||          }|dk    r7t          j        t          j
                            |          dk    ||          }	 t          j        ||          }nW# t$          $ rJ}| j                            |j                  }	t%          d	                     ||	d
z                       d}~ww xY w|S )z
        Special handling for ASCII table columns to convert columns containing
        numeric types to actual numeric arrays from the string representation.
        r   r   asciiNDEr-   r   z^{}; the header may be missing the necessary TNULL{} keyword or the table contains invalid datar   )r   r   r	   r1   nullr  encoder   r)   rV   r   ljustreplacer   r   rjustr   r   r   r2   indexr   )
r&   r   r7   r   r   nullvalr   	null_fillr   r9   s
             r+   _convert_asciizFITS_rec._convert_asciiO  s   
 FKVAY1GHH	fk""((**11'::w<<&,&&nn-G eV\22|C'8'8,s:K:KLL Z!6!6v|!D!DEE	
 u--8)UKK c>>HRW]]511S8)UKKE	HU)444EE 	 	 	:##FK00D==CVCPQ=R=R  	 s   F/ /
H9AG>>Hc           	      p   t          |t                    r|                     ||          S |                     |          }|\  }}}}}	}
}}| j                            |j                  }|s0t          | j        t                    r| 	                    ||          }|r|j
        dk    r|j        dd         }|r||j        fz   }n|j        d         }||k    rd}nt          t          j        |          }|r|j        }n(t!          |j                  dk    rd}n|j        d         }||k    rWt          |t"                    sBt%          j        d                    |dz   | j        |         j        ||dz                        d}|j        s|j        j        r|j        j        }n|j        j        }|r{|s|	rv|j        sn| j        r|dk    r'|dk    r!t5          j        |t4          j                  }n|dk    r'|d	k    r!t5          j        |t4          j                  }n|d
k    r;|dk    r5t5          j        |t4          j                  }t5          j        d
          }nAt5          j        |t4          j                  }n t5          j        |t4          j                  }|rt5          j         ||
|           |	ri| j        r]|dk    rW|!                                }	 ||z  }|}n?# tD          $ r- t%          j        d                    |dz                        Y n	w xY w||z  }d|_        ny|r3|j#        tH          k    r#t5          j%        |tM          d                    }nD|rB| j'        s;tQ          tR                    5  tU          |          }ddd           n# 1 swxY w Y   |rt          |t"                    svt          t          j        |          }|j
        dk    r|ddd|f         }|r+|j#        j+        }d| |d          |dd         f}||_#        n|j        d         f|z   |_        |S )zPerform conversions on any other fixed-width column data types.

        This may not perform any conversion at all if it's not necessary, in
        which case the original column array is returned.
        r   Nr   zbTDIM{} value {:d} does not fit with the size of the array items ({:d}).  TDIM{:d} will be ignored.i   Ir           Jl            KzDOverflow detected while applying TZERO{:d}. Returning unscaled data.Tr   |rm   ),r0   r   r  _get_scale_factorsr2   r)  r   r   r   r,  r   rg   r   r   operatormulr   r   r   r   r   dimsr!  p_formatr   r   rV   r   uint16uint32uint64float64multiplyr   OverflowErrorrc   r   equalr   r   r   UnicodeDecodeErrorr   r   )r&   r   r7   r   scale_factors_str_bool_number_scale_zerobscaler   r   r9   actual_shapenitemsactual_nitemsformat_codebzero64test_overflowfmtrc   s                         r+   r   zFITS_rec._convert_otherw  s    i** 	5??5)444//77BO?eWfeVUCz,,  	7
4=-@@ 	7''66E  	 zA~~${122 D#/5>2C#CL${1~l"" c22 3$)NMM%%**$%MM$)KNMM))*Y2Q2Q)MMMSV 1HdmD&9&>tVWxN N   C | 	/ 6 	/ -0KK !-.K +	0 +	0% +	01H +	0 z :E>>kS&8&8HU")<<<EEe^^s(:(:HU")<<<EEe^^s(:(:HU")<<<E i..GGHU"*===EEbj999 2E65111 #: #+"4"4$)JJLLM.%0 !. )    77=vdQh7G7G     UNE '+F## 	0u{d**HUCHH--EE 	0+ 0011 0 0(//E0 0 0 0 0 0 0 0 0 0 0 0 0 0 0  
	6z)X66 
	6HL#..FzA~~aaa&j) 6k&+S+#b'++S"X6#${1~/#5s$   !K) )4L L NN"%N"c                     | j         rO|                                                     t          j                  }| j        | j         z   }|| j        |         S t          j        g t          j                  S )z
        Returns a pointer into the table's raw data to its heap (if present).

        This is returned as a numpy byte array.
        r   )r}   r  r   rV   ubyter|   r   )r&   r   heap_ends      r+   _get_heap_datazFITS_rec._get_heap_data  sh     > 	0))++00::H'$.8HD,x7888Bbh////r-   c                 4   | j         | j        z   }| }t          |d          rr|j        m|j        }t          |d          rt          |d          r|j         |k    r|S nt          |d          r|j         |k    r|S t          |d          r|j        idS dS dS dS )a  
        Returns the base array of self that "raw data array" that is the
        array in the format that it was first read from a file before it was
        sliced or viewed as a different type in any way.

        This is determined by walking through the bases until finding one that
        has at least the same number of bytes as self, plus the heapsize.  This
        may be the immediate .base but is not always.  This is used primarily
        for variable-length array support which needs to be able to find the
        heap (the raw data *may* be larger than nbytes + heapsize if it
        contains a gap or padding).

        May return ``None`` if no array resembling the "raw data" according to
        the stated criteria can be found.
        r%   Nr|   nbytes)rS  r}   r  r%   )r&   raw_data_bytesr%   s      r+   r  zFITS_rec._get_raw_data	  s      t~5dF## 
	 	(=9D t]++  4**  t{^/K/KK 4**  t{n/L/LK dF## 
	 	(=(=(= 
	  
	 (=(= 
	  
	 r-   c                     |j         j         dk    }|j         j         dk    }|p| }|j        }|j        }|dv}|dv}|sd}|sd}|j        }	||||||||	fS )z5Get all the scaling flags and factors for one column.Ar   ) Nr   )rW  Nr   r   r   )r   rF  r   _dims)
r&   r   rA  rB  rC  rF  r   rD  rE  r   s
             r+   r3  zFITS_rec._get_scale_factors'  s     }#s*$+}%},]*  	F 	E leWfeVUCHHr-   c           	         d}t          | j        j                  D ]\  }}| j        |         }|j        j        }t          | |          }t          |t                    r	t          j
        g |j                  j        }|r|| j        v rd|dd<   d | j        |         D             }	|	|dt          |	          df<   t          j                            |dddf                   |j        z  |dddf<   |dddf         ddxx         |z  cc<   ||dddf                                         |j        z  z  }t#          |          t          k    r|dk    rt%          d          t          |t&                    r,|| j        v r#t)          | j        |         ||j                   |                     |          }
|
\  }}}}}}}}| j                            ||          }|s|rK|r5|s|r1|j        r*|                                }|r||z  }|r||z  }d	|_        n!|st          | j        t4                    r|}n't          | j        t4                    r|                     |||           nt          |t8          j                  r|                     |||           nt          |          r4t          |d         t          j                  rt          j        |          }|j         |j         k    r||dd<   n1|!                                "                    |j                  |dd<   ~|r|| j        v rt          j
        tG          d
          gt          j$                  d         t          j
        tG          d          gt          j$                  d         f}t          j%        ||          |dd<   || _&        dS )a	  
        Update the parent array, using the (latest) scaled array.

        If ``update_heap_pointers`` is `False`, this will leave all the heap
        pointers in P/Q columns as they are verbatim--it only makes sense to do
        this if there is already data on the heap and it can be guaranteed that
        that data has not been modified, and there is not new data to add to
        the heap.  Currently this is only used as an optimization for
        CompImageHDU that does its own handling of the heap.
        r   r   Nc                 @    g | ]}t          j        |j                  S r]   )rV   r  rg   ).0r   s     r+   
<listcomp>z(FITS_rec._scale_back.<locals>.<listcomp>a  s$    PPP3BGCI..PPPr-   rm   r   r/  zgThe heapsize limit for 'P' format has been reached. Please consider using the 'Q' format for your file.Fr   r   )'r   rc   r2   r   r   r   r   r0   r   rV   r   r{   r   r   
accumulater   sumr4   r   r   r   r   r3  r   r   r   r   _scale_back_ascii	chararray_scale_back_stringsintegeraroundrg   r   r   r   int8chooser}   )r&   update_heap_pointersheapsizer9   r   r   r   	raw_fieldrc   nptsr@  rA  rB  rC  rD  rE  rF  r   _r7   r   choicess                         r+   _scale_backzFITS_rec._scale_backA  s    #DJ$455 X	9 X	9JD$]4(F/I+D$77I )X.. 
 9?;;;A' 
3DDO,C,C $%IaaaLPP$/$:OPPPD04IkD		k1n-)))CRCF*;<<u~M abb!e$ aaadOAAA&&&(2&&&IaaadO//11ENBB 	??h..8u3D3D$N   )X.. 44?3J3Jtt,i9IJJJ 33F;;MDQAD%&%O''i88E  +9$ +9  % V5L !JJLLE ' ( /4F++ Z}EE !EE dm];; K**4	BBBB	9+>?? K,,T5)DDDD 9~~ 1*Yq\2:*N*N 1 "	% 0 0 %+55',	!!!
 (-{{}}'9'9)/'J'J	!!!E  944?22Hc#hhZrw777:Hc#hhZrw777:  "y88	!!! "r-   c           	         |j         j        dk    r|j         j        dk    r	 t          ||           n# t          $ rh}t	          d                    | j        |         j        t          |j	                  dk    r|j	        d         n|j	        |j
                            d }~ww xY w|                                                    |j                   }||j        d d <   t          |           d S )Nr   r   )r   zCould not save column '{}': Contains characters that cannot be encoded as ASCII as required by FITS, starting at the index {!r} of the column, and the index {} of the string at that location.r   r   )rc   r   _ascii_encode_UnicodeArrayEncodeErrorr   r   r   r   r   r)  r"   r   r   flatr   )r&   col_idxinput_fieldoutput_fieldr   s        r+   ra  zFITS_rec._scale_back_strings  s   & !S((\-?-D-K-Kk|<<<<<+ 
 
 
 3 4:6g.3(+CI!(;(;	!	4 4		 	 	
 &--//44\5GHHK#.Laaa 
 	%%%%%s   4 
B&A#B!!B&c                    | j         j        dd         }| j         j        }| j         |         j        }t	                                          d          j        }|                    ||d         z              |dk    r!||         ||dz
           z
  ||dz
           z
  }nd}|dk     rt          j	        d|dz    d           ||dz            ||         z
  ||         z
  }	|	dk     rt          j	        d|dz    d           d|v rd	}
nd
}
d
                    |
|dd         t          |d                  dd|	z  g          }|j        dk    o|j        dv }t          |          D ]\  }}|                    |          }t          |          ||dz            ||         z
  k    r)t          d                    |||                             |r|d         dk    r|dd         dz   }|||<   d|v r|                    dd          |dd<   dS dS )a  
        Convert internal array values back to ASCII table representation.

        The ``input_field`` is the internal representation of the values, and
        the ``output_field`` is the character array representing the ASCII
        output that will be written.
        Nrm   r   r   zColumn z- starting point overlaps the previous column.z' ending point overlaps the next column.rV  z{:z{:>rW  } )r   r#  r"  z9Value {!r} does not fit into the output's itemsize of {}..r"     E   D)r   startsspansr   ro   r7   r   rG   r   r   rI   r
   	precisionr   r   r   r'  )r&   rq  rr  rs  rz  r{  r   r#   leadtrail_pcrM  trailing_decimaljdxr>   ry   s                  r+   r_  zFITS_rec._scale_back_ascii  sg    %aaa(#w'. ggmmB(cF2J&'''Q;;'?VGaK%8851;MMDDD!88MT'A+TTT   w{#fWo5gF199MN'A+NNN   &==CCCggsF122J	&)(<cC%KQRR
 "+q0UV]o5U $K00 	& 	&JCJJu%%E5zzF7Q;/&/AAA OVVuW~      (E!HOO abb	C %L &==*224>>LOOO =r-   c                 Z      fd j         j        D             }d t          | D             S )Nc                 D    g | ]}|                                          S r]   )tolist)r[  r   r&   s     r+   r\  z#FITS_rec.tolist.<locals>.<listcomp>"  s)    KKKT
))++KKKr-   c                 ,    g | ]}t          |          S r]   )r   )r[  r   s     r+   r\  z#FITS_rec.tolist.<locals>.<listcomp>$  s    888cS		888r-   )r   r2   rs   )r&   column_listss   ` r+   r  zFITS_rec.tolist  s=     LKKK8JKKK88S,%78888r-   )r   FF)r   )T).rY   rZ   r[   r\   r   r   r   r   rf   rp   r   r   ri   classmethodr   rL   r   r:   r?   r   r   propertyr   r   setterdeleterr   r2   r   r   r7   r   r  r  r  r   r,  r   rQ  r  r3  rl  ra  r_  r  __classcell__ry   s   @r+   r_   r_      s)         L!%  (
' 
' 
' 
' 
'!6 !6 !6 !6 !6F& & &P	 	 	 G G G [GR) ) )
. . . . .(% % % % %N         D          X - - X-& _, , _, . . .
 
 
   X   X ! ! X!(/% /% /%b& & &6J J JK K K  4 4 4l& & &PC C CJ0 0 0     <I I I4i" i" i" i"V*& *& *&XE? E? E? E? E?N9 9 9 9 9 9 9r-   r_   c                     t           j                            | |          }|j        j        dv r9t          |t          j                  s|                    t          j                  }|S )z
    Compatibility function for using the recarray base class's field method.
    This incorporates the legacy functionality of returning string arrays as
    Numeric-style chararray objects.
    r   )rV   re   r7   rc   r   r0   r`  r   )r   r8   r7   s      r+   r   r   '  sV     KeS))E{:%%j	@S.T.T%

9.//Lr-   c                        e Zd Z fdZ xZS )ro  c                 `    t                                          |||||           || _        d S rA   )ro   r,   r)  )r&   encodingobject_r"   r#   reasonr)  ry   s          r+   r,   z!_UnicodeArrayEncodeError.__init__7  s.    7E3???


r-   )rY   rZ   r[   r,   r  r  s   @r+   ro  ro  6  s8                r-   ro  c                    t          j        d| j        j        dz   | j        j        f          }||                    |          }| j        |g}dgddgg}t          j        | |g||dg          }	 |D ]/\  }}|                                                    d	          |d
<   0nC# t          $ r6}t          j	        |j
        | j                  }	t          |j        |	fz    d}~ww xY w|j        d         S )a[  
    Takes a unicode array and fills the output string array with the ASCII
    encodings (if possible) of the elements of the input array.  The two arrays
    must be the same size (though not necessarily the same shape).

    This is like an inplace version of `np.char.encode` though simpler since
    it's only limited to ASCII, and hence the size of each character is
    guaranteed to be 1 byte.

    If any strings are non-ASCII an UnicodeArrayEncodeError is raised--this is
    just a `UnicodeEncodeError` with an additional attribute for the index of
    the item that couldn't be encoded.
    r   r   Nreadonly	writeonlyallocatezerosize_ok)	op_dtypesop_flagsflagsr!  .r   )rV   rc   r   rg   r   nditeritemr%  UnicodeEncodeErrorunravel_index	iterindexro  r   operands)
inarrayr   	out_dtyper  r  itinitemoutitemr   r)  s
             r+   rn  rn  <  s    ;gm49;;W]=PQRRI
hhy!!	*I{J78H		#)h}o
 
 
B?! 	9 	9OFG!;;==//88GCLL	9 ? ? ? w}==&UH)<>>? ;q>s   42B' '
C'11C""C'c                     d | j         j                                        D             }t          d |D                       S )zN
    Returns True if any fields in a structured array have Unicode dtype.
    c              3   &   K   | ]}|d          V  dS )r   Nr]   r[  ds     r+   	<genexpr>z&_has_unicode_fields.<locals>.<genexpr>b  s&      88qad888888r-   c              3   ,   K   | ]}|j         d k    V  dS )r   N)r   r  s     r+   r  z&_has_unicode_fields.<locals>.<genexpr>c  s(      --qv}------r-   )rc   rj   r   any)r   dtypess     r+   r   r   ^  sE     98EK.5577888F--f------r-   rA   ))r   r4  r   rQ   
contextlibr   	functoolsr   numpyrV   r   r`  astropy.utilsr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   utilr   r   r   r   re   r_   r   r  ro  rn  r   r]   r-   r+   <module>r     s                       # # # # # # & & & & & &                                 > = = = = = = = = =p p p p p p p pfO9 O9 O9 O9 O9r{ O9 O9 O9d$      1      D. . . . .r-   