
    HR-eq                     @   d Z ddlZddlZddlmZ ddlmZmZ ddlm	Z	 ddl
mZ ddlZddlmZ ddlmZmZmZ d	d
lmZmZmZ dZdZdgZg dZg dZ G d dej                  Z G d dej                   Z! G d dej"                  Z# G d dej$                  Z%dS )zClasses to read AAS MRT table format.

Ref: https://journals.aas.org/mrt-standards

:Copyright: Smithsonian Astrophysical Observatory (2021)
:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu),          Suyog Garg (suyog7130@gmail.com)
    N)StringIO)ceilfloor)Template)wrap)units)ColumnMaskedColumnTable   )cdscore
fixedwidthP   i *)z'Byte-by-byte Description of file: $fileP--------------------------------------------------------------------------------z+ Bytes Format Units  Label     Explanationsr   $bytebybyter   )zTitle:zAuthors:zTable:zP================================================================================r   zNotes:r   c                       e Zd ZdZd ZdS )MrtSplitterz^
    Contains the join function to left align the MRT columns
    when writing to a file.
    c                 j    d t          ||          D             }| j                            |          S )Nc                 D    g | ]\  }}|d |t          |          z
  z  z   S ) len).0valwidths      4lib/python3.11/site-packages/astropy/io/ascii/mrt.py
<listcomp>z$MrtSplitter.join.<locals>.<listcomp>;   s1    SSS:3cUSXX-..SSS    )zip	delimiterjoin)selfvalswidthss      r   r#   zMrtSplitter.join:   s5    SST6ARARSSS~""4(((r    N)__name__
__module____qualname____doc__r#    r    r   r   r   4   s-         
) ) ) ) )r    r   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )	MrtHeaderMRTc                    t          j        dt           j                  }|                    |          }|t	          | d          t          |          t          |                    d                    t          |                    d                    |                    d          dk    |                    d          dk    fS )	a  
        Splits a Float string into different parts to find number
        of digits after decimal and check if the value is in Scientific
        notation.

        Parameters
        ----------
        value : str
            String containing the float value to split.

        Returns
        -------
        fmt: (int, int, int, bool, bool)
            List of values describing the Float string.
            (size, dec, ent, sign, exp)
            size, length of the given string.
            ent, number of digits before decimal point.
            dec, number of digits after decimal point.
            sign, whether or not given value signed.
            exp, is value in Scientific notation?
        z(?P<sign> [+-]*)
                (?P<ent> [^eE.]+)
                (?P<deciPt> [.]*)
                (?P<decimals> [0-9]*)
                (?P<exp> [eE]*-*)[0-9]*Nz is not a float numberentdecimalssign exp)recompileVERBOSEmatch	Exceptionr   group)r$   valueregfloatmos       r   _split_float_formatzMrtHeader._split_float_formatB   s    , :+
 J
 
 ^^E"":u<<<===JJ  $$%%HHV"HHUOOr!
 	
r    c                     t          |          |_         t          |          |_        |j         t          j        j        j        u rd|_         |j        t          j        j        j        u r	d|_        dS dS )z
        Sets the ``col.min`` and ``col.max`` column attributes,
        taking into account columns with Null values.
        N)maxminnpmar   MaskedConstant)r$   cols     r   _set_column_val_limitsz MrtHeader._set_column_val_limitsl   s`    
 c((c((7bej///CG7bej///CGGG 0/r    c                    d\  }}}}d}d}|j         D ]}||dk    r|                     |          }	|	d         du r|dk    rd\  }}}d	}n|d	k    r@||	d
         k     r|	d
         }||	d         k     r|	d         }||	d         k     r|	d         }|	d         rd}||	d         |	d         z   k     r|	d         |	d         z   }|d	k    rt          |dd          ||_        |r|xj        dz  c_        |t	          |j                  z   dz   t	          |          z   |_        t	          |j                  dz   t	          |          z   dz   |_        dS d}
t          |dd           ||z   dz   |_        |r|xj        dz  c_        n|j                            d          rd}
|t	          |j                  z   dz   t	          |          z   |_        |
|j        dd         z   dz   |_        dS )a  
        String formatter function for a column containing Float values.
        Checks if the values in the given column are in Scientific notation,
        by splitting the value string. It is assumed that the column either has
        float values or Scientific notation.

        A ``col.formatted_width`` attribute is added to the column. It is not added
        if such an attribute is already present, say when the ``formats`` argument
        is passed to the writer. A properly formatted format string is also added as
        the ``col.format`` attribute.

        Parameters
        ----------
        col : A ``Table.Column`` object.
        )r   r   r   r   FFNr3      T)r   r   r   Er   r         formatted_width.e0f)str_valsr>   getattrrM   strfortran_formatformat
startswith)r$   rE   maxsizemaxprecmaxentmaxdecr2   fformatr   fmtleads              r   column_float_formatterz MrtHeader.column_float_formatterx   sP   ( ,6(&& < !	* !	*C{cRii **3//C1v~~ c>>/6,GWf c>>Qa&AQAQ1v Q#a&((a&3q6/c>>s-t44<&-# -''1,'' ")3s/B+C+C!Cc!ICPWLL!XCS011C7#f++EKCJJJD.55=&,vo&9# -''1,''&&s++  !(3s/B+C+C!Cc!ICPVKK!WC 2122 66<CJJJr    c                    g }| j                                         }t          | D ]}|                    |           t	          | j                  D ]]\  t          fd|D                       _        | j        1t          j        t          j
        j                            _        ^d | j        D             }d}t          t          t          |          t          | j                  z   dz
                      }dt          |          z   dz   }|dz   |z   }|dz  }|dz  }d	\  }	}
t          g d
t          gdz            }t	          | j                  D ]\  t          t                     _        j        #t          d j        D                       _        t)          j        j        t(          j                  r|                                t3          dd          St          t          t          j                            t          t          j                                      _        dt          j                  z   _        j        dj        dd         z   _        n4t)          j        j        t)          j        t8                    j                  r+|                                |                                nӉj        j        }j        r=}d|_        tA          |!                                t                    }|j        j        }t3          dd          :tE          tG          j$        d|          %                    d                    _        dt          j                  z   _        t          j                  dz   _        j        |z   dz
  }j        d_        j&        j&        }n
dj        z   }d}j        rd}j'        j'        (                    d          }n5j        )                                *                    d          dk    rd}nd}d}j        rj        rtW          fddD                       sÉj        d          dk    rjtY          j                  tZ          k     rLtY          j                  tZ          k     r/j        j        k    rd!j         d"}n\d!j         d#j         d"}nHj        d          d$v r9d!t]          j        d%z            d&z   d#t_          j        d%z            d&z   d"}|dk    s|dk    r	| | d| }t          j                  |	k    rt          j                  }	t          |          |
k    rt          |          }
j        d'k    r9|0                    |                    |          d(dd)d*g           d+_        |dz  }|0                    ||k    r|                    |          n|                    ||          j        dnj        |j        dnj        |g           |d,z   }tc                      }|2                    |d-dd.dd/d/d0t          |	          z   dz   dt          |
          z   dz   d12           |3                                4                                }|d,z  dz   d3z   |	z   d4z   }d}|D ]X}t          |          tj          k    r6|d56                    to          |d|z  tj          6                    z  }|d5z  }P||d5z   z  }Y|| _8        |dd         }|S )7aL  
        Writes the Byte-By-Byte description of the table.

        Columns that are `astropy.coordinates.SkyCoord` or `astropy.time.TimeSeries`
        objects or columns with values that are such objects are recognized as such,
        and some predefined labels and description is used for them.
        See the Vizier MRT Standard documentation in the link below for more details
        on these. An example Byte-By-Byte table is shown here.

        See: https://vizier.unistra.fr/doc/catstd-3.1.htx

        Example::

        --------------------------------------------------------------------------------
        Byte-by-byte Description of file: table.dat
        --------------------------------------------------------------------------------
        Bytes Format Units  Label     Explanations
        --------------------------------------------------------------------------------
         1- 8  A8     ---    names   Description of names
        10-14  E5.1   ---    e       [-3160000.0/0.01] Description of e
        16-23  F8.5   ---    d       [22.25/27.25] Description of d
        25-31  E7.1   ---    s       [-9e+34/2.0] Description of s
        33-35  I3     ---    i       [-30/67] Description of i
        37-39  F3.1   ---    sameF   [5.0/5.0] Description of sameF
        41-42  I2     ---    sameI   [20] Description of sameI
        44-45  I2     h      RAh     Right Ascension (hour)
        47-48  I2     min    RAm     Right Ascension (minute)
        50-67  F18.15 s      RAs     Right Ascension (second)
           69  A1     ---    DE-     Sign of Declination
        70-71  I2     deg    DEd     Declination (degree)
        73-74  I2     arcmin DEm     Declination (arcmin)
        76-91  F16.13 arcsec DEs     Declination (arcsec)

        --------------------------------------------------------------------------------
        c              3   B   K   | ]}t          |                   V  d S Nr   )r   r%   is     r   	<genexpr>z/MrtHeader.write_byte_by_byte.<locals>.<genexpr>   s-      ??TCQLL??????r    Nc                     g | ]	}|j         
S r+   )r   )r   rE   s     r   r   z0MrtHeader.write_byte_by_byte.<locals>.<listcomp>   s    111#)111r    r   z{:zd}-r   )      )BytesFormatUnitsLabelExplanations   )namesdtypec              3   4   K   | ]}t          |          V  d S rb   r   )r   svals     r   rd   z/MrtHeader.write_byte_by_byte.<locals>.<genexpr>  s(      )M)M#d)))M)M)M)M)M)Mr    rM   I>r3   )rp   z(\d+)$AsUnknownzDescription of ?r   	magnitudemagz---c              3   *   K   | ]}|j         v V  d S rb   name)r   xrE   s     r   rd   z/MrtHeader.write_byte_by_byte.<locals>.<genexpr>_  s:        &'AM     r    )RADELONLATPLNPLTr   []/)rJ   rH   d   g      Y@DEdA1zDE-zSign of DeclinationI2rK   zascii.fixed_width_no_headerFz<6s<)rj   rk   rl   rm   )rV   r"   bookenddelimiter_padformats   rI   
)subsequent_indentr   )9datarR   r!   append	enumeratecolsr@   r   
start_liner   infor~   rT   sumr   
isinstancer
   has_nullrV   rM   rB   
issubdtyperp   integerrF   rS   rA   rU   floattyper_   
fill_valuer	   filledintr5   searchr:   descriptionunit	to_stringlowerfindanyabsMAX_COL_INTLIMITr   r   add_rowr   writegetvalue
splitlinesMAX_SIZE_README_LINEr#   r   	linewidth)r$   	vals_listcol_str_itersr%   r&   startbbyte_count_width
singlebfmtfmtbmax_label_widthmax_descrip_sizebbbrp   mcolcoltmpendbr   nullflagcol_unitlim_valsbbblinesnsplitbuffnewlinerE   rc   s                           @@r   write_byte_by_bytezMrtHeader.write_byte_by_byte   s   J 		**,,' 	# 	#DT""""	** 	? 	?FAs????Y?????CI*	3sx}+=+=>>	11ty111
 s3v;;TY#?!#CDDEE C 0111D8
C*,c
 -2))GGGPSuWXy
 
 

  	** B	 B	FAs%c<88CLz%&))M)M)M)M)M&M&M# }SY
33 <++C0003 1488@*-c#cg,,.?.?S\\ARAR*S*SC'%(3s/B+C+C%C":%!$s'9!""'=!=CJsy"(5//*>?? <++C000++C0000 	< -D&(DO#DKKMM===F"L,E3 1488@*-bi	5.I.I.O.OPQ.R.R*S*SC'%(3s/B+C+C%C" !455;
&/!3D x$ *!o/#(: H|  x#8--e44!!&&{33b88 !  HG     +S     %a(C//CG'777LL+;;;7cg--'537~~~HH'?37'?'?SW'?'?'?H'*j88WE#'C-0047WW$sw}:M:MPT:TWWW  2~~R!)C8CCkCC 38}}.."%ch--;"222#&{#3#3  x5  "))&11-   &*"! KK ~~ %%f---VT22,4BB#:L(*BB
 
 
 AXFF ::		0s?333c9 "S)9%:%: :S @	  	 	
 	
 	
 $$&&1133 "A%)B.@1D  	' 	'G7||222*-,2     $&  CRCyr    c           
      R    ddl m} ddddd}g d}g }t           j                  D ]\  }}t	          ||          st	          |d         |          rk	  ||          }n^# t
          t          f$ rJ t	          |t                    st          |          }t          d	 |D                       }| j        |<   Y w xY wt	          ||          rhd
|j        	                                v rFt          t          |          t           j                  z
            dk    r|j        j        |j        j        }	}|j                                                            d          |j                                                            d          |j        |	j                                                            d          |	j                                                            d          |	j        g}
t.          j        t.          j        t.          j        t.          j        t.          j        t.          j        g}g d}t;          |
|||          D ]\  }}}}|dv r3t          t=          t?          j         |                    |||          }n t          t=          |          |||          }|dk    rd|_!        nF|dk    rd|_!        n8|dk    rd|_!        n*|dk    rd|_!        n|"                    d          rd|_!         j        #                    |           |#                    |           nqd}|$                                D ]Y\  }}||j%        v rIt          t          |dd                   t           j                  z
            dk    r||j%        k    rd|j%         d}t          tM          ||d                   |d          |'                                 d!| |j(        |d                  d"#          }t          tM          ||d                   |d         |'                                 d$| |j(        |d                  d%#          } j        #                    |            j        #                    |           |#                    |           [||vrtS          j*        d&|j%         d'| d( j        |          d)tV                      j        #                    t          |,                                 j        |         *                     |#                    |           t	          |t                    sht          |          }t?          j-        |j.        t?          j.        t^                    j0                  rt          d+ |D                       }| j        |<   |ddd,         D ]} j        1                    |           te           fd-d.D                       rt           j                  D ]s\  }}t	          ||          r^t          |,                                 j        |         *           j        |<   d/| d0 j        |          d)}tg          j4        |          ttk          d16                    tn                              }|8                    d2 9                                d3          }tk          d16                    tt                              }|8                    d4|i          }|#                    |           dS )5z
        Writes the Header of the MRT table, aka ReadMe, which
        also contains the Byte-By-Byte description of the table.
        r   )SkyCoord)GLATGLONbl)ELATELONlatlon)HLATHLONr   r   )HPLTHPLNTyTx)galacticeclipticheliographichelioprojective)RAhRAmRAsr   DEmDEsc                 ,    g | ]}t          |          S r+   rT   r   r   s     r   r   z#MrtHeader.write.<locals>.<listcomp>      !:!:!:s#c((!:!:!:r    ra   i1)zRight Ascension (hour)zRight Ascension (minute)zRight Ascension (second)zDeclination (degree)zDeclination (arcmin)zDeclination (arcsec))r   r   )r~   r   r   r   z013.10fr   z012.9fr   2dr   z+03d)r   r   02dr3   NrK   z ()rL   r   z
 Longitudez.12f)r~   r   r   rV   z	 Latitudez+.12fzCoordinate system of type 'zU' already stored in table as CDS/MRT-syle columns or of unrecognized type. So column z> is being skipped with designation of a string valued column `z`.r}   c                 ,    g | ]}t          |          S r+   r   r   s     r   r   z#MrtHeader.write.<locals>.<listcomp>`  r   r    rz   c              3   *   K   | ]}|j         v V  d S rb   )colnames)r   r   r$   s     r   rd   z"MrtHeader.write.<locals>.<genexpr>h  s*      JJaqDM!JJJJJJr    )r   r   r   r   zGTable already has coordinate system in CDS/MRT-syle columns. So column z@ should have been replaced already with a string valued column `r   z	table.dat)file
bytebybyter   );astropy.coordinatesr   r   r   r   
ValueError	TypeErrorr	   representation_component_nameskeysr   setr   r   hmsdecdmshroundastypemrv   durA   seconddegarcminarcsecr!   listrB   r   rV   rW   r   itemsr~   rS   
capitalizerepresentation_component_unitswarningswarnUserWarningr   r   rp   objectr   popr   r   InconsistentTableErrorr   r#   BYTE_BY_BYTE_TEMPLATE
substituter   MRT_TEMPLATE)r$   linesr   coord_systemseqtnamesto_poprc   rE   ra_cdec_ccoordscoord_unitscoord_descripcoordr~   
coord_unitdescrip	coord_colfrminfoframelatlonlon_collat_colmessagebbb_templatebyte_by_byterm_templatereadme_filleds   `                           r   r   zMrtHeader.write  s~   
 	100000 36:;	
 
 >==   	** F	# F	#FAs c8,, CFH1M1M "(3--CC"I. 	 	 	
 &c622 *$Skk !:!:c!:!:!:;;C#&DIaLH	 #x(( r# C>CCEEEECMMC,>,>>??1DD"%&*cgk%D--d33--d33..t44..t44F $%3qx!("SK% % %M =@+}= = 4 48tZ  >11(. $RVE]] 3 3%)%/,3	) ) )II )/ $U%)%/,3	) ) )I  5==/8I,,!U]]/7I,,!U]]/3I,,!U]]/5I,,!__\:: 5/4I,	((3333MM!$$$$ !G)6)<)<)>)> - -v!SX-- #Crr
OOc$-6H6H$H I IQ N N$00*:sx*:*:*:&, 'VAY 7 7%+AY/4/?/?/A/A,V,VW,V,V%(%Gq	%R'-' ' 'G '- 'VAY 7 7%+AY/4/?/?/A/A,U,UG,U,U%(%Gq	%R'.' ' 'G !I,,W555 I,,W555"MM!,,, F??M@ch @ @#$@ @ ,0=+;@ @ @ $   I$$VCMMOO$-PQBR%S%S%STTTMM!$$$  V,, #Skk=BHV,<,<,ABB < !:!:c!:!:!:;;C"	! " 	 	AIMM! JJJJ+IJJJJJ 	? $DI.. ? ?3c8,, ?#)#--//a@P#Q#Q#QDIaLH%&H H37=3CH H H 
 5g>>>?  		*? @ @AA#.. 0G0G0I0IJJ
 

 tyy6677#..l/KLL]#####s   A""AB=<B=N)	r'   r(   r)   _subfmtr>   rF   r_   r   r   r+   r    r   r-   r-   ?   sr        G(
 (
 (
T
 
 
S= S= S=jw w wry$ y$ y$ y$ y$r    r-   c                        e Zd ZdZdZeZd ZdS )MrtDatazMRT table data reader.r.   c                 ^    d| j         _        t          j                            | |           d S )Nr   )splitterr"   r   FixedWidthDatar   )r$   r  s     r   r   zMrtData.write  s+    "%!''e44444r    N)r'   r(   r)   r*   r&  r   splitter_classr   r+   r    r   r(  r(    s3          G N5 5 5 5 5r    r(  c                   >     e Zd ZdZdZdgZdZdZeZ	e
Zd fd	Z xZS )Mrta  AAS MRT (Machine-Readable Table) format table.

    **Reading**
    ::

      >>> from astropy.io import ascii
      >>> table = ascii.read('data.mrt', format='mrt')

    **Writing**

    Use ``ascii.write(table, 'data.mrt', format='mrt')`` to  write tables to
    Machine Readable Table (MRT) format.

    Note that the metadata of the table, apart from units, column names and
    description, will not be written. These have to be filled in by hand later.

    See also: :ref:`cds_mrt_format`.

    Caveats:

    * The Units and Explanations are available in the column ``unit`` and
      ``description`` attributes, respectively.
    * The other metadata defined by this format is not available in the output table.
    mrtTzMRT format tableNc                     t          |          dk    rt          | j        | j        _        d | j        _        d | j        _        |                                }t                                          |          S )Nr   )	r   NotImplementedErrorheaderr   position_liner   copysuperr   )r$   table	__class__s     r   r   z	Mrt.write  s]    u::??%%;	$(!!% 

ww}}U###r    rb   )r'   r(   r)   r*   _format_name_io_registry_format_aliases_io_registry_can_write_descriptionr(  
data_classr-   header_classr   __classcell__)r7  s   @r   r.  r.    sk         2 L#('!%LJL$ $ $ $ $ $ $ $ $ $r    r.  )&r*   r5   r  ior   mathr   r   stringr   textwrapr   numpyrB   astropyr   r   astropy.tabler	   r
   r   r3   r   r   r   r   r   __doctest_skip__r  r  FixedWidthSplitterr   	CdsHeaderr-   CdsDatar(  
BaseReaderr.  r+   r    r   <module>rK     s    
			                                      5 5 5 5 5 5 5 5 5 5 # # # # # # # # # #   5      ) ) ) ) )*/ ) ) )@	$ @	$ @	$ @	$ @	$ @	$ @	$ @	$F5 5 5 5 5ck 5 5 5.$ .$ .$ .$ .$$/ .$ .$ .$ .$ .$r    