__________________________ TestMisc.test_struct_print __________________________
self = <pydl.pydlutils.tests.test_misc.TestMisc object at 0x7fd44c6c0390>
def test_struct_print(self):
slist = np.zeros((5,), dtype=[('a', 'c16'), ('b', np.bool)])
with raises(PydlutilsException):
lines, css = struct_print(slist, silent=True)
slist = np.array([(1, 2.34, 'five'),
(2, 3.456, 'seven'),
(3, -4.5678, 'nine')],
dtype=[('a', 'i4'), ('bb', 'f4'), ('ccc', 'S5')])
lines, css = struct_print(slist, silent=True)
assert lines[0] == 'a bb ccc '
assert lines[1] == '- ------------ -----'
assert lines[2] == '1 2.34 five '
assert lines[3] == '2 3.456 seven'
assert lines[4] == '3 -4.5678 nine '
assert len(css) == 0
lines, css = struct_print(slist, silent=True, alias={'ccc': 'c'})
assert lines[0] == 'a bb c '
assert lines[1] == '- ------------ -----'
assert lines[2] == '1 2.34 five '
assert lines[3] == '2 3.456 seven'
assert lines[4] == '3 -4.5678 nine '
assert len(css) == 0
lines, css = struct_print(slist, silent=True,
formatcodes={'a': '{0:02d}'})
assert lines[0] == 'a bb ccc '
assert lines[1] == '-- ------------ -----'
assert lines[2] == '01 2.34 five '
assert lines[3] == '02 3.456 seven'
assert lines[4] == '03 -4.5678 nine '
assert len(css) == 0
lines, css = struct_print(slist, silent=True, fdigit=3)
assert lines[0] == 'a bb ccc '
assert lines[1] == '- ---------- -----'
assert lines[2] == '1 2.34 five '
assert lines[3] == '2 3.46 seven'
assert lines[4] == '3 -4.57 nine '
assert len(css) == 0
lines, css = struct_print(slist, silent=True, html=True)
assert lines[0] == '<table>'
assert lines[1] == '<tr><th>a</th><th>bb</th><th>ccc</th></tr>'
assert lines[2] == '<tr><td>1</td><td> 2.34</td><td>five </td></tr>'
assert lines[3] == '<tr><td>2</td><td> 3.456</td><td>seven</td></tr>'
assert lines[4] == '<tr><td>3</td><td> -4.5678</td><td>nine </td></tr>'
assert lines[5] == '</table>'
assert css[0] == '<style type="text/css">'
assert css[1] == 'table {'
assert css[2] == ' border-collapse: collapse;'
assert css[3] == '}'
assert css[4] == 'th {'
assert css[5] == ' padding: 2px;'
assert css[6] == ' text-align: right;'
assert css[7] == ' border: 1px solid black;'
assert css[8] == ' font-weight: bold;'
assert css[9] == '}'
assert css[10] == 'td {'
assert css[11] == ' padding: 2px;'
assert css[12] == ' text-align: right;'
assert css[13] == ' border: 1px solid black;'
assert css[14] == '}'
assert css[15] == '</style>'
slist = np.array([(1, 2.34, 'five'),
(2, 3.456, 'seven'),
(3, -4.5678, 'nine')],
dtype=[('a', 'i4'), ('bb', 'f8'), ('ccc', 'S5')])
lines, css = struct_print(slist, silent=True, ddigit=3)
assert lines[0] == 'a bb ccc '
assert lines[1] == '- ---------- -----'
assert lines[2] == '1 2.34 five '
assert lines[3] == '2 3.46 seven'
assert lines[4] == '3 -4.57 nine '
assert len(css) == 0
lines, css = struct_print(slist, silent=True,
> filename=self.struct_print_file)
/usr/lib/python2.7/dist-packages/pydl/pydlutils/tests/test_misc.py:188:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
array = array([(1, 2.34, 'five'), (2, 3.456, 'seven'), (3, -4.5678, 'nine')],
dtype=[('a', '<i4'), ('bb', '<f8'), ('ccc', 'S5')])
filename = '/usr/lib/python2.7/dist-packages/pydl/pydlutils/tests/t/struct_print.txt'
formatcodes = {'a': '{0:1d}', 'bb': '{1:14.7g}', 'ccc': '{2:5s}'}
alias = {'a': 'a', 'bb': 'bb', 'ccc': 'ccc'}, fdigit = 5, ddigit = 7
html = False, no_head = False, silent = True
def struct_print(array, filename=None, formatcodes=None, alias=None,
fdigit=5, ddigit=7, html=False, no_head=False,
silent=False):
"""Print a NumPy record array (analogous to an IDL structure) in a
nice way.
Parameters
----------
array : :class:`numpy.ndarray`
A record array to print.
filename : :class:`str` or file-like, optional
If supplied, write to this file.
formatcodes : :class:`dict`, optional
If supplied, use explicit format for certain columns.
alias : :class:`dict`, optional
If supplied, use this mapping of record array column names to printed
column names.
fdigit : :class:`int`, optional
Width of 32-bit floating point columns, default 5.
ddigit : :class:`int`, optional
Width of 64-bit floating point columns, default 7.
html : :class:`bool`, optional
If ``True``, print an html table.
no_head : :class:`bool`, optional
If ``True``, *don't* print a header line.
silent : :class:`bool`, optional
If ``True``, do not print the table, just return it.
Returns
-------
:func:`tuple`
A tuple containing a list of the lines in the table. If `html` is
``True``, also returns a list of lines of CSS for formatting the
table.
Examples
--------
>>> import numpy as np
>>> from pydl.pydlutils.misc import struct_print
>>> struct_print(np.array([(1,2.34,'five'),(2,3.456,'seven'),(3,4.5678,'nine')],dtype=[('a','i4'),('bb','f4'),('ccc','S5')]),silent=True)
(['a bb ccc ', '- ----------- -----', '1 2.34 five ', '2 3.456 seven', '3 4.5678 nine '], [])
"""
if html:
headstart = '<tr><th>'
headsep = '</th><th>'
headend = '</th></tr>'
colstart = '<tr><td>'
colsep = '</td><td>'
colend = '</td></tr>'
css = ['<style type="text/css">',
'table {',
' border-collapse: collapse;',
'}',
'th {',
' padding: 2px;',
' text-align: right;',
' border: 1px solid black;',
' font-weight: bold;',
'}',
'td {',
' padding: 2px;',
' text-align: right;',
' border: 1px solid black;',
'}',
'</style>']
else:
headstart = ''
headsep = ' '
headend = ''
colstart = ''
colsep = ' '
colend = ''
css = list()
#
# Alias should be a dictionary that maps structure names to column names
#
if alias is None:
#
# Create a dummy alias dictionary
#
alias = dict(list(zip(array.dtype.names, array.dtype.names)))
else:
#
# Fill in any missing values of the alias dictionary
#
for tag in array.dtype.names:
if tag not in alias:
alias[tag] = tag
#
# Formatcodes allows an override for certain columns.
#
if formatcodes is None:
formatcodes = dict()
#
# This dictionary will hold the number of characters in each column
#
nchar = dict()
#
# Construct format codes for each column
#
for k, tag in enumerate(array.dtype.names):
if tag in formatcodes:
thiscode = formatcodes[tag]
thisn = len(thiscode.format(array[tag][0]))
else:
d = array.dtype.fields[tag][0]
if d.kind == 'i' or d.kind == 'u':
thisn = max(max(len(str(array[tag].min())),
len(str(array[tag].max()))), len(tag))
thiscode = "{{{0:d}:{1:d}d}}".format(k, thisn)
elif d.kind == 'f':
if d.itemsize == 8:
prec = ddigit
else:
prec = fdigit
thisn = prec + 6
if array[tag].min() < 0:
thisn += 1
thiscode = "{{{0:d}:{1:d}.{2:d}g}}".format(k, thisn, prec)
elif d.kind == 'S' or d.kind == 'U':
thisn = max(d.itemsize, len(tag))
thiscode = "{{{0:d}:{1:d}s}}".format(k, thisn)
else:
raise PydlutilsException(
"Unsupported kind: {0}".format(d.kind))
formatcodes[tag] = thiscode
nchar[tag] = thisn
#
# Start building an array of lines
#
lines = list()
#
# Construct header lines
#
if html:
lines.append('<table>')
hdr1 = (headstart + headsep.join([alias[tag]
for tag in array.dtype.names]) + headend)
lines.append(hdr1)
else:
if not no_head:
hdr1 = (headstart + headsep.join([("{{0:{0:d}s}}".format(
nchar[tag])).format(alias[tag])
for tag in array.dtype.names]) + headend)
hdr2 = (headstart + headsep.join(['-' * nchar[tag]
for tag in array.dtype.names]) + headend)
lines.append(hdr1)
lines.append(hdr2)
#
# Create a format string for the data from the individual format codes
#
rowformat = (colstart + colsep.join([formatcodes[tag]
for tag in array.dtype.names]) + colend)
for k in range(array.size):
lines.append(rowformat.format(
*([decode_mixed(l) for l in array[k].tolist()])))
if html:
lines.append('</table>')
f = None # This variable will store a file handle
close_file = False
if filename is not None:
if hasattr(filename, 'write'):
f = filename
else:
> f = open(filename, 'w')
E IOError: [Errno 13] Permission denied: '/usr/lib/python2.7/dist-packages/pydl/pydlutils/tests/t/struct_print.txt'
/usr/lib/python2.7/dist-packages/pydl/pydlutils/misc.py:390: IOError
_______________________ TestYanny.test_write_table_yanny _______________________
self = <pydl.pydlutils.tests.test_yanny.TestYanny object at 0x7fd44c6aed10>
def test_write_table_yanny(self):
"""Test writing an astropy Table to yanny.
"""
filename = self.data('table.par')
a = [1, 4, 5]
b = [2.0, 5.0, 8.2]
c = [b'x', b'y', b'z']
t = Table([a, b, c], names=('a', 'b', 'c'),
meta={'name': 'first table'})
> t.write(filename, tablename='test')
/usr/lib/python2.7/dist-packages/pydl/pydlutils/tests/test_yanny.py:126:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python2.7/dist-packages/astropy/table/table.py:2349: in write
io_registry.write(self, *args, **kwargs)
/usr/lib/python2.7/dist-packages/astropy/io/registry.py:403: in write
writer(data, *args, **kwargs)
/usr/lib/python2.7/dist-packages/pydl/pydlutils/yanny.py:1339: in write_table_yanny
hdr=hdr, comments='Table')
/usr/lib/python2.7/dist-packages/pydl/pydlutils/yanny.py:1231: in write_ndarray_to_yanny
par.write(filename, comments=comments)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self =
newfile = '/usr/lib/python2.7/dist-packages/pydl/pydlutils/tests/t/table.par'
comments = '# Table\n'
def write(self, newfile=None, comments=None):
"""Write a yanny object to a file.
This assumes that the filename used to create the object was not that
of a pre-existing file. If a file of the same name is detected,
this method will *not* attempt to overwrite it, but will print a warning.
This also assumes that the special 'symbols' key has been properly
created. This will not necessarily make the file very human-readable,
especially if the data lines are long. If the name of a new file is
given, it will write to the new file (assuming it doesn't exist).
If the writing is successful, the data in the object will be updated.
Parameters
----------
newfile : :class:`str`, optional
The name of the file to write.
comments : :class:`str` or :class:`list` of :class:`str`, optional
Comments that will be placed at the head of the file. If a
single string is passed, it will be written out verbatim, although
a '#' character will be added if it does not already have one.
If a list of strings is passed, comment characters will be added
and the strings will be joined together.
"""
if newfile is None:
if len(self.filename) > 0:
newfile = self.filename
else:
raise ValueError("No filename specified!")
if os.access(newfile, os.F_OK):
raise PydlutilsException(
"{0} exists, aborting write!".format(newfile))
if comments is None:
basefile = os.path.basename(newfile)
timestamp = datetime.datetime.utcnow().strftime(
'%Y-%m-%d %H:%M:%S UTC')
comments = "#\n# {0}\n#\n# Created by pydl.pydlutils.yanny.yanny\n#\n# {1}\n#\n".format(basefile, timestamp)
else:
if isinstance(comments, six.string_types):
if not comments.startswith('#'):
comments = '# ' + comments
if not comments.endswith('\n'):
comments += '\n'
else:
comments = ("\n".join(["# {0}".format(c) for c in comments]) +
"\n")
contents = "#%yanny\n" + comments
#
# Print any key/value pairs
#
for key in self.pairs():
contents += "{0} {1}\n".format(key, self[key])
#
# Print out enum definitions
#
if len(self._symbols['enum']) > 0:
contents += "\n" + "\n\n".join(self._symbols['enum']) + "\n"
#
# Print out structure definitions
#
if len(self._symbols['struct']) > 0:
contents += "\n" + "\n\n".join(self._symbols['struct']) + "\n"
contents += "\n"
#
# Print out the data tables
#
for sym in self.tables():
columns = self.columns(sym)
for k in range(self.size(sym)):
line = list()
line.append(sym)
for col in columns:
if self.isarray(sym, col):
datum = ('{' + ' '.join([self.protect(x)
for x in self[sym][col][k]]) + '}')
else:
datum = self.protect(self[sym][col][k])
line.append(datum)
contents += "{0}\n".format(' '.join(line))
#
# Actually write the data to file
#
> with open(newfile, 'w') as f:
E IOError: [Errno 13] Permission denied: '/usr/lib/python2.7/dist-packages/pydl/pydlutils/tests/t/table.par'
/usr/lib/python2.7/dist-packages/pydl/pydlutils/yanny.py:926: IOError