Skip to content

Commit

Permalink
Use ruff to lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Huite committed Nov 9, 2023
1 parent 233113b commit 9af15a0
Show file tree
Hide file tree
Showing 44 changed files with 355 additions and 316 deletions.
21 changes: 8 additions & 13 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
repos:
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.1.5
hooks:
- id: isort

- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
# Run the linter.
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
# Run the formatter.
- id: ruff-format
2 changes: 0 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
#
import pkg_resources

import xugrid

# -- Project information -----------------------------------------------------

project = "Xugrid"
Expand Down
2 changes: 1 addition & 1 deletion examples/connectivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
xr.full_like(ds["face_z"].ugrid.obj, False, dtype=bool),
ds.grids[0],
)
uda.values[0] = True
uda[0] = True
uda.ugrid.plot()

# %%
Expand Down
4 changes: 1 addition & 3 deletions examples/overlap_regridder.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@


def create_grid(bounds, nx, ny):
"""
Create a simple grid of triangles covering a rectangle.
"""
"""Create a simple grid of triangles covering a rectangle."""
import numpy as np
from matplotlib.tri import Triangulation

Expand Down
4 changes: 1 addition & 3 deletions examples/regridder_overview.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@


def create_grid(bounds, nx, ny):
"""
Create a simple grid of triangles covering a rectangle.
"""
"""Create a simple grid of triangles covering a rectangle."""
import numpy as np
from matplotlib.tri import Triangulation

Expand Down
19 changes: 19 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# See https://docs.astral.sh/ruff/rules/
select = ["C4", "D2", "D3", "D4", "E", "F", "I", "NPY", "PD"]
ignore = [
"D202",
"D205",
"D206",
"D400",
"D404",
"E402",
"E501",
"E703",
"PD002",
"PD901",
]
fixable = ["I"]
ignore-init-module-imports = true

[pydocstyle]
convention = "numpy"
14 changes: 0 additions & 14 deletions setup.cfg

This file was deleted.

2 changes: 0 additions & 2 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# __init__.py for pytest-cov
import importlib

import pytest


Expand Down
33 changes: 33 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,36 @@
quads_1,
quads_structured,
)

__all__ = (
"disk",
"disk_layered",
"expected_results_centroid",
"expected_results_linear",
"expected_results_overlap",
"grid_data_a",
"grid_data_a_1d",
"grid_data_a_2d",
"grid_data_a_layered",
"grid_data_a_layered_1d",
"grid_data_a_layered_2d",
"grid_data_b",
"grid_data_b_1d",
"grid_data_b_2d",
"grid_data_b_flipped_1d",
"grid_data_c",
"grid_data_c_1d",
"grid_data_c_2d",
"grid_data_d",
"grid_data_d_1d",
"grid_data_dask_expected",
"grid_data_dask_expected_layered",
"grid_data_dask_source",
"grid_data_dask_source_layered",
"grid_data_dask_target",
"grid_data_e",
"grid_data_e_1d",
"quads_0_25",
"quads_1",
"quads_structured",
)
10 changes: 5 additions & 5 deletions tests/test_core_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@


def test_either_dict_or_kwargs():
result = either_dict_or_kwargs(dict(a=1), None, "foo")
expected = dict(a=1)
result = either_dict_or_kwargs({"a": 1}, None, "foo")
expected = {"a": 1}
assert result == expected

result = either_dict_or_kwargs(None, dict(a=1), "foo")
expected = dict(a=1)
result = either_dict_or_kwargs(None, {"a": 1}, "foo")
expected = {"a": 1}
assert result == expected

with pytest.raises(ValueError, match=r"foo"):
result = either_dict_or_kwargs(dict(a=1), dict(a=1), "foo")
result = either_dict_or_kwargs({"a": 1}, {"a": 1}, "foo")
4 changes: 2 additions & 2 deletions tests/test_plot_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def _importorskip(

@contextlib.contextmanager
def figure_context(*args, **kwargs):
"""context manager which autocloses a figure (even if the test failed)"""
"""Context manager which autocloses a figure (even if the test failed)"""

try:
yield None
Expand Down Expand Up @@ -395,5 +395,5 @@ def test_label_from_attrs(self) -> None:

# Latex strings can be longer without needing a new line:
long_latex_name = r"$Ra_s = \mathrm{mean}(\epsilon_k) / \mu M^2_\infty$"
da.attrs = dict(long_name=long_latex_name)
da.attrs = {"long_name": long_latex_name}
assert label_from_attrs(da) == long_latex_name
8 changes: 4 additions & 4 deletions tests/test_regrid/test_regridder.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def test_centroid_locator_regridder(disk, quads_1):
regridder = CentroidLocatorRegridder(source=disk, target=square)
result = regridder.regrid(disk)
assert isinstance(result, xu.UgridDataArray)
assert result.notnull().any()
assert result.notna().any()
assert result.min() >= disk.min()
assert result.max() <= disk.max()
assert result.grid.n_face == square.grid.n_face
Expand All @@ -76,7 +76,7 @@ def test_centroid_locator_regridder(disk, quads_1):
regridder = CentroidLocatorRegridder(source=result, target=disk)
back = regridder.regrid(result)
assert isinstance(back, xu.UgridDataArray)
assert back.notnull().any()
assert back.notna().any()
assert back.min() >= disk.min()
assert back.max() <= disk.max()
assert back.grid.n_face == disk.grid.n_face
Expand Down Expand Up @@ -108,7 +108,7 @@ def test_overlap_regridder(disk, quads_1):
square = quads_1
regridder = OverlapRegridder(disk, square, method="mean")
result = regridder.regrid(disk)
assert result.notnull().any()
assert result.notna().any()
assert result.min() >= disk.min()
assert result.max() <= disk.max()

Expand Down Expand Up @@ -142,7 +142,7 @@ def test_barycentric_interpolator(disk, quads_0_25):
square = quads_0_25
regridder = BarycentricInterpolator(source=disk, target=square)
result = regridder.regrid(disk)
assert result.notnull().any()
assert result.notna().any()
assert result.min() >= disk.min()
assert result.max() <= disk.max()

Expand Down
4 changes: 2 additions & 2 deletions tests/test_snap.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,6 @@ def test_snap_to_grid_with_data():
assert isinstance(uds, xu.UgridDataset)
assert isinstance(gdf, gpd.GeoDataFrame)
assert uds["a"].dims == (uds.ugrid.grid.edge_dimension,)
assert uds["a"].notnull().sum() == 8
assert uds["line_index"].notnull().sum() == 8
assert uds["a"].notna().sum() == 8
assert uds["line_index"].notna().sum() == 8
assert uds["line_index"].sum() == 0 # all values should be 0
23 changes: 15 additions & 8 deletions tests/test_ugrid_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def test_getattr(self):
assert self.uda.dims == self.uda.ugrid.obj.dims
assert isinstance(self.uda.data, np.ndarray)
# So are functions
assert isinstance(self.uda.isnull(), xugrid.UgridDataArray)
assert isinstance(self.uda.isna(), xugrid.UgridDataArray)
# obj should be accessible
assert isinstance(self.uda.obj, xr.DataArray)

Expand Down Expand Up @@ -489,7 +489,7 @@ def test_setitem(self):
def test_getattr(self):
assert tuple(self.uds.dims) == ("mesh2d_nFaces",)
assert isinstance(self.uds.a, xugrid.UgridDataArray)
assert isinstance(self.uds.notnull(), xugrid.UgridDataset)
assert isinstance(self.uds.notna(), xugrid.UgridDataset)
# obj should be accessible
assert isinstance(self.uds.obj, xr.Dataset)

Expand Down Expand Up @@ -944,11 +944,14 @@ def test_merge():

def get_ugrid_fillvaluem999_startindex1():
"""
this is a very minimal but comparable dataset to Grevelingen_0002_map.nc (FM output)
It contains triangles and squares
the fillvalue of the connectivity arrays is -999
the start_index of the connectivity arrays is 1
Return a minimal dataset with a specific fill value.
This is a very minimal but comparable dataset to Grevelingen_0002_map.nc
(FM output).
* It contains both triangles and squares.
* The fillvalue of the connectivity arrays is -999
* The start_index of the connectivity arrays is 1
"""

ds2 = xr.Dataset()
Expand Down Expand Up @@ -1113,7 +1116,9 @@ def get_ugrid_fillvaluem999_startindex1():

def test_fm_fillvalue_startindex_isel():
"""
FM data has 1-based starting index and _FillValue -999, this raises several issues. Since it is not possible to generate a Ugrid2d with these attributes, we are testing with raw data
FM data has 1-based starting index and _FillValue -999, this raises several
issues. Since it is not possible to generate a Ugrid2d with these
attributes, we are testing with raw data
"""

# xugrid 0.5.0 warns "RuntimeWarning: invalid value encountered in cast: cast = data.astype(dtype, copy=True)"
Expand All @@ -1125,7 +1130,9 @@ def test_fm_fillvalue_startindex_isel():

def test_fm_facenodeconnectivity_fillvalue():
"""
FM data has 1-based starting index and _FillValue -999, this raises several issues. Since it is not possible to generate a Ugrid2d with these attributes, we are testing with raw data
FM data has 1-based starting index and _FillValue -999, this raises several
issues. Since it is not possible to generate a Ugrid2d with these
attributes, we are testing with raw data
"""

# xugrid 0.5.0 warns "RuntimeWarning: invalid value encountered in cast: cast = data.astype(dtype, copy=True)"
Expand Down
24 changes: 0 additions & 24 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,6 @@ isolated_build = True
setenv =
CONDA_EXE=mamba

[testenv:format]
skip_install = True
basepython = python3.9
commands =
isort .
black .
blacken-docs README.rst
deps =
black
blacken-docs
isort

[testenv:lint]
skip_install = True
basepython = python3.9
commands =
isort --check .
black --check .
flake8 .
deps =
black
flake8
isort

[testenv:build]
description = run pytest and build docs
basepython = python3.9
Expand Down
30 changes: 30 additions & 0 deletions xugrid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,33 @@
except pkg_resources.DistributionNotFound:
# package is not installed
pass


__all__ = (
"data",
"concat",
"full_like",
"merge",
"ones_like",
"open_dataarray",
"open_dataset",
"open_mfdataset",
"open_zarr",
"zeros_like",
"UgridDataArrayAccessor",
"UgridDatasetAccessor",
"UgridDataArray",
"UgridDataset",
"plot",
"BarycentricInterpolator",
"CentroidLocatorRegridder",
"OverlapRegridder",
"RelativeOverlapRegridder",
"burn_vector_geometry",
"UgridRolesAccessor",
"merge_partitions",
"polygonize",
"snap_to_grid",
"Ugrid1d",
"Ugrid2d",
)
4 changes: 1 addition & 3 deletions xugrid/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ class Vector(NamedTuple):


class MissingOptionalModule:
"""
Presents a clear error for optional modules.
"""
"""Presents a clear error for optional modules."""

def __init__(self, name):
self.name = name
Expand Down
4 changes: 2 additions & 2 deletions xugrid/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def _scalar_spacing(coords, spacing):
diff = coords.diff(dim)
spacing_value = abs(spacing.item())
if not np.allclose(
abs(diff.values), spacing_value, atol=abs(1.0e-4 * spacing.item())
abs(diff.to_numpy()), spacing_value, atol=abs(1.0e-4 * spacing.item())
):
raise ValueError(
f"spacing of {coords.name} does not match value of {spacing.name}"
Expand All @@ -140,7 +140,7 @@ def _implicit_spacing(coords):
f"Cannot derive spacing of 1-sized coordinate: {coords.name} \n"
f"Set bounds yourself or assign a d{coords.name} variable with spacing"
)
halfdiff = 0.5 * abs(coords.diff(dim)).values
halfdiff = 0.5 * abs(coords.diff(dim)).to_numpy()
return np.insert(halfdiff, 0, halfdiff[0])


Expand Down
Loading

0 comments on commit 9af15a0

Please sign in to comment.