Skip to content

Commit

Permalink
Merge pull request #191 from mcflugen/mcflugen/add-flake8-simplify
Browse files Browse the repository at this point in the history
Add linters to deltametrics: flake8-simplify
  • Loading branch information
mcflugen authored Dec 20, 2024
2 parents 9639f52 + 683a7cd commit 75edf17
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 137 deletions.
7 changes: 2 additions & 5 deletions deltametrics/cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ def show_plan(self, *args, **kwargs):
stacklevel=2,
)
# pass `t` arg to `idx` for legacy
if "t" in kwargs.keys():
if "t" in kwargs:
idx = kwargs.pop("t")
kwargs["idx"] = idx

Expand Down Expand Up @@ -746,13 +746,10 @@ def __getitem__(self, var):
dims=self._view_dimensions,
)
_obj = _xrt
elif var in self._coords:
elif (var in self._coords) or (var in self._variables):
# ensure coords can be called by cube[var]
_obj = self._dataio.dataset[var]

elif var in self._variables:
_obj = self._dataio.dataset[var]

else:
raise AttributeError(
f"No variable of {str(self)} named {var}"
Expand Down
4 changes: 2 additions & 2 deletions deltametrics/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def write(self):
raise NotImplementedError

def __getitem__(self, var):
if var in self._in_memory_data.keys():
if var in self._in_memory_data:
return self._in_memory_data[var]
else:
return self.dataset[var]
Expand Down Expand Up @@ -455,7 +455,7 @@ def __getitem__(self, var):
Returns the variables exactly as they are: either a numpy ndarray or
xarray.
"""
if var in self.dataset.keys():
if var in self.dataset:
return self.dataset[var]
elif var in self.known_coords:
return self.dimensions[var]
Expand Down
93 changes: 27 additions & 66 deletions deltametrics/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,13 +284,12 @@ def _check_deprecated_is_mask(self, is_mask):
)

def _check_deprecated_3d_input(self, args_0_shape):
if self._input_flag == "array":
if len(args_0_shape) > 2:
raise ValueError(
"Creating a `Mask` with a time dimension is deprecated. "
"Please manage multiple masks manually (e.g., "
"append the masks into a `list`)."
)
if (self._input_flag == "array") and (len(args_0_shape) > 2):
raise ValueError(
"Creating a `Mask` with a time dimension is deprecated. "
"Please manage multiple masks manually (e.g., "
"append the masks into a `list`)."
)


class ThresholdValueMask(BaseMask, abc.ABC):
Expand Down Expand Up @@ -707,18 +706,13 @@ def __init__(self, *args, is_mask=None, **kwargs):
# do nothing, will need to call ._compute_mask later
return

elif self._input_flag == "cube":
elif self._input_flag in ("cube", "mask"):
raise NotImplementedError
# _tval = kwargs.pop('t', -1)
# _eta = args[0]['eta'][_tval, :, :]
# _flow = args[0]['velocity'][_tval, :, :]
# need to convert these fields to proper masks

elif self._input_flag == "mask":
# this pathway should allow someone to specify a combination of
# elevation mask, landmask, and velocity mask to make the new mask.
raise NotImplementedError

elif self._input_flag == "array":
# first make a landmask
_eta = args[0]
Expand Down Expand Up @@ -927,13 +921,7 @@ def __init__(self, *args, **kwargs):
if self._input_flag is None:
# do nothing, will need to call ._compute_mask later
return
elif self._input_flag == "cube":
raise NotImplementedError
# _tval = kwargs.pop('t', -1)
# _eta = args[0]['eta'][_tval, :, :]
elif self._input_flag == "mask":
# this pathway should allow someone to specify a combination of
# landmask, and ocean/elevation mask
elif self._input_flag in ("cube", "mask"):
raise NotImplementedError
elif self._input_flag == "array":
_eta = args[0]
Expand Down Expand Up @@ -1171,12 +1159,7 @@ def __init__(self, *args, contour_threshold=75, method="OAM", **kwargs):
# do nothing, will need to call ._compute_mask later
return

elif self._input_flag == "cube":
raise NotImplementedError
# _tval = kwargs.pop('t', -1)
# _eta = args[0]['eta'][_tval, :, :]

elif self._input_flag == "mask":
elif self._input_flag in ("cube", "mask"):
raise NotImplementedError

elif self._input_flag == "array":
Expand Down Expand Up @@ -1440,17 +1423,16 @@ def _compute_mask(self, *args, **kwargs):
from deltametrics.plan import OpeningAnglePlanform

# handle types / input arguments
if len(args) <= 2:
if len(args) == 1:
if isinstance(args[0], OpeningAnglePlanform):
_below_mask = args[0]._below_mask
_opening_angles = args[0]._opening_angles
_method = "OAM"
elif isinstance(args[0], MorphologicalPlanform):
_elev_mask = args[0]._elevation_mask
_mean_image = args[0]._mean_image
_method = "MPM"
if len(args) >= 3:
if len(args) == 1:
if isinstance(args[0], OpeningAnglePlanform):
_below_mask = args[0]._below_mask
_opening_angles = args[0]._opening_angles
_method = "OAM"
elif isinstance(args[0], MorphologicalPlanform):
_elev_mask = args[0]._elevation_mask
_mean_image = args[0]._mean_image
_method = "MPM"
elif len(args) >= 3:
_method = args[2]
if _method == "OAM":
_below_mask = args[0]
Expand Down Expand Up @@ -2020,18 +2002,7 @@ def __init__(self, *args, method="skeletonize", **kwargs):
# do nothing, will need to call ._compute_mask later
return

elif self._input_flag == "cube":
raise NotImplementedError
# _tval = kwargs.pop('t', -1)
# _eta = args[0]['eta'][_tval, :, :]
# _flow = args[0]['velocity'][_tval, :, :]
# need to convert these fields to proper masks

elif self._input_flag == "mask":
# this pathway should allow someone to specify a combination of
# elevation mask, landmask, and velocity mask or channelmask
# directly, to make the new mask. This is basically an ambiguous
# definition of the static methods.
elif self._input_flag in ("cube", "mask"):
raise NotImplementedError

elif self._input_flag == "array":
Expand Down Expand Up @@ -2279,13 +2250,12 @@ def __init__(self, *args, origin=None, **kwargs):
operation: :obj:`angular`, :obj:`circular`, :obj:`strike`,
and :obj:`dip`.
"""
if len(args) > 0:
# most argument are fine, but we need to convert an input tuple
# (specific only to GeometricMask type) into an array to be the
# basis.
if isinstance(args[0], tuple):
# args[0] = np.zeros(args[0])
args = (np.zeros(args[0]),)
# most argument are fine, but we need to convert an input tuple
# (specific only to GeometricMask type) into an array to be the
# basis.
if (len(args) > 0) and isinstance(args[0], tuple):
# args[0] = np.zeros(args[0])
args = (np.zeros(args[0]),)

super().__init__("geometric", *args, **kwargs)

Expand Down Expand Up @@ -2687,16 +2657,7 @@ def __init__(self, *args, background_value=0, elevation_tolerance=0.1, **kwargs)
# do nothing, will need to call ._compute_mask later
return

elif self._input_flag == "cube":
raise NotImplementedError
# _tval = kwargs.pop('t', -1)
# _eta = args[0]['eta'][_tval, :, :]
# _flow = args[0]['velocity'][_tval, :, :]
# need to convert these fields to proper masks

elif self._input_flag == "mask":
# this pathway should allow someone to specify a combination of
# elevation mask, landmask, and velocity mask to make the new mask.
elif self._input_flag in ("cube", "mask"):
raise NotImplementedError

elif self._input_flag == "array":
Expand Down
8 changes: 5 additions & 3 deletions deltametrics/mobility.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,11 @@ def check_inputs(chmap, basevalues=None, basevalues_idx=None, window=None,
raise ValueError('No window or window_idx supplied!')

# check map shapes align
if out_maps['landmap'] is not None:
if np.shape(out_maps['chmap']) != np.shape(out_maps['landmap']):
raise ValueError('Shapes of chmap and landmap do not match.')
if (
(out_maps['landmap'] is not None)
and (np.shape(out_maps['chmap']) != np.shape(out_maps['landmap']))
):
raise ValueError('Shapes of chmap and landmap do not match.')

# check that the combined basemap + timewindow does not exceed max t-index
Kmax = np.max(base_out) + win_out
Expand Down
4 changes: 1 addition & 3 deletions deltametrics/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -2047,9 +2047,7 @@ def morphological_closing_method(elevationmask, biggestdisk=None):
)

# check biggestdisk
if biggestdisk is None:
biggestdisk = 1
elif biggestdisk <= 0:
if (biggestdisk is None) or (biggestdisk <= 0):
biggestdisk = 1

# loop through and do binary closing for each disk size up to biggestdisk
Expand Down
25 changes: 13 additions & 12 deletions deltametrics/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,9 +881,10 @@ def get_display_arrays(VarInst, data=None):
elif VarInst.slicetype == "stratigraphy_section":
# # StratigraphySection # #
data = data or "stratigraphy"
if data in VarInst.strat._spacetime_names:
VarInst.strat._check_knows_spacetime() # always False
elif data in VarInst.strat._preserved_names:
if (
(data in VarInst.strat._spacetime_names)
or (data in VarInst.strat._preserved_names)
):
VarInst.strat._check_knows_spacetime() # always False
elif data in VarInst.strat._stratigraphy_names:
_z = VarInst[VarInst.dims[0]]
Expand Down Expand Up @@ -968,9 +969,10 @@ def _reshape_long(X):
elif VarInst.slicetype == "stratigraphy_section":
# # StratigraphySection # #
data = data or "stratigraphy"
if data in VarInst.strat._spacetime_names:
VarInst.strat._check_knows_spacetime() # always False
elif data in VarInst.strat._preserved_names:
if (
(data in VarInst.strat._spacetime_names)
or (data in VarInst.strat._preserved_names)
):
VarInst.strat._check_knows_spacetime() # always False
elif data in VarInst.strat._stratigraphy_names:
raise NotImplementedError # not sure best implementation
Expand Down Expand Up @@ -1034,9 +1036,10 @@ def get_display_limits(VarInst, data=None, factor=1.5):
# # StratigraphySection # #
data = data or "stratigraphy"
_S, _Z = np.meshgrid(VarInst["s"], VarInst[VarInst.dims[0]])
if data in VarInst.strat._spacetime_names:
VarInst.strat._check_knows_spacetime() # always False
elif data in VarInst.strat._preserved_names:
if (
(data in VarInst.strat._spacetime_names)
or (data in VarInst.strat._preserved_names)
):
VarInst.strat._check_knows_spacetime() # always False
elif data in VarInst.strat._stratigraphy_names:
return np.min(_S), np.max(_S), np.min(_Z), np.max(_Z) * factor
Expand Down Expand Up @@ -1593,7 +1596,7 @@ def overlay_sparse_array(
fig, ax = plt.subplots()

# check this is a tuple or list
if isinstance(alpha_clip, tuple) or isinstance(alpha_clip, list):
if isinstance(alpha_clip, (tuple, list)):
if len(alpha_clip) != 2:
raise ValueError("`alpha_clip` must be tuple or list of length 2.")
else: # if it is a tuple, check the length
Expand All @@ -1614,8 +1617,6 @@ def overlay_sparse_array(
if isinstance(cmap, str):
# cmap = plt.cm.get_cmap(cmap)
cmap = mpl.colormaps[cmap]
else:
cmap = cmap

# get the extent to plot
if "extent" in kwargs:
Expand Down
6 changes: 3 additions & 3 deletions deltametrics/strat.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def _determine_deposit_from_background(sediment_volume, background):
>>> _ = ax[1, 1].imshow(background2[59], cmap='Greys_r') # just below initial basin depth
>>> plt.tight_layout()
"""
if (background is None):
if background is None:
deposit = np.ones(sediment_volume.shape, dtype=bool)
elif (isinstance(background, float) or isinstance(background, int)):
elif isinstance(background, (float, int)):
deposit = (sediment_volume != background)
elif (isinstance(background, np.ndarray)):
elif isinstance(background, np.ndarray):
deposit = ~background.astype(bool) # ensure boolean
else:
raise TypeError('Invalid type for `background`.')
Expand Down
20 changes: 10 additions & 10 deletions deltametrics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,7 @@ def _attribute_checker(self, checklist):
def is_ndarray_or_xarray(data):
"""Check that data is numpy array or xarray data.
"""
truth = (isinstance(data, xr.core.dataarray.DataArray) or
isinstance(data, np.ndarray))
return truth
return isinstance(data, (xr.core.dataarray.DataArray, np.ndarray))


def curve_fit(data, fit='harmonic'):
Expand Down Expand Up @@ -518,13 +516,15 @@ def _point_in_polygon(x, y, polygon):
p1x, p1y = polygon[0]
for i in range(n+1):
p2x, p2y = polygon[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
if (
(y > min(p1y, p2y))
and (y <= max(p1y, p2y))
and (x <= max(p1x, p2x))
):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x, p1y = p2x, p2y

return inside
Expand Down
3 changes: 1 addition & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
[flake8]
exclude = docs/source/pyplots/guides, build, .nox
ignore =
extend-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
16 changes: 8 additions & 8 deletions tests/cube_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ def test_register_section(self):
golf.stratigraphy_from("eta", dz=0.1)
golf.register_section("testsection", StrikeSection(distance_idx=10))
assert golf.sections is golf.section_set
assert len(golf.sections.keys()) == 1
assert "testsection" in golf.sections.keys()
assert len(golf.sections) == 1
assert "testsection" in golf.sections
with pytest.raises(TypeError, match=r"`SectionInstance` .*"):
golf.register_section("fail1", "astring")
with pytest.raises(TypeError, match=r"`SectionInstance` .*"):
Expand All @@ -115,7 +115,7 @@ def test_sections_slice_op(self):
golf = DataCube(golf_path)
golf.stratigraphy_from("eta", dz=0.1)
golf.register_section("testsection", StrikeSection(distance_idx=10))
assert "testsection" in golf.sections.keys()
assert "testsection" in golf.sections
slc = golf.sections["testsection"]
assert issubclass(type(slc), BaseSection)

Expand All @@ -124,8 +124,8 @@ def test_register_planform(self):
golf.stratigraphy_from("eta", dz=0.1)
golf.register_planform("testplanform", Planform(idx=10))
assert golf.planforms is golf.planform_set
assert len(golf.planforms.keys()) == 1
assert "testplanform" in golf.planforms.keys()
assert len(golf.planforms) == 1
assert "testplanform" in golf.planforms
with pytest.raises(TypeError, match=r"`PlanformInstance` .*"):
golf.register_planform("fail1", "astring")
with pytest.raises(TypeError, match=r"`PlanformInstance` .*"):
Expand All @@ -142,14 +142,14 @@ def test_register_plan_legacy_method(self):
golf = DataCube(golf_path)
golf.register_plan("testplanform", Planform(idx=10))
assert golf.planforms is golf.planform_set
assert len(golf.planforms.keys()) == 1
assert "testplanform" in golf.planforms.keys()
assert len(golf.planforms) == 1
assert "testplanform" in golf.planforms

def test_planforms_slice_op(self):
golf = DataCube(golf_path)
golf.stratigraphy_from("eta", dz=0.1)
golf.register_planform("testplanform", Planform(idx=10))
assert "testplanform" in golf.planforms.keys()
assert "testplanform" in golf.planforms
slc = golf.planforms["testplanform"]
assert issubclass(type(slc), BasePlanform)

Expand Down
Loading

0 comments on commit 75edf17

Please sign in to comment.