
    HR-eO                     @   d Z ddlZddlZddlZddlmZ ddlZddlm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZmZ d
ZdZdZ G d de          Z G d dej                  Zd Z G d dej                  Z G d dej                  Z G d dej                  Z dS )z
Define the Enhanced Character-Separated-Values (ECSV) which allows for reading and
writing all the meta data associated with an astropy Table object.
    N)OrderedDict)convert_numpy)meta	serialize)serialize_context_as)AstropyUserWarning   )basiccorez1.0) ,)boolint8int16int32int64uint8uint16uint32uint64float16float32float64float128stringc                       e Zd ZdZdS )InvalidEcsvDatatypeWarningz.
    ECSV specific Astropy warning class.
    N)__name__
__module____qualname____doc__     5lib/python3.11/site-packages/astropy/io/ascii/ecsv.pyr   r   )   s           r#   r   c                   :     e Zd ZdZd Zd Zd Zd Z fdZ xZ	S )
EcsvHeaderzHeader class for which the column definition line starts with the
    comment character.  See the :class:`CommentedHeader` class  for an example.
    c              #      K   t          j        | j                  }|D ]U}|                                }|s|                    |          }|r#||                                d         }|r|V  S dS dS )zReturn only non-blank lines that start with the comment regexp.  For these
        lines strip out the matching characters and leading/trailing whitespace.
        N)recompilecommentstripmatchend)selflines
re_commentliner,   outs         r$   process_lineszEcsvHeader.process_lines4   s       Z--
 	 	D::<<D $$T**E 599;;==) III 	 	r#   c                      j         j        t          vrt          d           j        dd} j        r
 j        |d<    j         j        dk    r j         j        |d<   dt           dgt          j        |          z   }|	                     fd	|D                        |
                     j                             d
  j        D                                  dS )ab  
        Write header information in the ECSV ASCII format.

        This function is called at the point when preprocessing has been done to
        convert the input table columns to `self.cols` which is a list of
        `astropy.io.ascii.core.Column` objects. In particular `col.str_vals`
        is available for each column with the string representation of each
        column item for output.

        This format starts with a delimiter separated list of the column names
        in order to make this format readable by humans and simple csv-type
        readers. It then encodes the full table meta and column attributes and
        meta as YAML and pretty-prints this in the header.  Finally the
        delimited column names are repeated again, for humans and readers that
        look for the *last* comment line as defining the column names.
        =only space and comma are allowed for delimiter in ECSV formatzastropy-2.0)colsschemar   r   	delimiterz%ECSV z---c                 $    g | ]}j         |z   S r"   )write_comment).0r1   r.   s     r$   
<listcomp>z$EcsvHeader.write.<locals>.<listcomp>k   s!    NNNDd(4/NNNr#   c                 &    g | ]}|j         j        S r"   )infonamer;   xs     r$   r<   z$EcsvHeader.write.<locals>.<listcomp>l   s    (H(H(H(H(H(Hr#   N)splitterr8   
DELIMITERS
ValueErrorr6   
table_metaECSV_VERSIONr   get_yaml_from_headerextendappendjoin)r.   r/   headerheader_yaml_liness   `   r$   writezEcsvHeader.writeF   s   " ="*44O  
 )}==? 	-!_F6N ="c))"&-"9F; $\##
 %f--.
 	NNNN<MNNNOOOT]''(H(Hdi(H(H(HIIJJJJJr#   c                     dS )z
        WRITE: Override the default write_comments to do nothing since this is handled
        in the custom write method.
        Nr"   r.   r/   r   s      r$   write_commentszEcsvHeader.write_commentsn   	    
 	r#   c                     dS )z
        READ: Override the default update_meta to do nothing.  This process is done
        in get_cols() for this reader.
        Nr"   rO   s      r$   update_metazEcsvHeader.update_metau   rQ   r#   c                     |}t          |                     |                    }d}d}|st          j        |          t	          j        ||d                                         t          j                  }|st          j        |          	 t          j	        |          }n'# t          j
        $ r t          j        d          w xY wd|v r|d         | _        d|v r=|d         }|t          vrt          d          || j        _        || j        j        _        t#          d |d	         D                       }d
 |d	         D             | _        t'          t)                                          |                    }	t'          |                     |	g                    }
|
| j        k    rt          j        d| j         d|
           |                                  | j        D ]#}dD ]3}|||j                 v r"t1          ||||j                 |                    4||j                 d	         |_        |j        t4          vr6d|j        d|j        dt4           d}t7          j        |t:                     |j        }|rId|v rE|                    d          }|d|         |_        tA          j!        ||d                   |_"        dD ]'}tG          ||          dk    rt1          ||d           (|j        dk    rd|_        %dS )z
        READ: Initialize the header Column objects from the table ``lines``.

        Parameters
        ----------
        lines : list
            List of table lines

        z%ECSV [ ]
                             (?P<major> \d+)
                             \. (?P<minor> \d+)
                             \.? (?P<bugfix> \d+)? $zeECSV header line like "# %ECSV <version>" not found as first line.  This is required for a ECSV file.r   z#unable to parse yaml in meta headerr   r8   r5   c              3   *   K   | ]}|d          |fV  dS )r?   Nr"   r@   s     r$   	<genexpr>z&EcsvHeader.get_cols.<locals>.<genexpr>   s*      !M!MQ1V9a.!M!M!M!M!M!Mr#   datatypec                     g | ]
}|d          S )r?   r"   r@   s     r$   r<   z'EcsvHeader.get_cols.<locals>.<listcomp>   s    <<<Aai<<<r#   zcolumn names from ECSV header z1 do not match names from header line of CSV data )descriptionformatunitr   subtypezunexpected datatype z of column z" is not in allowed ECSV datatypes zQ. Using anyway as a numpy dtype but beware since unexpected results are possible.category[N)dtyper\   r   strjsonobject)$listr3   r   InconsistentTableErrorr(   r,   r+   VERBOSEr   get_header_from_yamlYamlParseErrorrE   rC   rD   rB   r8   datar   namesnextsuper_set_cols_from_namesr6   r?   setattrr`   ECSV_DATATYPESwarningswarnr   r\   indexrb   loadsshapegetattr)r.   r/   	raw_linesecsv_header_reno_header_msgr,   rK   r8   header_colsheader_lineheader_namescolattrmsgr\   idx	__class__s                   r$   get_colszEcsvHeader.get_cols|   s    	 T''..//82 	
  	=-m<<<q)9)92:FF 	=-m<<<	U.u55FF" 	U 	U 	U-.STTT	U V$VnDO&  {+I
** S   '0DM#+4DI( "!M!M&:L!M!M!MMM<<
);<<<
 57700;;<<DMM;-8899 4:%%-K K K<HK K   	!!### 9 !	' !	'CL D D;sx000C{38'<T'BCCC#CH-j9CI y..,39 , ,38 , ,8F, , ,  c,FGGGG kG 63'>>mmC((%dsdm Jwstt}55	 - . .3%%11Cu--- {f$$&C!	' !	's   B$ $$C)
r   r   r    r!   r3   rM   rP   rS   r   __classcell__r   s   @r$   r&   r&   /   s           $&K &K &KP    j' j' j' j' j' j' j' j' j'r#   r&   c                 L    | j         dk    rt          d| j        d          d S )Nra   zdatatype of column z must be "string")r`   rD   r?   )r|   s    r$   _check_dtype_is_strr      s3    
yELsxLLLMMM r#   c                   ,     e Zd ZdZg Z fdZd Z xZS )EcsvOutputtera  
    After reading the input lines and processing, convert the Reader columns
    and metadata to an astropy.table.Table object.  This overrides the default
    converters to be an empty list because there is no "guessing" of the
    conversion function.
    c                 t    t                                          ||          }t          j        |          }|S N)rl   __call__r   _construct_mixins_from_columns)r.   r6   r   r2   r   s       r$   r   zEcsvOutputter.__call__   s3    ggtT** 6s;;
r#   c           
      8	   |D ]}	 |j         dk    rbt          |           d |j        D             }t          j        t          |          g|j        z   t                    |_        ||j        d<   n|j        r|j        d         t          |           t          |d          r,t          j
        |j                  d         D ]}d	|j        |<   g }|j        D ]}t          j        |          }	 t          j        ||j                   }n# t          $ r t          j        |t                    }|dk    }	t          j        |j                   j        }
d
dd                    |
d          ||	<   t          j                            |                    |j                   |	          }Y nw xY w|                    |           d|_        t          j        t                    |_        t          j        t          |          t                    |_        ||j        dd<   n|j        rst          |           t          |d          rut          j        |j        dt                    }t          j        |                                          }t          j
        |j                  d         D ]}||j        |<   |`d |j        D             }t          j        |t                    }|dk    }	t          j        |	          s |                    |j                   |_        nt          j        |j                   j        }
d
dd                    |
d          ||	<   t          j                            |                    |j                   |	          |_        ng|j         r4t5          j        d|j         d|j        d|j        dt:                     t=          |j                  \  }} ||j                  |_        |j        j        dd         t?          |j                  k    rtA          d          E# t          j!        $ r tA          d|j        d          tD          $ r}tA          d|j        d|           d}~ww xY wdS )a  READ: Convert str_vals in `cols` to final arrays with correct dtypes.

        This is adapted from ``BaseOutputter._convert_vals``. In the case of ECSV
        there is no guessing and all types are known in advance. A big change
        is handling the possibility of JSON-encoded values, both unstructured
        object data and structured values that may contain masked data.
        rc   c                 6    g | ]}t          j        |          S r"   rb   rs   r;   vals     r$   r<   z/EcsvOutputter._convert_vals.<locals>.<listcomp>       HHHC
3HHHr#   )r`   .Nmaskr   z[] r#   )US)r   r"   )rt   
fill_valuer`   c                 6    g | ]}t          j        |          S r"   r   r   s     r$   r<   z/EcsvOutputter._convert_vals.<locals>.<listcomp>P  r   r#   zunexpected subtype z set for column z, using dtype=z	 instead.r]   r	   z1shape mismatch between value and column specifierzcolumn z2 failed to convert: column value is not valid JSONz failed to convert: )#r\   r   str_valsnpemptylenrt   rc   ri   hasattrnonzeror   rb   rs   array	TypeErrorr`   kindgetmaastyperI   fulldumpstolistanyrp   rq   r?   r   r   tuplerD   JSONDecodeError	Exception)r.   r6   r|   col_valsr   str_valobj_valarr_valri   r   r   all_none_arrall_none_jsonconverter_func_excs                   r$   _convert_valszEcsvOutputter._convert_vals  s     h	R h	RCgR;(**',,,HH3<HHHH!xX#)(C6RRRCH$,CHSMM
 Y O<39R=#8',,,
 sF++ 5#%:ch#7#7#: 5 5C04CL--  "H#&< 1 1"&*W"5"5W&(hwck&J&J&JGG( 	W 	W 	W $&8G6#B#B#BD#'4<D#%8CK#8#8#=D/1)<)<)@)@q)I)IDJ&(ekk$++ck2J2JQUk&V&VGGG	W !0000 "CI " 0 0CI!xHVDDDCH"*CHQQQKK Y )<',,, sF++ %')w"%)F( ( ( )-
<3F3F3H3H(I(I#%:ch#7#7#: > >C0=CL--HHH3<HHHH 8HF;;;D4<D6$<< T#';;s{#;#;  "x449+-C%8%8%<%<T1%E%ET
#%5;;t{{3;/G/Gd;#S#S {  P#+ P P"xP P9<P P P%?   
 )6ci(@(@%NA-~cl;;CH8>!""%sy)9)999$K   :
 '    5ch 5 5 5    R R R !P38!P!P3!P!PQQQROh	R h	Rs>   C-Q5DQBF2/Q1F22JQ0R8RR)r   r   r    r!   default_convertersr   r   r   r   s   @r$   r   r      sg              pR pR pR pR pR pR pRr#   r   c                   $     e Zd Z fdZd Z xZS )EcsvDatac                    t                                          |           	 | j        j        d         }n# t          t
          f$ r Y dS w xY w|D ]4}|j        dk    r'|j        |v r||j                 d         dk    ri |_        5dS )a9  READ: Set the fill values of the individual cols based on fill_values of BaseData.

        For ECSV handle the corner case of data that has been serialized using
        the serialize_method='data_mask' option, which writes the full data and
        mask directly, AND where that table includes a string column with zero-length
        string entries ("") which are valid data.

        Normally the super() method will set col.fill_value=('', '0') to replace
        blanks with a '0'.  But for that corner case subset, instead do not do
        any filling.
        __serialized_columns__Nra   r   z!astropy.table.column.MaskedColumn)	rl   _set_fill_valuesrK   rE   AttributeErrorKeyErrorr`   r?   fill_values)r.   r6   scsr|   r   s       r$   r   zEcsvData._set_fill_valuesy  s     	  &&&	+()ABCC) 	 	 	FF	  	% 	%C	U""HOOM+.2UUU"$	% 	%s   7 AAc                     | j         D ]t          j                  dk    sj        j        j        dk    rfdnfd	 fdt          t                              D             _        n2# t          $ r%}t          dj        j	        d|           |d}~ww xY wt          d	          r7j        dk    r,j                                        d
         D ]}dj        |<   d | j         D             }|S )a  WRITE: convert all values in table to a list of lists of strings.

        This version considerably simplifies the base method:
        - No need to set fill values and column formats
        - No per-item formatting, just use repr()
        - Use JSON for object-type or multidim values
        - Only Column or MaskedColumn can end up as cols here.
        - Only replace masked values with "", not the generalized filling
        r	   Oc                     |          }	 |                                 }n# t          $ r Y nw xY wt          j        |d          S )N)r   :)
separators)r   r   rb   r   )r   objr|   s     r$   format_col_itemz*EcsvData.str_vals.<locals>.format_col_item  sU    c(C!jjll)   :cjAAAAs     
--c                 .    t          |                    S r   )ra   )r   r|   s    r$   r   z*EcsvData.str_vals.<locals>.format_col_item  s    s3x==(r#   c                 &    g | ]} |          S r"   r"   )r;   r   r   s     r$   r<   z%EcsvData.str_vals.<locals>.<listcomp>  s#    PPP 4 4PPPr#   zcould not convert column z to string: Nr   r   r   c                     g | ]	}|j         
S r"   )r   )r;   r|   s     r$   r<   z%EcsvData.str_vals.<locals>.<listcomp>  s    111s|111r#   )r6   r   rt   r>   r`   r   ranger   r   r?   r   ndimr   r   )r.   r   r   r2   r|   r   s       @@r$   r   zEcsvData.str_vals  s[    9 	+ 	+C39~~!!SX^%8C%?%?B B B B B B) ) ) ) )PPPPc#hhPPP   RRRSRR  sF## +A8++--a0 + +C(*CL%%11ty111
s   -A33
B"= BB")r   r   r    r   r   r   r   s   @r$   r   r   x  sH        % % % % %@( ( ( ( ( ( (r#   r   c                   4    e Zd ZdZdZdZdZeZe	Z
eZdZd ZdS )Ecsva  ECSV (Enhanced Character Separated Values) format table.

    Th ECSV format allows for specification of key table and column meta-data, in
    particular the data type and unit.

    See: https://github.com/astropy/astropy-APEs/blob/main/APE6.rst

    Examples
    --------
    >>> from astropy.table import Table
    >>> ecsv_content = '''# %ECSV 0.9
    ... # ---
    ... # datatype:
    ... # - {name: a, unit: m / s, datatype: int64, format: '%03d'}
    ... # - {name: b, unit: km, datatype: int64, description: This is column b}
    ... a b
    ... 001 2
    ... 004 3
    ... '''

    >>> Table.read(ecsv_content, format='ascii.ecsv')
    <Table length=2>
      a     b
    m / s   km
    int64 int64
    ----- -----
      001     2
      004     3

    ecsvzEnhanced CSVz.ecsvNc                 |    t          d          5  t          j        |          }ddd           n# 1 swxY w Y   |S )a  
        Update table columns in place if mixin columns are present.

        This is a hook to allow updating the table columns after name
        filtering but before setting up to write the data.  This is currently
        only used by ECSV and is otherwise just a pass-through.

        Parameters
        ----------
        table : `astropy.table.Table`
            Input table for writing

        Returns
        -------
        table : `astropy.table.Table`
            Output table for writing
        r   N)r   r   represent_mixins_as_columns)r.   tabler2   s      r$   update_table_datazEcsv.update_table_data  s|    $ "&)) 	? 	?7>>C	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	? 	?
s   155)r   r   r    r!   _format_name_description_io_registry_suffixr&   header_classr   
data_classr   outputter_classmax_ndimr   r"   r#   r$   r   r     sS         > L!L!LJ#OH    r#   r   )!r!   rb   r(   rp   collectionsr   numpyr   astropy.io.ascii.corer   astropy.tabler   r   astropy.utils.data_infor   astropy.utils.exceptionsr   r   r
   r   rF   rC   ro   r   BasicHeaderr&   r   TableOutputterr   	BasicDatar   Basicr   r"   r#   r$   <module>r      s   
  				  # # # # # #     / / / / / / ) ) ) ) ) ) ) ) 8 8 8 8 8 8 7 7 7 7 7 7        
$    !3   w' w' w' w' w'" w' w' w'tN N N
GR GR GR GR GRD' GR GR GRTI I I I Iu I I IX> > > > >5; > > > > >r#   