Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ pip-log.txt
nosetests.xml
.cache
.ropeproject/
.tags*
.testmondata
.pytest_cache

# asv environments
.asv
Expand Down
3 changes: 3 additions & 0 deletions .stickler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ linters:
flake8:
max-line-length: 79
fixer: true
ignore: I002
exclude:
- 'doc/'
py3k:
fixers:
enable: true
3 changes: 1 addition & 2 deletions asv_bench/benchmarks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from __future__ import division
from __future__ import print_function
import itertools
import random

import numpy as np

Expand All @@ -11,7 +10,7 @@

def requires_dask():
try:
import dask
import dask # noqa
except ImportError:
raise NotImplementedError

Expand Down
4 changes: 2 additions & 2 deletions asv_bench/benchmarks/dataarray_missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pandas as pd

try:
import dask
import dask # noqa
except ImportError:
pass

Expand All @@ -17,7 +17,7 @@
def make_bench_data(shape, frac_nan, chunks):
vals = randn(shape, frac_nan)
coords = {'time': pd.date_range('2000-01-01', freq='D',
periods=shape[0])}
periods=shape[0])}
da = xr.DataArray(vals, dims=('time', 'x', 'y'), coords=coords)

if chunks is not None:
Expand Down
2 changes: 1 addition & 1 deletion asv_bench/benchmarks/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

outer_indexes = {
'1d': {'x': randint(0, nx, 400)},
'2d': {'x': randint(0, nx, 500), 'y': randint(0, ny, 400)},
'2d': {'x': randint(0, nx, 500), 'y': randint(0, ny, 400)},
'2d-1scalar': {'x': randint(0, nx, 100), 'y': 1, 't': randint(0, nt, 400)}
}

Expand Down
1 change: 1 addition & 0 deletions doc/examples/_code/accessor_example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import xarray as xr


@xr.register_dataset_accessor('geo')
class GeoAccessor(object):
def __init__(self, xarray_obj):
Expand Down
1 change: 0 additions & 1 deletion doc/examples/_code/weather_data_setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import xarray as xr
import numpy as np
import pandas as pd
import seaborn as sns # pandas aware plotting library

np.random.seed(123)

Expand Down
6 changes: 4 additions & 2 deletions doc/gallery/plot_cartopy_facetgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
For more details see `this discussion`_ on github.

.. _this discussion: https://github.com/pydata/xarray/issues/1397#issuecomment-299190567
"""
""" # noqa

from __future__ import division

import xarray as xr
import cartopy.crs as ccrs
Expand All @@ -27,7 +29,7 @@

p = air.plot(transform=ccrs.PlateCarree(), # the data's projection
col='time', col_wrap=1, # multiplot settings
aspect=ds.dims['lon']/ds.dims['lat'], # for a sensible figsize
aspect=ds.dims['lon'] / ds.dims['lat'], # for a sensible figsize
Copy link
Contributor

Choose a reason for hiding this comment

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

W1619 division w/o future statement

subplot_kws={'projection': map_proj}) # the plot's projection

# We have to set the map's options on all four axes
Expand Down
10 changes: 5 additions & 5 deletions doc/gallery/plot_colorbar_center.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,26 @@
ds = xr.tutorial.load_dataset('air_temperature')
air = ds.air.isel(time=0)

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6))
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6))

# The first plot (in kelvins) chooses "viridis" and uses the data's min/max
air.plot(ax=ax1, cbar_kwargs={'label':'K'})
air.plot(ax=ax1, cbar_kwargs={'label': 'K'})
ax1.set_title('Kelvins: default')
ax2.set_xlabel('')

# The second plot (in celsius) now chooses "BuRd" and centers min/max around 0
airc = air - 273.15
airc.plot(ax=ax2, cbar_kwargs={'label':'°C'})
airc.plot(ax=ax2, cbar_kwargs={'label': '°C'})
ax2.set_title('Celsius: default')
ax2.set_xlabel('')
ax2.set_ylabel('')

# The center doesn't have to be 0
air.plot(ax=ax3, center=273.15, cbar_kwargs={'label':'K'})
air.plot(ax=ax3, center=273.15, cbar_kwargs={'label': 'K'})
ax3.set_title('Kelvins: center=273.15')

# Or it can be ignored
airc.plot(ax=ax4, center=False, cbar_kwargs={'label':'°C'})
airc.plot(ax=ax4, center=False, cbar_kwargs={'label': '°C'})
ax4.set_title('Celsius: center=False')
ax4.set_ylabel('')

Expand Down
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ python_files=test_*.py

[flake8]
max-line-length=79
ignore=I002
exclude=
doc/
Copy link
Member

Choose a reason for hiding this comment

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

Can you add this configuration to the .stickler.yml file, too? That will help keep things in sync.

See https://stickler-ci.com/docs#python

Copy link
Collaborator Author

@max-sixty max-sixty Feb 20, 2018

Choose a reason for hiding this comment

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

Good idea, done
(though ideally @stickler-ci you should read from standard configs...)

Copy link
Member

Choose a reason for hiding this comment

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

It looks like this didn't actually work to ignore the doc directories -- see all the Stickler messages in #1930

17 changes: 11 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import warnings

from setuptools import setup, find_packages
from setuptools import Command

MAJOR = 0
MINOR = 10
Expand Down Expand Up @@ -64,7 +63,7 @@
- Issue tracker: http://github.com/pydata/xarray/issues
- Source code: http://github.com/pydata/xarray
- SciPy2015 talk: https://www.youtube.com/watch?v=X0pAhJgySxk
"""
""" # noqa

# Code to extract and write the version copied from pandas.
# Used under the terms of pandas's license, see licenses/PANDAS_LICENSE.
Expand All @@ -84,18 +83,23 @@
(so, serr) = pipe.communicate()
if pipe.returncode == 0:
break
except:
except BaseException:
pass

if pipe is None or pipe.returncode != 0:
# no git, or not in git dir
if os.path.exists('xarray/version.py'):
warnings.warn("WARNING: Couldn't get git revision, using existing xarray/version.py")
warnings.warn(
"WARNING: Couldn't get git revision,"
" using existing xarray/version.py")
write_version = False
else:
warnings.warn("WARNING: Couldn't get git revision, using generic version string")
warnings.warn(
"WARNING: Couldn't get git revision,"
" using generic version string")
else:
# have git, in git dir, but may have used a shallow clone (travis does this)
# have git, in git dir, but may have used a shallow clone (travis does
# this)
rev = so.strip()
# makes distutils blow up on Python 2.7
if sys.version_info[0] >= 3:
Expand Down Expand Up @@ -132,6 +136,7 @@ def write_version_py(filename=None):
finally:
a.close()


if write_version:
write_version_py()

Expand Down
4 changes: 2 additions & 2 deletions xarray/backends/rasterio_.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ def open_rasterio(filename, parse_coordinates=None, chunks=None, cache=None,
if parse:
nx, ny = riods.width, riods.height
# xarray coordinates are pixel centered
x, _ = (np.arange(nx)+0.5, np.zeros(nx)+0.5) * transform
_, y = (np.zeros(ny)+0.5, np.arange(ny)+0.5) * transform
x, _ = (np.arange(nx) + 0.5, np.zeros(nx) + 0.5) * transform
_, y = (np.zeros(ny) + 0.5, np.arange(ny) + 0.5) * transform
coords['y'] = y
coords['x'] = x
else:
Expand Down
4 changes: 2 additions & 2 deletions xarray/backends/zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ def _encode_zarr_attr_value(value):
encoded = value.item()
# np.string_('X').item() returns a type `bytes`
# zarr still doesn't like that
if type(encoded) is bytes:
if type(encoded) is bytes: # noqa
encoded = b64encode(encoded)
else:
encoded = value
return encoded


def _ensure_valid_fill_value(value, dtype):
if dtype.type == np.string_ and type(value) == bytes:
if dtype.type == np.string_ and type(value) == bytes: # noqa
valid = b64encode(value)
else:
valid = value
Expand Down
6 changes: 4 additions & 2 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1516,7 +1516,8 @@ def take(variable, slices):
# Note: remove helper function when once when numpy
# supports vindex https://github.com/numpy/numpy/pull/6075
if hasattr(variable.data, 'vindex'):
# Special case for dask backed arrays to use vectorised list indexing
# Special case for dask backed arrays to use vectorised list
# indexing
sel = variable.data.vindex[slices]
else:
# Otherwise assume backend is numpy array with 'fancy' indexing
Expand Down Expand Up @@ -1579,7 +1580,8 @@ def relevant_keys(mapping):
variables = OrderedDict()

for name, var in reordered.variables.items():
if name in indexers_dict or any(d in indexer_dims for d in var.dims):
if name in indexers_dict or any(
d in indexer_dims for d in var.dims):
# slice if var is an indexer or depends on an indexed dim
slc = [indexers_dict[k]
if k in indexers_dict
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ class ExplicitIndexer(object):
"""

def __init__(self, key):
if type(self) is ExplicitIndexer:
if type(self) is ExplicitIndexer: # noqa
raise TypeError('cannot instantiate base ExplicitIndexer objects')
self._key = tuple(key)

Expand Down
10 changes: 6 additions & 4 deletions xarray/core/pycompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def __exit__(self, exctype, excinst, exctb):
# exactly reproduce the limitations of the CPython interpreter.
#
# See http://bugs.python.org/issue12029 for more details
return exctype is not None and issubclass(exctype, self._exceptions)
return exctype is not None and issubclass(
exctype, self._exceptions)
try:
from contextlib import ExitStack
except ImportError:
Expand Down Expand Up @@ -185,7 +186,8 @@ def enter_context(self, cm):
If successful, also pushes its __exit__ method as a callback and
returns the result of the __enter__ method.
"""
# We look up the special methods on the type to match the with statement
# We look up the special methods on the type to match the with
# statement
_cm_type = type(cm)
_exit = _cm_type.__exit__
result = _cm_type.__enter__(cm)
Expand All @@ -208,7 +210,7 @@ def __exit__(self, *exc_details):

def _fix_exception_context(new_exc, old_exc):
# Context may not be correct, so find the end of the chain
while 1:
while True:
exc_context = new_exc.__context__
if exc_context is old_exc:
# Context is already set correctly (see issue 20317)
Expand All @@ -231,7 +233,7 @@ def _fix_exception_context(new_exc, old_exc):
suppressed_exc = True
pending_raise = False
exc_details = (None, None, None)
except:
except BaseException:
new_exc_details = sys.exc_info()
# simulate the stack of exceptions by setting the context
_fix_exception_context(new_exc_details[1], exc_details[1])
Expand Down
4 changes: 2 additions & 2 deletions xarray/plot/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,9 +759,9 @@ def _is_monotonic(coord, axis=0):
else:
n = coord.shape[axis]
delta_pos = (coord.take(np.arange(1, n), axis=axis) >=
coord.take(np.arange(0, n-1), axis=axis))
coord.take(np.arange(0, n - 1), axis=axis))
delta_neg = (coord.take(np.arange(1, n), axis=axis) <=
coord.take(np.arange(0, n-1), axis=axis))
coord.take(np.arange(0, n - 1), axis=axis))
return np.all(delta_pos) or np.all(delta_neg)


Expand Down
6 changes: 3 additions & 3 deletions xarray/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def assert_equal(a, b):
"""
import xarray as xr
__tracebackhide__ = True # noqa: F841
assert type(a) == type(b)
assert type(a) == type(b) # noqa
if isinstance(a, (xr.Variable, xr.DataArray, xr.Dataset)):
assert a.equals(b), '{}\n{}'.format(a, b)
else:
Expand All @@ -77,7 +77,7 @@ def assert_identical(a, b):
"""
import xarray as xr
__tracebackhide__ = True # noqa: F841
assert type(a) == type(b)
assert type(a) == type(b) # noqa
if isinstance(a, xr.DataArray):
assert a.name == b.name
assert_identical(a._to_temp_dataset(), b._to_temp_dataset())
Expand Down Expand Up @@ -115,7 +115,7 @@ def assert_allclose(a, b, rtol=1e-05, atol=1e-08, decode_bytes=True):
"""
import xarray as xr
__tracebackhide__ = True # noqa: F841
assert type(a) == type(b)
assert type(a) == type(b) # noqa
kwargs = dict(rtol=rtol, atol=atol, decode_bytes=decode_bytes)
if isinstance(a, xr.Variable):
assert a.dims == b.dims
Expand Down
17 changes: 10 additions & 7 deletions xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ def test_roundtrip_endian(self):
# should still pass though.
assert_identical(ds, actual)

if type(self) is NetCDF4DataTest:
if isinstance(self, NetCDF4DataTest):
ds['z'].encoding['endian'] = 'big'
with pytest.raises(NotImplementedError):
with self.roundtrip(ds) as actual:
Expand Down Expand Up @@ -2214,7 +2214,10 @@ def create_tmp_geotiff(nx=4, ny=3, nz=3,
else:
data_shape = nz, ny, nx
write_kwargs = {}
data = np.arange(nz*ny*nx, dtype=rasterio.float32).reshape(*data_shape)
data = np.arange(
nz * ny * nx,
dtype=rasterio.float32).reshape(
*data_shape)
if transform is None:
transform = from_origin(*transform_args)
with rasterio.open(
Expand All @@ -2231,10 +2234,10 @@ def create_tmp_geotiff(nx=4, ny=3, nz=3,
data = data[np.newaxis, ...] if nz == 1 else data
expected = DataArray(data, dims=('band', 'y', 'x'),
coords={
'band': np.arange(nz)+1,
'y': -np.arange(ny) * d + b + dy/2,
'x': np.arange(nx) * c + a + dx/2,
})
'band': np.arange(nz) + 1,
'y': -np.arange(ny) * d + b + dy / 2,
'x': np.arange(nx) * c + a + dx / 2,
})
yield tmp_file, expected


Expand Down Expand Up @@ -2316,7 +2319,7 @@ def test_notransform(self):
with create_tmp_file(suffix='.tif') as tmp_file:
# data
nx, ny, nz = 4, 3, 3
data = np.arange(nx*ny*nz,
data = np.arange(nx * ny * nz,
dtype=rasterio.float32).reshape(nz, ny, nx)
with rasterio.open(
tmp_file, 'w',
Expand Down
2 changes: 1 addition & 1 deletion xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ def test_properties(self):
# change them inadvertently:
assert isinstance(ds.dims, utils.Frozen)
assert isinstance(ds.dims.mapping, utils.SortedKeysDict)
assert type(ds.dims.mapping.mapping) is dict
assert type(ds.dims.mapping.mapping) is dict # noqa

with pytest.warns(FutureWarning):
self.assertItemsEqual(ds, list(ds.variables))
Expand Down
Loading