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 linters to deltametrics: flake8 #186

Merged
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ repos:
rev: 7.1.1
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- flake8-comprehensions
- flake8-simplify
# additional_dependencies:
# - flake8-bugbear
# - flake8-comprehensions
# - flake8-simplify
exclude: ^docs/source/pyplots/guides/.*$

- repo: https://github.com/asottile/pyupgrade
Expand Down
2 changes: 2 additions & 0 deletions deltametrics/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
import deltametrics.sample_data as sample_data
from deltametrics._version import __version__

__all__ = ("sample_data", "__version__")
1 change: 0 additions & 1 deletion deltametrics/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,6 @@ def threshold(self):

def _compute_mask(self):
"""Provide abstract method."""
pass


class ElevationMask(ThresholdValueMask):
Expand Down
30 changes: 14 additions & 16 deletions deltametrics/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from numba import prange
from numba import set_num_threads
from scipy.ndimage import binary_fill_holes
from scipy.ndimage import generate_binary_structure
from scipy.signal import fftconvolve
from scipy.spatial import ConvexHull
from skimage import morphology
Expand All @@ -26,6 +25,7 @@
from deltametrics.utils import is_ndarray_or_xarray
# from shapely.geometry.polygon import Polygon


class BasePlanform(abc.ABC):
"""Base planform object.

Expand Down Expand Up @@ -1826,7 +1826,7 @@
# Query set refers to the points for which the angle is calculated, test
# set refers to the points which bound the angle calculations.

## Preprocess
# Preprocess
if preprocess:
# Preprocess in orginal paper: "we pre-process by filling lakes
# (contiguous sets of water pixels surrounded by land)"
Expand All @@ -1837,10 +1837,10 @@
# Ensure array is integer binary
below_mask = below_mask.astype(int)

## Make padded version of below_mask and edges
# Make padded version of below_mask and edges
pad_below_mask = np.pad(below_mask, 1, "edge")

## Find land-water interface (`edges`)
# Find land-water interface (`edges`)
selem = np.ones((3, 3)).astype(
int
) # include diagonals in edge, another option would be a 3x3 disk (no corners)
Expand All @@ -1861,11 +1861,11 @@
"Cannot compute the Opening Angle Method."
)

## Find set of all `sea` points to evaluate
# Find set of all `sea` points to evaluate
all_sea_idxs = np.column_stack(np.where(pad_below_mask))
all_sea_points = np.fliplr(all_sea_idxs)

## Make test set
# Make test set
edge_idxs = np.column_stack(np.where(pad_edges))
edge_points = np.fliplr(edge_idxs) # as columns, x-y pairs
land_points = np.fliplr(
Expand Down Expand Up @@ -1898,10 +1898,10 @@
f"Invalid option '{test_set}' for `test_set` parameter was supplied."
)

## Find convex hull
# Find convex hull
hull = ConvexHull(test_set_points, qhull_options="Qc")

## Make sea points
# Make sea points
# identify set of points in both the convex hull polygon and
# defined as points_to_test and put these binary points into seamap
sea_points_in_hull_bool = _points_in_polygon(
Expand All @@ -1914,7 +1914,7 @@
sea_points_in_hull = all_sea_points[sea_points_in_hull_bool]
sea_idxs_outside_hull = all_sea_idxs[~sea_points_in_hull_bool]

## Make query set
# Make query set
# flexible processing of the query set
if query_set == "sea":
# all water locations inside the hull
Expand All @@ -1931,7 +1931,7 @@
f"Invalid option '{query_set}' for `query_set` parameter was supplied."
)

## Compute opening angle
# Compute opening angle
# this is the main workhorse of the algorithm
# (see _compute_angles_between docstring for more information).
if parallel > 0:
Expand All @@ -1940,7 +1940,7 @@
set_num_threads(1) # if false, 1 thread max
theta = _compute_angles_between(test_set_points, query_set_points, numviews)

## Cast to map shape
# Cast to map shape
# create a new array with padded shape to return and cast values into it
pad_opening_angles = np.zeros_like(pad_below_mask)
# fill the query points with the value returned from theta
Expand Down Expand Up @@ -1988,10 +1988,8 @@
The FFT implementation is after
https://www.cs.utep.edu/vladik/misha5.pdf
"""
_changed = np.inf
disk = morphology.disk(disksize)
r = (disksize // 2) + 1 # kernel radius, i.e. half the width of disk
_iter = 0 # count number of closings, cap at 100

# binary_closing is dilation followed by erosion
_dilated = _fft_dilate(img, disk)
Expand Down Expand Up @@ -2156,15 +2154,15 @@
# coerce the channel mask to just the raw mask values
if is_ndarray_or_xarray(channelmask):
if isinstance(channelmask, xr.core.dataarray.DataArray):
_dx = float(
_ = float(

Check warning on line 2157 in deltametrics/plan.py

View check run for this annotation

Codecov / codecov/patch

deltametrics/plan.py#L2157

Added line #L2157 was not covered by tests
channelmask[channelmask.dims[0]][1]
- channelmask[channelmask.dims[0]][0]
)
elif isinstance(channelmask, np.ndarray):
_dx = 1
_ = 1
elif isinstance(channelmask, ChannelMask):
channelmask = channelmask.mask
_dx = float(
_ = float(
channelmask[channelmask.dims[0]][1] - channelmask[channelmask.dims[0]][0]
)
channelmask = np.array(channelmask)
Expand Down
11 changes: 3 additions & 8 deletions deltametrics/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,7 @@ def __init__(self, name, **kwargs):
raise TypeError("name argument must be type `str`, but was %s" % type(name))
self._name = name

self.cmap = kwargs.pop(
"cmap", mpl.colormaps["viridis"].resampled(64)
) # .get_cmap('viridis', 64))
self.cmap = kwargs.pop("cmap", mpl.colormaps["viridis"].resampled(64))
self.label = kwargs.pop("label", None)
self.norm = kwargs.pop("norm", None)
self.vmin = kwargs.pop("vmin", None)
Expand Down Expand Up @@ -498,12 +496,9 @@ def net_to_gross(self):
@net_to_gross.setter
def net_to_gross(self, var):
if not var:
# oranges = cm.get_cmap('Oranges', 64)
# greys = cm.get_cmap('Greys_r', 64)
# whiteblack = cm.get_cmap('Greys', 2)
oranges = mpl.colormaps["Oranges"].resampled(64)
greys = mpl.colormaps["Greys_r"].resampled(64)
whiteblack = mpl.colormaps["Greys"].resampled(2)
# whiteblack = mpl.colormaps["Greys"].resampled(2)
combined = np.vstack(
(greys(np.linspace(0.3, 0.6, 16)), oranges(np.linspace(0.2, 0.8, 48)))
)
Expand Down Expand Up @@ -1181,7 +1176,7 @@ def show_one_dimensional_trajectory_to_strata(
else:
raise ValueError('Elevation data "e" must be one-dimensional.')
t = np.arange(e.shape[0]) # x-axis time array
t3 = np.expand_dims(t, axis=(1, 2)) # 3d time, for slicing
# t3 = np.expand_dims(t, axis=(1, 2)) # 3d time, for slicing
e_in = e.copy()

if sigma_dist is not None:
Expand Down
9 changes: 9 additions & 0 deletions deltametrics/sample_data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,12 @@
from deltametrics.sample_data.sample_data import rcm8
from deltametrics.sample_data.sample_data import savi2020
from deltametrics.sample_data.sample_data import xslope

__all__ = (
"aeolian",
"golf",
"landsat",
"rcm8",
"savi2020",
"xslope",
)
3 changes: 0 additions & 3 deletions deltametrics/sample_data/sample_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@
import sys
import warnings

import netCDF4
import numpy as np
import pooch

if sys.version_info >= (3, 12): # pragma: no cover (PY12+)
import importlib.resources as importlib_resources
else: # pragma: no cover (<PY312)
import importlib_resources

from deltametrics._version import __version__
from deltametrics.cube import DataCube


Expand Down
9 changes: 6 additions & 3 deletions deltametrics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,15 +188,18 @@ def curve_fit(data, fit='harmonic'):

# do fit
if fit == 'harmonic':
def func_harmonic(x, a, b): return a / (1 + b * x)
def func_harmonic(x, a, b):
return a / (1 + b * x)
popt, pcov = optimize.curve_fit(func_harmonic, xdata, data)
yfit = func_harmonic(xdata, *popt)
elif fit == 'exponential':
def func_exponential(x, a, b, c): return (a - b) * np.exp(-c * x) + b
def func_exponential(x, a, b, c):
return (a - b) * np.exp(-c * x) + b
popt, pcov = optimize.curve_fit(func_exponential, xdata, data)
yfit = func_exponential(xdata, *popt)
elif fit == 'linear':
def func_linear(x, a, b): return a * x + b
def func_linear(x, a, b):
return a * x + b
popt, pcov = optimize.curve_fit(func_linear, xdata, data)
yfit = func_linear(xdata, *popt)

Expand Down
1 change: 0 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
#
import importlib
import os
import sys


def get_version_from_file(path_to_version_file: str) -> str:
Expand Down
1 change: 1 addition & 0 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def lint(session: nox.Session) -> None:
session.run("pre-commit", "run", "--all-files", "trailing-whitespace")
session.run("pre-commit", "run", "--all-files", "end-of-file-fixer")
session.run("pre-commit", "run", "--all-files", "pyupgrade")
session.run("pre-commit", "run", "--all-files", "flake8")


@nox.session
Expand Down
11 changes: 11 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[flake8]
exclude = docs/source/pyplots/guides, build, .nox
ignore =
C901, E203, E501, W503,
# These mostly deal with whitespace and will be found and fixed with black
E121, E125, E126, E127, E226, E241, E261, E275, E302, E305,
B024, B950,
W504
max-line-length = 88
max-complexity = 18
select = B,C,E,F,W,T4,B9
3 changes: 1 addition & 2 deletions tests/test_io.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import sys

import numpy as np
Expand Down Expand Up @@ -211,7 +210,7 @@ def test_bad_dimensions_length(self):
def test_bad_dimensions_shape_mismatch(self):
with pytest.raises(ValueError, match=r'Shape of `dimensions` .*'):
# note dim2 and dim1 are switchd below!
_ = dict_io = DictionaryIO(
DictionaryIO(
self.dict_np, dimensions={
'time': np.arange(self._shape[0]),
'x': np.arange(self._shape[2]),
Expand Down
4 changes: 1 addition & 3 deletions tests/test_mask.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""Tests for the mask.py script."""
import os
import sys
import unittest.mock as mock

import matplotlib.pyplot as plt
Expand Down Expand Up @@ -67,7 +65,7 @@ def test_simple_example(self):
basemask = BaseMask("field", self.fake_input)

# make a bunch of assertions
assert np.all(basemask._mask == False)
assert not np.any(basemask._mask)
assert np.all(basemask.integer_mask == 0)
assert basemask._mask is basemask.mask
assert basemask.shape == self.fake_input.shape
Expand Down
3 changes: 0 additions & 3 deletions tests/test_mobility.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
"""Tests for mobility.py."""
import os
import sys

import numpy as np
import pytest
import xarray as xr
Expand Down
2 changes: 0 additions & 2 deletions tests/test_plot.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
Expand Down
6 changes: 3 additions & 3 deletions tests/test_section.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ def test_autodetect_origin_45_aziumth(self):
def test_autodetect_origin_85_aziumth(self):
rcm8cube = DataCube(golf_path)
rcm8cube.register_section("test3", RadialSection(azimuth=85))
_cshp, L0 = rcm8cube.shape, float(rcm8cube.meta["L0"])
_cshp, _ = rcm8cube.shape, float(rcm8cube.meta["L0"])
assert isinstance(rcm8cube.sections["test3"], RadialSection)
assert rcm8cube.sections["test3"].trace.shape[0] < _cshp[1] # slight oblique
assert (
Expand All @@ -575,7 +575,7 @@ def test_autodetect_origin_85_aziumth(self):
def test_autodetect_origin_115_aziumth(self):
rcm8cube = DataCube(golf_path)
rcm8cube.register_section("test4", RadialSection(azimuth=115))
_cshp, L0 = rcm8cube.shape, float(rcm8cube.meta["L0"])
_cshp, _ = rcm8cube.shape, float(rcm8cube.meta["L0"])
assert isinstance(rcm8cube.sections["test4"], RadialSection)
assert rcm8cube.sections["test4"].trace.shape[0] < _cshp[1] # slight oblique
assert (
Expand All @@ -589,7 +589,7 @@ def test_autodetect_origin_115_aziumth(self):
def test_autodetect_origin_165_aziumth(self):
rcm8cube = DataCube(golf_path)
rcm8cube.register_section("test5", RadialSection(azimuth=165))
_cshp, L0 = rcm8cube.shape, float(rcm8cube.meta["L0"])
_cshp, _ = rcm8cube.shape, float(rcm8cube.meta["L0"])
assert isinstance(rcm8cube.sections["test5"], RadialSection)
assert rcm8cube.sections["test5"].trace.shape[0] > _cshp[1] # obtuse
assert rcm8cube.sections["test5"]._dim2_idx[-1] == 0
Expand Down
2 changes: 1 addition & 1 deletion tests/test_strat.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def test_onedim_traj_upsanddowns_negatives(self):
z = _determine_strat_coordinates(e, dz=0.5) # vert coordinates
s, p = _compute_elevation_to_preservation(e)
sc, dc = _compute_preservation_to_cube(s, z)
c = self.take_var_time(s, z, sc, dc)
self.take_var_time(s, z, sc, dc)
assert np.all(p.nonzero()[0] == (4, 5, 9))


Expand Down
Loading