Exemple #1
0
def array_to_table(arrs, fmt_str, use_astropy=False):
    r"""Serialize an array as an ASCII table.

    Args:
        arrs (np.ndarray, list, tuple): Structured array or list/tuple of
            arrays that contain table information.
        fmt_str (str, bytes): Format string that should be used to structure
            the ASCII array.
        use_astropy (bool, optional): If True, astropy will be used to format
            the table if it is installed. Defaults to False.

    Returns:
        bytes: ASCII table.

    """
    if not _use_astropy:
        use_astropy = False
    dtype = cformat2nptype(fmt_str)
    if len(dtype) == 0:
        dtype = np.dtype([('f0', dtype)])
    info = format2table(fmt_str)
    comment = info.get('comment', None)
    if comment is not None:
        fmt_str = fmt_str.split(comment, 1)[-1]
    arr1 = consolidate_array(arrs, dtype=dtype)
    if use_astropy:
        fd = sio.StringIO()
        table = apy_Table(arr1)
        delimiter = tools.bytes2str(info['delimiter'])
        apy_ascii.write(table, fd, delimiter=delimiter,
                        format='no_header')
        out = tools.str2bytes(fd.getvalue())
    else:
        fd = sio.BytesIO()
        fmt_str = tools.str2bytes(fmt_str)
        for ele in arr1:
            line = format_message(ele.tolist(), fmt_str)
            fd.write(line)
        # fmt = fmt_str.split(info['newline'])[0]
        # np.savetxt(fd, arr1,
        #            fmt=fmt, delimiter=info['delimiter'],
        #            newline=info['newline'], header='')
        out = fd.getvalue()
    fd.close()
    return out
def array_to_table(arrs, fmt_str, use_astropy=False):
    r"""Serialize an array as an ASCII table.

    Args:
        arrs (np.ndarray, list, tuple): Structured array or list/tuple of
            arrays that contain table information.
        fmt_str (str, bytes): Format string that should be used to structure
            the ASCII array.
        use_astropy (bool, optional): If True, astropy will be used to format
            the table if it is installed. Defaults to False.

    Returns:
        bytes: ASCII table.

    """
    if not _use_astropy:
        use_astropy = False
    dtype = cformat2nptype(fmt_str)
    info = format2table(fmt_str)
    arr1 = consolidate_array(arrs, dtype=dtype)
    fd = backwards.BytesIO()
    if use_astropy:
        table = apy_Table(arr1)
        apy_ascii.write(table, fd, delimiter=info['delimiter'],
                        format='no_header')
    else:
        for ele in arr1:
            line = format_message(ele.tolist(), fmt_str)
            fd.write(line)
        # fmt = fmt_str.split(info['newline'])[0]
        # np.savetxt(fd, arr1,
        #            fmt=fmt, delimiter=info['delimiter'],
        #            newline=info['newline'], header='')
    out = fd.getvalue()
    fd.close()
    return out
    def write_array(self, array, names=None, skip_header=False):
        r"""Write a numpy array to the table.

        Args:
            array (np.ndarray): Array to be written.
            names (list, optional): List of column names to write out. If
                not provided, existing names are used if they exist. Defaults
                to None.
            skip_header (bool, optional): If True, no header information is
                written (it is assumed it was already written. Defaults to
                False.

        Raises:
            ValueError: If names are provided, but not the same number as
                there are columns.

        """
        fmt = backwards.bytes2unicode(self.format_str.split(self.newline)[0])
        column = backwards.bytes2unicode(self.column)
        comment = backwards.bytes2unicode(self.comment) + ' '
        newline = backwards.bytes2unicode(self.newline)
        open_mode = self.open_mode
        openned = False
        fd = self.fd
        if not self.is_open:
            fd = open(self.filepath, open_mode)
            openned = True
        if skip_header:
            names = None
        else:
            if names is None:
                names = self.column_names
            if (names is not None) and (len(names) != self.ncols):
                raise ValueError("The number of names does not match " +
                                 "the number of columns")
        if self.use_astropy:
            table = apy_Table(array)
            if skip_header:
                table_format = 'no_header'
            else:
                table_format = 'commented_header'
                table.meta["comments"] = [fmt]
            apy_ascii.write(table,
                            fd,
                            delimiter=column,
                            comment=comment,
                            format=table_format,
                            names=names)
        else:
            if skip_header:
                head = ''
            else:
                head = fmt
                if names is not None:
                    head = column.join(names) + newline + " " + head
            # Write directly to file, savetxt writes bytes as "b'body'"
            if len(head) > 0:
                head = head.replace(newline, newline + comment)
                fd.write(asbytes(comment + head + newline))
            for row in array:
                row2 = []
                for x in row:
                    if np.iscomplexobj(x):
                        row2.append(x.real)
                        row2.append(x.imag)
                    else:
                        row2.append(x)
                line = backwards.format_bytes(asbytes(fmt), tuple(row2))
                fd.write(line + asbytes(newline))
            # np.savetxt(fd, array,
            #            fmt=fmt, delimiter=column, comments=comment,
            #            newline=newline, header=head)
        if openned:
            fd.close()
            fd = None