diff --git a/deltametrics/cube.py b/deltametrics/cube.py index bb5078a6..4c219c36 100644 --- a/deltametrics/cube.py +++ b/deltametrics/cube.py @@ -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 @@ -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}" diff --git a/deltametrics/io.py b/deltametrics/io.py index 5bdebcb8..362bc1b3 100644 --- a/deltametrics/io.py +++ b/deltametrics/io.py @@ -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] @@ -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] diff --git a/deltametrics/mask.py b/deltametrics/mask.py index 2ba59f92..c2a403f6 100644 --- a/deltametrics/mask.py +++ b/deltametrics/mask.py @@ -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): @@ -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] @@ -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] @@ -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": @@ -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] @@ -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": @@ -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) @@ -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": diff --git a/deltametrics/mobility.py b/deltametrics/mobility.py index c511166e..f95b495b 100644 --- a/deltametrics/mobility.py +++ b/deltametrics/mobility.py @@ -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 diff --git a/deltametrics/plan.py b/deltametrics/plan.py index 43f18eca..597d520e 100644 --- a/deltametrics/plan.py +++ b/deltametrics/plan.py @@ -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 diff --git a/deltametrics/plot.py b/deltametrics/plot.py index 0122558e..66fc38f7 100644 --- a/deltametrics/plot.py +++ b/deltametrics/plot.py @@ -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]] @@ -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 @@ -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 @@ -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 @@ -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: diff --git a/deltametrics/strat.py b/deltametrics/strat.py index 077dfceb..b0b05524 100644 --- a/deltametrics/strat.py +++ b/deltametrics/strat.py @@ -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`.') diff --git a/deltametrics/utils.py b/deltametrics/utils.py index ec211cda..f2a49dc2 100644 --- a/deltametrics/utils.py +++ b/deltametrics/utils.py @@ -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'): @@ -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 diff --git a/setup.cfg b/setup.cfg index 705629af..96a7a3ce 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [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, @@ -8,4 +8,3 @@ ignore = W504 max-line-length = 88 max-complexity = 18 -select = B,C,E,F,W,T4,B9 diff --git a/tests/cube_test.py b/tests/cube_test.py index 9f740d3f..73fad7a5 100644 --- a/tests/cube_test.py +++ b/tests/cube_test.py @@ -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` .*"): @@ -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) @@ -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` .*"): @@ -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) diff --git a/tests/io_test.py b/tests/io_test.py index 3688b83c..fb359f50 100644 --- a/tests/io_test.py +++ b/tests/io_test.py @@ -38,7 +38,7 @@ def empty_txt_file(tmp_path): def test_netcdf_io_init(): netcdf_io = NetCDFIO(golf_path, 'netcdf') assert netcdf_io.io_type == 'netcdf' - assert len(netcdf_io._in_memory_data.keys()) == 0 + assert len(netcdf_io._in_memory_data) == 0 def test_netcdf_io_init_legacy(): @@ -48,7 +48,7 @@ def test_netcdf_io_init_legacy(): with pytest.warns(UserWarning, match=r'No associated .*'): netcdf_io = NetCDFIO(rcm8_path, 'netcdf') assert netcdf_io.io_type == 'netcdf' - assert len(netcdf_io._in_memory_data.keys()) == 0 + assert len(netcdf_io._in_memory_data) == 0 def test_netcdf_io_keys(): @@ -81,9 +81,9 @@ def test_netcdf_io_intomemory_direct(): inmemory_size = sys.getsizeof(netcdf_io._in_memory_data) var = 'velocity' - assert len(netcdf_io._in_memory_data.keys()) == 0 + assert len(netcdf_io._in_memory_data) == 0 netcdf_io._in_memory_data[var] = np.array(netcdf_io.dataset.variables[var]) - assert len(netcdf_io._in_memory_data.keys()) == 1 + assert len(netcdf_io._in_memory_data) == 1 _arr = netcdf_io._in_memory_data[var] dataset_size_after = sys.getsizeof(netcdf_io.dataset) @@ -101,9 +101,9 @@ def test_netcdf_io_intomemory_read(): inmemory_size = sys.getsizeof(netcdf_io._in_memory_data) var = 'velocity' - assert len(netcdf_io._in_memory_data.keys()) == 0 + assert len(netcdf_io._in_memory_data) == 0 netcdf_io.read(var) - assert len(netcdf_io._in_memory_data.keys()) == 1 + assert len(netcdf_io._in_memory_data) == 1 _arr = netcdf_io._in_memory_data[var] assert isinstance(_arr, xr.core.dataarray.DataArray) @@ -119,7 +119,7 @@ def test_hdf5_io_init(): with pytest.warns(UserWarning, match=r'No associated .*'): netcdf_io = NetCDFIO(hdf_path, 'hdf5') assert netcdf_io.io_type == 'hdf5' - assert len(netcdf_io._in_memory_data.keys()) == 0 + assert len(netcdf_io._in_memory_data) == 0 def test_hdf5_io_keys(): @@ -150,7 +150,7 @@ def test_readvar_intomemory(): assert netcdf_io._in_memory_data == {} netcdf_io.read('eta') - assert ('eta' in netcdf_io._in_memory_data.keys()) is True + assert ('eta' in netcdf_io._in_memory_data) is True def test_readvar_intomemory_error(): @@ -164,7 +164,7 @@ def test_readvar_intomemory_error(): def test_netcdf_no_metadata(): # works fine, because there is no `connect` call in io init netcdf_io = NetCDFIO(golf_path, 'netcdf') - assert len(netcdf_io._in_memory_data.keys()) == 0 + assert len(netcdf_io._in_memory_data) == 0 class TestDictionaryIO: @@ -176,19 +176,19 @@ class TestDictionaryIO: def test_create_from_xarray_data(self): dict_io = DictionaryIO(self.dict_xr) - assert ('eta' in dict_io._in_memory_data.keys()) is True + assert ('eta' in dict_io._in_memory_data) is True assert isinstance(dict_io['eta'], xr.core.dataarray.DataArray) def test_dimensions_ignored_if_xarray(self): dict_io = DictionaryIO(self.dict_xr, dimensions=(3, 4, 5)) - assert ('eta' in dict_io._in_memory_data.keys()) is True + assert ('eta' in dict_io._in_memory_data) is True assert isinstance(dict_io['eta'], xr.core.dataarray.DataArray) def test_create_from_numpy_data_nodims(self): dict_io = DictionaryIO( self.dict_np) - assert ('eta' in dict_io._in_memory_data.keys()) is True - assert ('velocity' in dict_io._in_memory_data.keys()) is True + assert ('eta' in dict_io._in_memory_data) is True + assert ('velocity' in dict_io._in_memory_data) is True assert isinstance(dict_io['eta'], np.ndarray) assert isinstance(dict_io['dim0'], np.ndarray) @@ -198,8 +198,8 @@ def test_create_from_numpy_data_dimensions(self): 'time': np.arange(self._shape[0]), 'x': np.arange(self._shape[1]), 'y': np.arange(self._shape[2])}) - assert ('eta' in dict_io._in_memory_data.keys()) is True - assert ('velocity' in dict_io._in_memory_data.keys()) is True + assert ('eta' in dict_io._in_memory_data) is True + assert ('velocity' in dict_io._in_memory_data) is True assert isinstance(dict_io['eta'], np.ndarray) assert isinstance(dict_io['time'], np.ndarray) assert isinstance(dict_io['x'], np.ndarray) diff --git a/tests/section_test.py b/tests/section_test.py index 6995bbf1..b8ef67a9 100644 --- a/tests/section_test.py +++ b/tests/section_test.py @@ -888,14 +888,14 @@ def test_withstrat_SectionVariable_basic_math(self): def test_withstrat_strat_attr_mesh_components(self): sa = self.rcm8cube.sections["test"]["velocity"].strat.strat_attr - assert "strata" in sa.keys() - assert "psvd_idx" in sa.keys() - assert "psvd_flld" in sa.keys() - assert "x0" in sa.keys() - assert "x1" in sa.keys() - assert "s" in sa.keys() - assert "s_sp" in sa.keys() - assert "z_sp" in sa.keys() + assert "strata" in sa + assert "psvd_idx" in sa + assert "psvd_flld" in sa + assert "x0" in sa + assert "x1" in sa + assert "s" in sa + assert "s_sp" in sa + assert "z_sp" in sa def test_withstrat_strat_attr_shapes(self): sa = self.rcm8cube.sections["test"]["velocity"].strat.strat_attr