Skip to content

Commit

Permalink
remove custom exceptions (#91)
Browse files Browse the repository at this point in the history
Removes custom exceptions so other packages don't have to import them for try/except blocks.
  • Loading branch information
bradyrx authored Jul 17, 2020
1 parent 51de777 commit 087090d
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 27 deletions.
8 changes: 4 additions & 4 deletions esmtools/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from .grid import convert_lon


@xr.register_dataarray_accessor("grid")
@xr.register_dataset_accessor("grid")
@xr.register_dataarray_accessor('grid')
@xr.register_dataset_accessor('grid')
class GridAccessor:
"""Allows functions to be called directly on an xarray dataset for the grid module.
Expand All @@ -14,7 +14,7 @@ class GridAccessor:
def __init__(self, xarray_obj):
self._obj = xarray_obj

def convert_lon(self, coord="lon"):
def convert_lon(self, coord='lon'):
"""Converts longitude grid from -180to180 to 0to360 and vice versa.
.. note::
Expand All @@ -29,6 +29,6 @@ def convert_lon(self, coord="lon"):
xarray object: Dataset with converted longitude grid.
Raises:
CoordinateError: If ``coord`` does not exist in the dataset.
ValueError: If ``coord`` does not exist in the dataset.
"""
return convert_lon(self._obj, coord=coord)
8 changes: 3 additions & 5 deletions esmtools/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import numpy as np
import xarray as xr

from .exceptions import DimensionError


def has_missing(data):
"""Returns ``True`` if any NaNs in ``data`` and ``False`` otherwise.
Expand Down Expand Up @@ -36,9 +34,9 @@ def has_dims(xobj, dims, kind):
dims = [dims]

if not all(dim in xobj.dims for dim in dims):
raise DimensionError(
f"Your {kind} object must contain the "
f"following dimensions at the minimum: {dims}"
raise ValueError(
f'Your {kind} object must contain the '
f'following dimensions at the minimum: {dims}'
)
return True

Expand Down
11 changes: 5 additions & 6 deletions esmtools/grid.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from .checks import is_xarray
from .exceptions import CoordinateError


@is_xarray(0)
def _convert_lon_to_180to180(ds, coord="lon"):
def _convert_lon_to_180to180(ds, coord='lon'):
"""Convert from 0 to 360 (degrees E) grid to -180 to 180 (W-E) grid.
.. note::
Expand All @@ -28,7 +27,7 @@ def _convert_lon_to_180to180(ds, coord="lon"):


@is_xarray(0)
def _convert_lon_to_0to360(ds, coord="lon"):
def _convert_lon_to_0to360(ds, coord='lon'):
"""Convert from -180 to 180 (W-E) to 0 to 360 (degrees E) grid.
.. note::
Expand All @@ -55,7 +54,7 @@ def _convert_lon_to_0to360(ds, coord="lon"):
# NOTE: Check weird POP grid that goes up to 240 or something. How do we deal with
# that?
@is_xarray(0)
def convert_lon(ds, coord="lon"):
def convert_lon(ds, coord='lon'):
"""Converts longitude grid from -180to180 to 0to360 and vice versa.
.. note::
Expand All @@ -70,7 +69,7 @@ def convert_lon(ds, coord="lon"):
xarray object: Dataset with converted longitude grid.
Raises:
CoordinateError: If ``coord`` does not exist in the dataset.
ValueError: If ``coord`` does not exist in the dataset.
Examples:
>>> import numpy as np
Expand All @@ -87,7 +86,7 @@ def convert_lon(ds, coord="lon"):
>>> converted = convert_lon(data, coord='lon')
"""
if coord not in ds.coords:
raise CoordinateError(f"{coord} not found in coordinates.")
raise ValueError(f'{coord} not found in coordinates.')
if ds[coord].min() < 0:
ds = _convert_lon_to_0to360(ds, coord=coord)
else:
Expand Down
23 changes: 11 additions & 12 deletions esmtools/tests/test_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import pytest
import xarray as xr

from esmtools.exceptions import CoordinateError
from esmtools.grid import convert_lon


Expand All @@ -23,13 +22,13 @@ def _gen_data(degreesEast=None):
elif not degreesEast:
lon = np.linspace(-179.5, 179.5, 360)
else:
raise ValueError("Please specify `degreesEast` as either True or False.")
raise ValueError('Please specify `degreesEast` as either True or False.')
# Template for broadcasting to
empty = xr.DataArray(
np.empty((180, 360)), dims=["lat", "lon"], coords=[lat, lon]
np.empty((180, 360)), dims=['lat', 'lon'], coords=[lat, lon]
)
# Data is roughly the longitude at each grid cell.
data = xr.DataArray(np.linspace(-180, 180, 360), dims=["lon"], coords=[lon])
data = xr.DataArray(np.linspace(-180, 180, 360), dims=['lon'], coords=[lon])
# Simple broadcasting up to 180x360 dimensions.
data, _ = xr.broadcast(data, empty)
data = data.T
Expand All @@ -55,19 +54,19 @@ def _gen_data(degreesEast=None):
elif not degreesEast:
x = np.linspace(-179.5, 179.5, 360)
else:
raise ValueError("Please specify `degreesEast` as either True or False.")
raise ValueError('Please specify `degreesEast` as either True or False.')
# Meshgrid into a 2-dimensional lon/lat.
lon, lat = np.meshgrid(x, y)
# Template for broadcasting to
empty = xr.DataArray(np.empty((180, 360)), dims=["y", "x"])
empty = xr.DataArray(np.empty((180, 360)), dims=['y', 'x'])
# Data is roughly the longitude at each grid cell.
data = xr.DataArray(np.linspace(-180, 180, 360), dims=["x"])
data = xr.DataArray(np.linspace(-180, 180, 360), dims=['x'])
# Simple broadcasting up to 180x360 dimensions.
data, _ = xr.broadcast(data, empty)
data = data.T
# Add 2D coordinates.
data["lon"] = (("y", "x"), lon)
data["lat"] = (("y", "x"), lat)
data['lon'] = (('y', 'x'), lon)
data['lat'] = (('y', 'x'), lat)
return data

return _gen_data
Expand Down Expand Up @@ -127,7 +126,7 @@ def test_coordinate_error(da_1D):
"""Tests that coordinate error is thrown when convert_lon is called and the
coordinate doesn't exist."""
data = da_1D(degreesEast=True)
with pytest.raises(CoordinateError) as e:
with pytest.raises(ValueError) as e:
# Purposefully call nonexistant coordinate.
convert_lon(data, coord="foo")
assert "not found in coordinates" in str(e.value)
convert_lon(data, coord='foo')
assert 'not found in coordinates' in str(e.value)

0 comments on commit 087090d

Please sign in to comment.