def func_serialize(self, args): r"""Serialize a message. Args: args: List of arguments to be formatted or numpy array to be serialized. Returns: bytes, str: Serialized message. """ if self.format_str is None: # if self.as_array: # dtype = args.dtype # else: # dtype = np.dtype(names=self.field_names, # formats=[type(x) for x in args]) # self.format_str = serialize.table2format(dtype) raise RuntimeError("Format string is not defined.") if self.as_array: out = serialize.array_to_table(args, self.format_str, use_astropy=self.use_astropy) out = backwards.unicode2bytes(out) else: out = super(AsciiTableSerialize, self).func_serialize(args) return out
def test_array_to_table(): r"""Test conversion of arrays to ASCII table and back.""" flist = [backwards.unicode2bytes("%5s\t%ld\t%lf\t%g%+gj\n")] for use_astropy in [False, True]: for f in flist: dtype = serialize.cformat2nptype(f) arr0 = np.ones(5, dtype) arr0['f0'][0] = backwards.unicode2bytes('hello') tab = serialize.array_to_table(arr0, f, use_astropy=use_astropy) arr1 = serialize.table_to_array(tab, f, use_astropy=use_astropy) np.testing.assert_array_equal(arr1, arr0)
def write_table(self, fname): r"""Write the table out to a file. Args: fname (str): Full path to the file that the table should be written to. """ header = serialize.format_header(format_str=self.fmt_str, comment=self.comment, delimiter=self.delimiter, newline=self.newline, field_names=self.field_names, field_units=self.field_units) body = serialize.array_to_table(self.file_array, self.fmt_str) with open(fname, 'wb') as fd: fd.write(header) fd.write(body)
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. """ openned = False fd = self.fd if not self.is_open: fd = open(self.filepath, self.open_mode) openned = True # Write header if not skip_header: if names is None: names = self.column_names header = serialize.format_header(format_str=self.format_str, comment=self.comment, delimiter=self.column, newline=self.newline, field_names=names) fd.write(header) # Write array fd.write( serialize.array_to_table(array, self.format_str, use_astropy=self.use_astropy)) if openned: fd.close() fd = None