Skip to content

Commit

Permalink
Fix ruff linting errors
Browse files Browse the repository at this point in the history
  • Loading branch information
tomvothecoder committed Oct 2, 2024
1 parent 9112f98 commit 2401905
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 56 deletions.
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[tool.ruff.lint]
[tool.ruff]
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
Expand Down Expand Up @@ -30,6 +30,7 @@ exclude = [
"venv",
]

[tool.ruff.lint]
# E4 - whitespace
# E7 - multiple-statements
# E9 - trailing-whitespace
Expand All @@ -38,7 +39,7 @@ exclude = [
# W - Enable pycodestyle
# C901 - complex-structure
# D - Enable flake8-docstrings
select = ["E4", "E7", "E9", "F", "B", "W", "D", "C901"]
select = ["E4", "E7", "E9", "F", "B", "W", "C901"]

# E501 - line-too-long
ignore = ["E501"]
Expand Down
2 changes: 1 addition & 1 deletion tests/test_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,7 @@ def test_add_monthly_bounds_for_end_of_month_set_to_true(self):
# Get time axis and create new axis with time set to first day of month.
time = ds_with_bnds.time
new_time = []
for i, t in enumerate(time.values):
for _, t in enumerate(time.values):
y = t.year
m = t.month
nt = cftime.DatetimeGregorian(y, m, 1, 0)
Expand Down
13 changes: 9 additions & 4 deletions tests/test_regrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,12 @@ def test_methods(self):
xgcm.XGCMRegridder(self.ds, self.output_grid, method="linear", target_data=None)

with pytest.raises(ValueError, match="'dummy' is invalid, possible choices"):
xgcm.XGCMRegridder(self.ds, self.output_grid, method="dummy", target_data=None) # type: ignore
xgcm.XGCMRegridder(
self.ds,
self.output_grid,
method="dummy", # type: ignore
target_data=None,
)

def test_missing_input_z_coord(self):
ds = fixtures.generate_dataset(
Expand Down Expand Up @@ -663,7 +668,7 @@ def test_map_latitude_coarse_to_fine(self):
np.testing.assert_allclose(x, y)

for x2, y2 in zip(weights, expected_weigths):
np.testing.assert_allclose(x, y)
np.testing.assert_allclose(x2, y2)

def test_map_latitude_fine_to_coarse(self):
mapping, weights = regrid2._map_latitude(
Expand Down Expand Up @@ -1254,7 +1259,7 @@ def test_grid(self):
ValueError,
match=r".*lon\d?.*lon\d?.*",
):
ds_multi.regridder.grid
ds_multi.regridder.grid # noqa: B018

def test_grid_raises_error_when_dataset_has_multiple_dims_for_an_axis(self):
ds_bounds = fixtures.generate_dataset(
Expand All @@ -1265,7 +1270,7 @@ def test_grid_raises_error_when_dataset_has_multiple_dims_for_an_axis(self):
)

with pytest.raises(ValueError):
ds_bounds.regridder.grid
ds_bounds.regridder.grid # noqa: B018

@mock.patch("xcdat.regridder.accessor._get_input_grid")
def test_horizontal_tool_check(self, _get_input_grid):
Expand Down
15 changes: 10 additions & 5 deletions xcdat/bounds.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Bounds module for functions related to coordinate bounds."""

import collections
import datetime
import warnings
from typing import Dict, List, Literal, Optional, Union
from typing import Dict, List, Literal, Optional, Tuple, Union

import cf_xarray as cfxr # noqa: F401
import cftime
Expand Down Expand Up @@ -124,7 +125,7 @@ def keys(self) -> List[str]:
)

def add_missing_bounds( # noqa: C901
self, axes: List[CFAxisKey] = ["X", "Y", "T"]
self, axes: List[CFAxisKey] | Tuple[CFAxisKey, ...] = ("X", "Y", "T")
) -> xr.Dataset:
"""Adds missing coordinate bounds for supported axes in the Dataset.
Expand Down Expand Up @@ -153,9 +154,9 @@ def add_missing_bounds( # noqa: C901
Parameters
----------
axes : List[str]
axes : List[str] | Tuple[str]
List of CF axes that function should operate on, by default
["X", "Y", "T"]. Options include "X", "Y", "T", or "Z".
("X", "Y", "T"). Options include "X", "Y", "T", or "Z".
Returns
-------
Expand Down Expand Up @@ -614,7 +615,11 @@ def _create_time_bounds( # noqa: C901
hrs = diff.seconds / 3600
daily_subfreq = int(24 / hrs) # type: ignore

time_bnds = self._create_daily_time_bounds(timesteps, obj_type, freq=daily_subfreq) # type: ignore
time_bnds = self._create_daily_time_bounds(
timesteps,
obj_type,
freq=daily_subfreq, # type: ignore
)

# Create the bounds data array
da_time_bnds = xr.DataArray(
Expand Down
22 changes: 11 additions & 11 deletions xcdat/dataset.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Dataset module for functions related to an xarray.Dataset."""

from __future__ import annotations

import os
Expand All @@ -21,9 +22,8 @@

from xcdat import bounds as bounds_accessor # noqa: F401
from xcdat._logger import _setup_custom_logger
from xcdat.axis import CFAxisKey, _get_all_coord_keys
from xcdat.axis import CFAxisKey, _get_all_coord_keys, swap_lon_axis
from xcdat.axis import center_times as center_times_func
from xcdat.axis import swap_lon_axis

logger = _setup_custom_logger(__name__)

Expand All @@ -44,7 +44,7 @@
def open_dataset(
path: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
data_var: Optional[str] = None,
add_bounds: List[CFAxisKey] | None = ["X", "Y"],
add_bounds: List[CFAxisKey] | Tuple[CFAxisKey, ...] | None = ("X", "Y"),
decode_times: bool = True,
center_times: bool = False,
lon_orient: Optional[Tuple[float, float]] = None,
Expand All @@ -63,9 +63,9 @@ def open_dataset(
data_var: Optional[str], optional
The key of the non-bounds data variable to keep in the Dataset,
alongside any existing bounds data variables, by default None.
add_bounds: List[CFAxisKey] | None | bool
add_bounds: List[CFAxisKey] | Tuple[CFAxisKey, ...] | None
List of CF axes to try to add bounds for (if missing), by default
["X", "Y"]. Set to None to not add any missing bounds. Please note that
("X", "Y"). Set to None to not add any missing bounds. Please note that
bounds are required for many xCDAT features.
* This parameter calls :py:func:`xarray.Dataset.bounds.add_missing_bounds`
Expand Down Expand Up @@ -127,7 +127,7 @@ def open_dataset(
def open_mfdataset(
paths: str | NestedSequence[str | os.PathLike],
data_var: Optional[str] = None,
add_bounds: List[CFAxisKey] | None = ["X", "Y"],
add_bounds: List[CFAxisKey] | Tuple[CFAxisKey, ...] | None = ("X", "Y"),
decode_times: bool = True,
center_times: bool = False,
lon_orient: Optional[Tuple[float, float]] = None,
Expand All @@ -152,9 +152,9 @@ def open_mfdataset(
If concatenation along more than one dimension is desired, then
``paths`` must be a nested list-of-lists (see [2]_
``xarray.combine_nested`` for details).
add_bounds: List[CFAxisKey] | None | bool
add_bounds: List[CFAxisKey] | Tuple[CFAxisKey, ...] | None
List of CF axes to try to add bounds for (if missing), by default
["X", "Y"]. Set to None to not add any missing bounds. Please note that
("X", "Y"). Set to None to not add any missing bounds. Please note that
bounds are required for many xCDAT features.
* This parameter calls :py:func:`xarray.Dataset.bounds.add_missing_bounds`
Expand Down Expand Up @@ -464,7 +464,7 @@ def _postprocess_dataset(
dataset: xr.Dataset,
data_var: Optional[str] = None,
center_times: bool = False,
add_bounds: List[CFAxisKey] | None | bool = ["X", "Y"],
add_bounds: List[CFAxisKey] | Tuple[CFAxisKey, ...] | None = ("X", "Y"),
lon_orient: Optional[Tuple[float, float]] = None,
) -> xr.Dataset:
"""Post-processes a Dataset object.
Expand All @@ -479,9 +479,9 @@ def _postprocess_dataset(
If True, center time coordinates using the midpoint between its upper
and lower bounds. Otherwise, use the provided time coordinates, by
default False.
add_bounds: List[CFAxisKey] | None | bool
add_bounds: List[CFAxisKey] | Tuple[CFAxisKey, ...] | bool
List of CF axes to try to add bounds for (if missing), default
["X", "Y"]. Set to None to not add any missing bounds.
("X", "Y"). Set to None to not add any missing bounds.
* This parameter simply calls :py:func:`xarray.Dataset.bounds.add_missing_bounds`
* Supported CF axes include "X", "Y", "Z", and "T"
Expand Down
9 changes: 4 additions & 5 deletions xcdat/regridder/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from xcdat.regridder.accessor import RegridderAccessor
from xcdat.regridder.regrid2 import Regrid2Regridder
from xcdat.regridder.xesmf import XESMFRegridder
from xcdat.regridder.xgcm import XGCMRegridder
from xcdat.utils import _has_module
from xcdat.regridder.accessor import RegridderAccessor # noqa: F401
from xcdat.regridder.regrid2 import Regrid2Regridder # noqa: F401
from xcdat.regridder.xesmf import XESMFRegridder # noqa: F401
from xcdat.regridder.xgcm import XGCMRegridder # noqa: F401
4 changes: 2 additions & 2 deletions xcdat/regridder/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def horizontal(
except KeyError as e:
raise ValueError(
f"Tool {e!s} does not exist, valid choices {list(HORIZONTAL_REGRID_TOOLS)}"
)
) from e

input_grid = _get_input_grid(self._ds, data_var, ["X", "Y"])
regridder = regrid_tool(input_grid, output_grid, **options)
Expand Down Expand Up @@ -269,7 +269,7 @@ def vertical(
raise ValueError(
f"Tool {e!s} does not exist, valid choices "
f"{list(VERTICAL_REGRID_TOOLS)}"
)
) from e
input_grid = _get_input_grid(
self._ds,
data_var,
Expand Down
6 changes: 3 additions & 3 deletions xcdat/regridder/regrid2.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def _map_latitude(


def _get_latitude_weights(
bounds: List[Tuple[np.ndarray, np.ndarray]]
bounds: List[Tuple[np.ndarray, np.ndarray]],
) -> List[np.ndarray]:
weights = []

Expand Down Expand Up @@ -555,8 +555,8 @@ def _get_dimension(input_data_var, cf_axis_name):
def _get_bounds_ensure_dtype(ds, axis):
try:
name = ds.cf.bounds[axis][0]
except (KeyError, IndexError):
raise RuntimeError(f"Could not determine {axis!r} bounds")
except (KeyError, IndexError) as e:
raise RuntimeError(f"Could not determine {axis!r} bounds") from e
else:
bounds = ds[name]

Expand Down
18 changes: 10 additions & 8 deletions xcdat/regridder/xgcm.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,10 @@ def vertical(self, data_var: str, ds: xr.Dataset) -> xr.Dataset:
"""See documentation in :py:func:`xcdat.regridder.xgcm.XGCMRegridder`"""
try:
output_coord_z = get_dim_coords(self._output_grid, "Z")
except KeyError:
raise RuntimeError("Could not determine 'Z' coordinate in output dataset")
except KeyError as e:
raise RuntimeError(
"Could not determine 'Z' coordinate in output dataset"
) from e

if self._grid_positions is None:
grid_coords = self._get_grid_positions()
Expand All @@ -165,11 +167,11 @@ def vertical(self, data_var: str, ds: xr.Dataset) -> xr.Dataset:
target_data = ds[self._target_data]
except ValueError:
target_data = self._target_data
except KeyError:
except KeyError as e:
if self._target_data is not None and isinstance(self._target_data, str):
raise RuntimeError(
f"Could not find target variable {self._target_data!r} in dataset"
)
) from e

target_data = None

Expand Down Expand Up @@ -216,8 +218,8 @@ def _get_grid_positions(self) -> Dict[str, Union[Any, Hashable]]:

try:
coord_z = get_dim_coords(self._input_grid, "Z")
except KeyError:
raise RuntimeError("Could not determine `Z` coordinate in dataset.")
except KeyError as e:
raise RuntimeError("Could not determine `Z` coordinate in dataset.") from e

if isinstance(coord_z, xr.Dataset):
coords = ", ".join(sorted(list(coord_z.coords.keys()))) # type: ignore[arg-type]
Expand All @@ -231,8 +233,8 @@ def _get_grid_positions(self) -> Dict[str, Union[Any, Hashable]]:

try:
bounds_z = self._input_grid.bounds.get_bounds("Z")
except KeyError:
raise RuntimeError("Could not determine `Z` bounds in dataset.")
except KeyError as e:
raise RuntimeError("Could not determine `Z` bounds in dataset.") from e

# handle simple point positions based on point and bounds
if (coord_z[0] > bounds_z[0][0] and coord_z[0] < bounds_z[0][1]) or (
Expand Down
Loading

0 comments on commit 2401905

Please sign in to comment.