Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add info method to dataset #1176

Merged
merged 6 commits into from
Dec 23, 2016
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ Dataset methods
Dataset.load
Dataset.chunk
Dataset.filter_by_attrs
Dataset.info

DataArray methods
-----------------
Expand Down
4 changes: 4 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ Enhancements
plots (:issue:`897`). See :ref:`plotting.figsize` for more details.
By `Stephan Hoyer <https://github.com/shoyer>`_ and
`Fabien Maussion <https://github.com/fmaussion>`_.
- New :py:meth:`~Dataset.info` method to summarize ``Dataset`` variables
and attributes. The method prints to a buffer (e.g. ``stdout``) with output
similar to what the command line utility ``ncdump -h`` produces (:issue:`1150`).
By `Joe Hamman <https://github.com/jhamman>`_.

Bug fixes
~~~~~~~~~
Expand Down
38 changes: 38 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from collections import Mapping
from numbers import Number

import sys

import numpy as np
import pandas as pd

Expand Down Expand Up @@ -802,6 +804,42 @@ def to_netcdf(self, path=None, mode='w', format=None, group=None,
def __unicode__(self):
return formatting.dataset_repr(self)

def info(self, buf=None):
"""
Concise summary of a Dataset variables and attributes.
Parameters
----------
buf : writable buffer, defaults to sys.stdout

See Also
--------
pandas.DataFrame.assign
netCDF's ncdump
"""

if buf is None: # pragma: no cover
buf = sys.stdout

lines = []
lines.append('xarray.Dataset {')
lines.append('dimensions:')
for name, size in self.dims.items():
lines.append('\t{name} = {size} ;'.format(name=name, size=size))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these probably should all be unicode (using u literals), otherwise this will break for non-ASCII characters on Python 2. Take a look at what things look like in formatting.py.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would also be good to add a test for attributes with non-ASCII values.

lines.append('\nvariables:')
for name, da in self.variables.items():
dims = ', '.join(da.dims)
lines.append('\t{type} {name}({dims}) ;'.format(
type=da.dtype, name=name, dims=dims))
for k, v in da.attrs.items():
lines.append('\t\t{name}:{k} = {v} ;'.format(name=name, k=k,
v=v))
lines.append('\n// global attributes:')
for k, v in self.attrs.items():
lines.append('\t:{k} = {v} ;'.format(k=k, v=v))
lines.append('}')

formatting._put_lines(buf, lines)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would probably just use buf.write(u'\n'.join(lines)) here, which will work as long as you ensure all elements in lines are the same (unicode/str) type.


@property
def chunks(self):
"""Block dimensions for this dataset's data or None if it's not a dask
Expand Down
12 changes: 11 additions & 1 deletion xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from .options import OPTIONS
from .pycompat import (
PY2, unicode_type, bytes_type, dask_array_type, OrderedDict)
PY2, unicode_type, bytes_type, dask_array_type, OrderedDict, basestring)


def pretty_print(x, numchars):
Expand Down Expand Up @@ -361,6 +361,16 @@ def array_repr(arr):
return u'\n'.join(summary)


def _put_lines(buf, lines):
'''see also from pandas.formats.format import _put_lines'''
if any(isinstance(x, basestring) for x in lines):
if PY2:
lines = [unicode(x) for x in lines]
else:
lines = [basestring(x) for x in lines]
buf.write('\n'.join(lines))


def dataset_repr(ds):
summary = [u'<xarray.%s>' % type(ds).__name__]

Expand Down
37 changes: 37 additions & 0 deletions xarray/test/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
import dask.array as da
except ImportError:
pass
try:
from io import StringIO
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we might put this in in pycompat instead

except ImportError:
from cStringIO import StringIO

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -190,6 +194,39 @@ def test_unicode_data(self):
actual = unicode_type(data)
self.assertEqual(expected, actual)

def test_info(self):
ds = create_test_data(seed=123)
ds = ds.drop('dim3') # string type prints differently in PY2 vs PY3
ds.attrs['foo'] = 'bar'
buf = StringIO()
ds.info(buf=buf)

expected = dedent(u'''\
xarray.Dataset {
dimensions:
dim1 = 8 ;
dim2 = 9 ;
dim3 = 10 ;
time = 20 ;

variables:
datetime64[ns] time(time) ;
float64 dim2(dim2) ;
float64 var1(dim1, dim2) ;
var1:foo = variable ;
float64 var2(dim1, dim2) ;
var2:foo = variable ;
float64 var3(dim3, dim1) ;
var3:foo = variable ;
int64 numbers(dim3) ;

// global attributes:
:foo = bar ;
}''')
actual = buf.getvalue()
self.assertEqual(expected, actual)
buf.close()

def test_constructor(self):
x1 = ('x', 2 * np.arange(100))
x2 = ('x', np.arange(1000))
Expand Down
3 changes: 1 addition & 2 deletions xarray/test/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ def test_format_items(self):
actual = ' '.join(formatting.format_items(item))
self.assertEqual(expected, actual)


def test_format_array_flat(self):
actual = formatting.format_array_flat(np.arange(100), 13)
expected = '0 1 2 3 4 ...'
Expand Down Expand Up @@ -126,7 +125,7 @@ def test_format_timestamp_out_of_bounds(self):
expected = '1300-12-01'
result = formatting.format_timestamp(date)
self.assertEqual(result, expected)

date = datetime(2300, 12, 1)
expected = '2300-12-01'
result = formatting.format_timestamp(date)
Expand Down