From b142b081516e6ac78e426257c7472dd4a9994b89 Mon Sep 17 00:00:00 2001 From: wpbonelli Date: Thu, 14 Mar 2024 15:43:53 -0400 Subject: [PATCH] chore: switch to ruff, ignore known test warnings, numpy compat fixes (#2124) * switch to ruff from black, isort, flake8, pylint, keep (mostly) the same settings * apply some suggested linting/formatting rules, ignore others in pyproject.toml * run ruff check --select NPY201 as suggested here, replace deprecated syntax * np.float_ -> np.float64 * np.NaN -> np.nan * ignore well-known python-dateutil and pandas warnings --- .../modflow_postprocessing_example.py | 2 +- .../modpath7_unstructured_lateral_example.py | 2 +- .docs/Notebooks/plot_cross_section_example.py | 5 ++- .docs/Notebooks/plot_map_view_example.py | 12 +++-- .docs/Notebooks/swi2package_example3.py | 2 +- .github/workflows/commit.yml | 28 ++---------- autotest/pytest.ini | 7 ++- autotest/regression/conftest.py | 4 +- autotest/regression/test_mf6.py | 26 +++++------ autotest/test_copy.py | 13 +++--- autotest/test_export.py | 2 +- autotest/test_get_modflow.py | 1 + autotest/test_grid.py | 2 +- autotest/test_gridintersect.py | 44 ++++++++++++++----- autotest/test_hydmodfile.py | 16 ++----- autotest/test_mf6.py | 8 ++-- autotest/test_mfsimlist.py | 4 +- autotest/test_plot_cross_section.py | 2 +- autotest/test_plot_map_view.py | 2 +- autotest/test_specific_discharge.py | 2 +- autotest/test_util_geometry.py | 2 +- autotest/test_uzf.py | 4 +- flopy/discretization/unstructuredgrid.py | 2 +- flopy/export/longnames.py | 2 +- flopy/export/netcdf.py | 11 +++-- flopy/export/unitsformat.py | 2 +- flopy/export/utils.py | 36 +++++++-------- flopy/export/vtk.py | 2 +- flopy/mbase.py | 4 +- flopy/mf6/coordinates/modeldimensions.py | 4 +- flopy/mf6/coordinates/modelgrid.py | 7 +-- flopy/mf6/data/mfdata.py | 2 +- flopy/mf6/data/mfdataarray.py | 23 +++++----- flopy/mf6/data/mfdatalist.py | 11 ++--- flopy/mf6/data/mfdataplist.py | 7 +-- flopy/mf6/data/mfdatascalar.py | 16 +++---- flopy/mf6/data/mfdatastorage.py | 39 ++++++++-------- flopy/mf6/data/mfdatautil.py | 6 +-- flopy/mf6/data/mffileaccess.py | 18 +++----- flopy/mf6/data/mfstructure.py | 6 +-- flopy/mf6/mfbase.py | 2 +- flopy/mf6/mfmodel.py | 8 ++-- flopy/mf6/mfpackage.py | 23 +++++----- flopy/mf6/mfsimbase.py | 6 +-- flopy/mf6/modflow/__init__.py | 1 - flopy/mf6/utils/createpackages.py | 7 +-- flopy/mf6/utils/model_splitter.py | 16 +++---- flopy/mf6/utils/output_util.py | 8 +--- flopy/mf6/utils/testutils.py | 3 +- flopy/mfusg/mfusgcln.py | 1 + flopy/mfusg/mfusgsms.py | 1 + flopy/modflow/mfbcf.py | 6 +-- flopy/modflow/mfdis.py | 4 +- flopy/modflow/mfdrn.py | 4 +- flopy/modflow/mfdrt.py | 4 +- flopy/modflow/mffhb.py | 15 ++++--- flopy/modflow/mfghb.py | 4 +- flopy/modflow/mflak.py | 5 ++- flopy/modflow/mflpf.py | 6 +-- flopy/modflow/mfmnw2.py | 4 +- flopy/modflow/mfoc.py | 6 +-- flopy/modflow/mfpar.py | 2 +- flopy/modflow/mfpks.py | 2 +- flopy/modflow/mfsfr2.py | 4 +- flopy/modflow/mfswi2.py | 2 +- flopy/modpath/mp6.py | 2 +- flopy/modpath/mp6bas.py | 6 +-- flopy/modpath/mp7particledata.py | 10 ++--- flopy/mt3d/mtbtn.py | 17 +++---- flopy/mt3d/mtlkt.py | 2 +- flopy/mt3d/mtsft.py | 2 +- flopy/mt3d/mtssm.py | 8 ++-- flopy/mt3d/mtuzt.py | 2 +- flopy/pakbase.py | 6 +-- flopy/plot/__init__.py | 28 ++++++------ flopy/plot/crosssection.py | 2 +- flopy/plot/plotutil.py | 12 +++-- flopy/utils/__init__.py | 28 ++++++------ flopy/utils/compare.py | 2 +- flopy/utils/crs.py | 3 +- flopy/utils/datafile.py | 2 +- flopy/utils/flopy_io.py | 4 +- flopy/utils/get_modflow.py | 1 + flopy/utils/gridutil.py | 4 +- flopy/utils/mflistfile.py | 16 +++---- flopy/utils/rasters.py | 4 +- flopy/utils/recarray_utils.py | 2 +- flopy/utils/util_array.py | 2 +- flopy/utils/util_list.py | 10 ++--- pyproject.toml | 37 +++++++++++----- scripts/process_benchmarks.py | 2 +- scripts/update_version.py | 4 +- 92 files changed, 375 insertions(+), 375 deletions(-) diff --git a/.docs/Notebooks/modflow_postprocessing_example.py b/.docs/Notebooks/modflow_postprocessing_example.py index 98259ce3aa..656aef5d44 100644 --- a/.docs/Notebooks/modflow_postprocessing_example.py +++ b/.docs/Notebooks/modflow_postprocessing_example.py @@ -100,7 +100,7 @@ grid, os.path.join(workspace, "heads5_rot.tif"), hdslayer, nodata=nodata ) -results = np.loadtxt(os.path.join(workspace, f"heads5_rot.asc"), skiprows=6) +results = np.loadtxt(os.path.join(workspace, "heads5_rot.asc"), skiprows=6) results[results == nodata] = np.nan plt.imshow(results) plt.colorbar() diff --git a/.docs/Notebooks/modpath7_unstructured_lateral_example.py b/.docs/Notebooks/modpath7_unstructured_lateral_example.py index 22ccf7a478..9b3f85c3b1 100644 --- a/.docs/Notebooks/modpath7_unstructured_lateral_example.py +++ b/.docs/Notebooks/modpath7_unstructured_lateral_example.py @@ -436,7 +436,7 @@ sim.set_sim_path(workspace) sim.write_simulation() success, buff = sim.run_simulation(silent=True, report=True) -assert success, f"Failed to run MF6 simulation." +assert success, "Failed to run MF6 simulation." for line in buff: print(line) diff --git a/.docs/Notebooks/plot_cross_section_example.py b/.docs/Notebooks/plot_cross_section_example.py index 00848cd277..e253379404 100644 --- a/.docs/Notebooks/plot_cross_section_example.py +++ b/.docs/Notebooks/plot_cross_section_example.py @@ -341,7 +341,10 @@ # Plot a shapefile of shp = os.path.join(loadpth, "gis", "bedrock_outcrop_hole_rotate14") patch_collection = mapview.plot_shapefile( - shp, edgecolor="green", linewidths=2, alpha=0.5 # facecolor='none', + shp, + edgecolor="green", + linewidths=2, + alpha=0.5, # facecolor='none', ) # Plot a shapefile of a cross-section line shp = os.path.join(loadpth, "gis", "cross_section_rotate14") diff --git a/.docs/Notebooks/plot_map_view_example.py b/.docs/Notebooks/plot_map_view_example.py index e50a65580c..d52969e4f4 100644 --- a/.docs/Notebooks/plot_map_view_example.py +++ b/.docs/Notebooks/plot_map_view_example.py @@ -452,7 +452,10 @@ # Plot a shapefile of shp = os.path.join(loadpth, "gis", "bedrock_outcrop_hole") patch_collection = mapview.plot_shapefile( - shp, edgecolor="green", linewidths=2, alpha=0.5 # facecolor='none', + shp, + edgecolor="green", + linewidths=2, + alpha=0.5, # facecolor='none', ) # Plot a shapefile of a cross-section line shp = os.path.join(loadpth, "gis", "cross_section") @@ -488,7 +491,10 @@ # Plot a shapefile of shp = os.path.join(loadpth, "gis", "bedrock_outcrop_hole_rotate14") patch_collection = mapview.plot_shapefile( - shp, edgecolor="green", linewidths=2, alpha=0.5 # facecolor='none', + shp, + edgecolor="green", + linewidths=2, + alpha=0.5, # facecolor='none', ) # Plot a shapefile of a cross-section line shp = os.path.join(loadpth, "gis", "cross_section_rotate14") @@ -1024,7 +1030,7 @@ def load_iverts(fname): plt.colorbar(quadmesh, shrink=0.75) # change the font type to comic sans - styles.set_font_type(family="fantasy", fontname="Comic Sans MS"), + (styles.set_font_type(family="fantasy", fontname="Comic Sans MS"),) # use styles to add a heading, xlabel, ylabel, and remove tick marks styles.heading( diff --git a/.docs/Notebooks/swi2package_example3.py b/.docs/Notebooks/swi2package_example3.py index 415df76f50..4b0486d14f 100644 --- a/.docs/Notebooks/swi2package_example3.py +++ b/.docs/Notebooks/swi2package_example3.py @@ -80,7 +80,7 @@ def MergeData(ndim, zdata, tb): found.fill(False) for idx, layer in enumerate(zdata): for jdx, z in enumerate(layer): - if found[jdx] == True: + if found[jdx] is True: continue t0 = tb[idx][0] - sv t1 = tb[idx][1] + sv diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index b549d7e640..29da178352 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -61,31 +61,11 @@ jobs: pip install . pip install ".[lint]" - - name: Run isort - run: | - echo "if isort check fails update isort using" - echo " pip install isort --upgrade" - echo "and run" - echo " isort ./flopy" - echo "and then commit the changes." - isort --check --diff ./flopy - - - name: Run black - run: | - echo "if black check fails update black using" - echo " pip install black --upgrade" - echo "and run" - echo " black ./flopy" - echo "and then commit the changes." - black --check --diff ./flopy - - - name: Run flake8 - run: | - flake8 --count --show-source --exit-zero ./flopy + - name: Lint + run: ruff check . - - name: Run pylint - run: | - pylint --jobs=2 --errors-only --exit-zero ./flopy + - name: Check format + run: ruff format . --check - name: Check CITATION.cff run: | diff --git a/autotest/pytest.ini b/autotest/pytest.ini index c94efd1f32..0bd2bad2e5 100644 --- a/autotest/pytest.ini +++ b/autotest/pytest.ini @@ -15,4 +15,9 @@ markers = meta: tests run by other tests mf6: tests for MODFLOW 6 support regression: tests comparing multiple versions - slow: tests not completing in a few seconds \ No newline at end of file + slow: tests not completing in a few seconds +filterwarnings = + # from python-dateutil, used by arrow, jupyter_client, matplotlib, pandas + ignore:datetime.datetime.utcfromtimestamp + # from pandas, see https://github.com/pandas-dev/pandas/issues/54466 + ignore:\n.*Pyarrow \ No newline at end of file diff --git a/autotest/regression/conftest.py b/autotest/regression/conftest.py index 685c0f7a2f..66c064645f 100644 --- a/autotest/regression/conftest.py +++ b/autotest/regression/conftest.py @@ -18,10 +18,10 @@ def get_mf6_examples_path() -> Path: __mf6_examples_lock.acquire() try: if __mf6_examples_path.is_dir() and any(__mf6_examples_path.glob("*")): - print(f"Example models already exist") + print("Example models already exist") else: __mf6_examples_path.mkdir(exist_ok=True) - print(f"Downloading example models") + print("Downloading example models") download_and_unzip( url="https://github.com/MODFLOW-USGS/modflow6-examples/releases/download/current/modflow6-examples.zip", path=str(__mf6_examples_path), diff --git a/autotest/regression/test_mf6.py b/autotest/regression/test_mf6.py index 417a547e7b..9c98504631 100644 --- a/autotest/regression/test_mf6.py +++ b/autotest/regression/test_mf6.py @@ -299,7 +299,7 @@ def test_np001(function_tmpdir, example_data_path): ) except FlopyException: ex = True - assert ex == True + assert ex is True kwargs = {} kwargs["xul"] = 20.5 @@ -855,9 +855,9 @@ def test_np002(function_tmpdir, example_data_path): sim.simulation_data.max_columns_of_data = 22 name = sim.name_file - assert name.continue_.get_data() == None - assert name.nocheck.get_data() == True - assert name.memory_print_option.get_data() == None + assert name.continue_.get_data() is None + assert name.nocheck.get_data() is True + assert name.memory_print_option.get_data() is None tdis_rc = [(6.0, 2, 1.0), (6.0, 3, 1.0)] tdis_package = ModflowTdis( @@ -1885,7 +1885,7 @@ def test005_create_tests_advgw_tidal(function_tmpdir, example_data_path): assert model.name_file.filename == "new_name.nam" package_type_dict = {} for package in model.packagelist: - if not package.package_type in package_type_dict: + if package.package_type not in package_type_dict: filename = os.path.split(package.filename)[1] assert filename == f"new_name.{package.package_type}" package_type_dict[package.package_type] = 1 @@ -1901,7 +1901,7 @@ def test005_create_tests_advgw_tidal(function_tmpdir, example_data_path): sim.rename_all_packages("all_files_same_name") package_type_dict = {} for package in model.packagelist: - if not package.package_type in package_type_dict: + if package.package_type not in package_type_dict: filename = os.path.split(package.filename)[1] assert filename == f"all_files_same_name.{package.package_type}" package_type_dict[package.package_type] = 1 @@ -2220,9 +2220,9 @@ def test035_create_tests_fhb(function_tmpdir, example_data_path): ) time = model.modeltime assert ( - time.steady_state[0] == False - and time.steady_state[1] == False - and time.steady_state[2] == False + time.steady_state[0] is False + and time.steady_state[1] is False + and time.steady_state[2] is False ) wel_period = {0: [((0, 1, 0), "flow")]} wel_package = ModflowGwfwel( @@ -3771,10 +3771,10 @@ def test005_advgw_tidal(function_tmpdir, example_data_path): model = sim.get_model(model_name) time = model.modeltime assert ( - time.steady_state[0] == True - and time.steady_state[1] == False - and time.steady_state[2] == False - and time.steady_state[3] == False + time.steady_state[0] is True + and time.steady_state[1] is False + and time.steady_state[2] is False + and time.steady_state[3] is False ) ghb = model.get_package("ghb") obs = ghb.obs diff --git a/autotest/test_copy.py b/autotest/test_copy.py index 476a560ab5..52072ad15b 100644 --- a/autotest/test_copy.py +++ b/autotest/test_copy.py @@ -1,5 +1,4 @@ -"""Test copying of flopy objects. -""" +"""Test copying of flopy objects.""" import copy import inspect @@ -64,10 +63,10 @@ def model_is_copy(m1, m2): continue elif k not in m2.__dict__: return False - elif type(v) == bool: + elif isinstance(v, bool): if not v == v2: return False - elif type(v) in [str, int, float, dict, list]: + elif isinstance(v, (str, int, float, dict, list)): if v != v2: return False continue @@ -118,13 +117,13 @@ def package_is_copy(pk1, pk2): return False elif k not in pk2.__dict__: return False - elif type(v) == bool: + elif isinstance(v, bool): if not v == v2: return False - elif type(v) in [str, int, float, dict]: + elif isinstance(v, (str, int, float, dict)): if v != v2: return False - elif type(v) == list: + elif isinstance(v, list): for item, item2 in zip(v, v2): if not isinstance(item, MFPackage): if item != item2: diff --git a/autotest/test_export.py b/autotest/test_export.py index 1b5e607bd1..b5c7a26a1e 100644 --- a/autotest/test_export.py +++ b/autotest/test_export.py @@ -520,7 +520,7 @@ def test_shapefile_ibound(function_tmpdir, example_data_path): field_names = [item[0] for item in shape.fields][1:] ib_idx = field_names.index("ibound_1") txt = f"should be int instead of {type(shape.record(0)[ib_idx])}" - assert type(shape.record(0)[ib_idx]) == int, txt + assert isinstance(shape.record(0)[ib_idx], int), txt shape.close() diff --git a/autotest/test_get_modflow.py b/autotest/test_get_modflow.py index bd5e9cfcce..e243992df5 100644 --- a/autotest/test_get_modflow.py +++ b/autotest/test_get_modflow.py @@ -1,4 +1,5 @@ """Test get-modflow utility.""" + import os import platform import sys diff --git a/autotest/test_grid.py b/autotest/test_grid.py index 7bf27622e0..4212f1f132 100644 --- a/autotest/test_grid.py +++ b/autotest/test_grid.py @@ -1119,7 +1119,7 @@ def test_voronoi_grid(request, function_tmpdir, grid_info): # ensure proper number of cells almost_right = ncpl == 538 and gridprops["ncpl"] == 535 if almost_right: - warn(f"off-by-3") + warn("off-by-3") # ensure that all cells have 3 or more points invalid_cells = [i for i, ivts in enumerate(vor.iverts) if len(ivts) < 3] diff --git a/autotest/test_gridintersect.py b/autotest/test_gridintersect.py index 983e3771c4..dc7a7656f1 100644 --- a/autotest/test_gridintersect.py +++ b/autotest/test_gridintersect.py @@ -135,7 +135,9 @@ def test_rect_grid_3d_point_outside(): @requires_pkg("shapely") def test_rect_grid_3d_point_inside(): - botm = np.concatenate([np.ones(4), 0.5 * np.ones(4), np.zeros(4)]).reshape(3, 2, 2) + botm = np.concatenate([np.ones(4), 0.5 * np.ones(4), np.zeros(4)]).reshape( + 3, 2, 2 + ) gr = get_rect_grid(top=np.ones(4), botm=botm) ix = GridIntersect(gr, method="structured") result = ix.intersect(Point(2.0, 2.0, 0.2)) @@ -454,7 +456,9 @@ def test_rect_grid_linestring_in_and_out_of_cell(): def test_rect_grid_linestring_in_and_out_of_cell2(): gr = get_rect_grid() ix = GridIntersect(gr, method="structured") - result = ix.intersect(LineString([(5, 15), (5.0, 9), (15.0, 5.0), (5.0, 1.0)])) + result = ix.intersect( + LineString([(5, 15), (5.0, 9), (15.0, 5.0), (5.0, 1.0)]) + ) assert len(result) == 3 # assert result.cellids[0] == (1, 0) # assert result.cellids[1] == (1, 1) @@ -751,7 +755,9 @@ def test_rect_grid_polygon_outside(): def test_rect_grid_polygon_in_2cells(): gr = get_rect_grid() ix = GridIntersect(gr, method="structured") - result = ix.intersect(Polygon([(2.5, 5.0), (7.5, 5.0), (7.5, 15.0), (2.5, 15.0)])) + result = ix.intersect( + Polygon([(2.5, 5.0), (7.5, 5.0), (7.5, 15.0), (2.5, 15.0)]) + ) assert len(result) == 2 assert result.areas.sum() == 50.0 @@ -788,7 +794,9 @@ def test_rect_grid_polygon_running_along_boundary(): def test_rect_grid_polygon_on_inner_boundary(): gr = get_rect_grid() ix = GridIntersect(gr, method="structured") - result = ix.intersect(Polygon([(5.0, 10.0), (15.0, 10.0), (15.0, 5.0), (5.0, 5.0)])) + result = ix.intersect( + Polygon([(5.0, 10.0), (15.0, 10.0), (15.0, 5.0), (5.0, 5.0)]) + ) assert len(result) == 2 assert result.areas.sum() == 50.0 @@ -969,7 +977,9 @@ def test_rect_grid_polygon_outside_shapely(rtree): def test_rect_grid_polygon_in_2cells_shapely(rtree): gr = get_rect_grid() ix = GridIntersect(gr, method="vertex", rtree=rtree) - result = ix.intersect(Polygon([(2.5, 5.0), (7.5, 5.0), (7.5, 15.0), (2.5, 15.0)])) + result = ix.intersect( + Polygon([(2.5, 5.0), (7.5, 5.0), (7.5, 15.0), (2.5, 15.0)]) + ) assert len(result) == 2 assert result.areas.sum() == 50.0 @@ -990,7 +1000,9 @@ def test_rect_grid_polygon_on_outer_boundary_shapely(rtree): def test_rect_grid_polygon_on_inner_boundary_shapely(rtree): gr = get_rect_grid() ix = GridIntersect(gr, method="vertex", rtree=rtree) - result = ix.intersect(Polygon([(5.0, 10.0), (15.0, 10.0), (15.0, 5.0), (5.0, 5.0)])) + result = ix.intersect( + Polygon([(5.0, 10.0), (15.0, 10.0), (15.0, 5.0), (5.0, 5.0)]) + ) assert len(result) == 2 assert result.areas.sum() == 50.0 @@ -1073,7 +1085,9 @@ def test_tri_grid_polygon_in_2cells(rtree): if gr == -1: return ix = GridIntersect(gr, rtree=rtree) - result = ix.intersect(Polygon([(2.5, 5.0), (5.0, 5.0), (5.0, 15.0), (2.5, 15.0)])) + result = ix.intersect( + Polygon([(2.5, 5.0), (5.0, 5.0), (5.0, 15.0), (2.5, 15.0)]) + ) assert len(result) == 2 assert result.areas.sum() == 25.0 @@ -1098,7 +1112,9 @@ def test_tri_grid_polygon_on_inner_boundary(rtree): if gr == -1: return ix = GridIntersect(gr, rtree=rtree) - result = ix.intersect(Polygon([(5.0, 10.0), (15.0, 10.0), (15.0, 5.0), (5.0, 5.0)])) + result = ix.intersect( + Polygon([(5.0, 10.0), (15.0, 10.0), (15.0, 5.0), (5.0, 5.0)]) + ) assert len(result) == 4 assert result.areas.sum() == 50.0 @@ -1374,7 +1390,9 @@ def test_rasters(example_data_path): if (np.max(data) - 2608.557) > 1e-4: raise AssertionError - data = rio.resample_to_grid(ml.modelgrid, band=rio.bands[0], method="nearest") + data = rio.resample_to_grid( + ml.modelgrid, band=rio.bands[0], method="nearest" + ) if data.size != 5913: raise AssertionError if abs(np.min(data) - 1942.1735) > 1e-4: @@ -1423,11 +1441,15 @@ def test_raster_sampling_methods(example_data_path): } for method, value in methods.items(): - data = rio.resample_to_grid(ml.modelgrid, band=rio.bands[0], method=method) + data = rio.resample_to_grid( + ml.modelgrid, band=rio.bands[0], method=method + ) print(data[30, 37]) if np.abs(data[30, 37] - value) > 1e-05: - raise AssertionError(f"{method} resampling returning incorrect values") + raise AssertionError( + f"{method} resampling returning incorrect values" + ) if __name__ == "__main__": diff --git a/autotest/test_hydmodfile.py b/autotest/test_hydmodfile.py index 76b70f1bb2..3bf29a2689 100644 --- a/autotest/test_hydmodfile.py +++ b/autotest/test_hydmodfile.py @@ -79,24 +79,16 @@ def test_hydmodfile_read(hydmod_model_path): assert isinstance(h, HydmodObs) ntimes = h.get_ntimes() - assert ntimes == 101, "Not enough times in hydmod file ()...".format( - os.path.basename(pth) - ) + assert ntimes == 101, "Not enough times in hydmod file ()...".format() times = h.get_times() - assert len(times) == 101, "Not enough times in hydmod file ()...".format( - os.path.basename(pth) - ) + assert len(times) == 101, "Not enough times in hydmod file ()...".format() nitems = h.get_nobs() - assert nitems == 8, "Not enough records in hydmod file ()...".format( - os.path.basename(pth) - ) + assert nitems == 8, "Not enough records in hydmod file ()...".format() labels = h.get_obsnames() - assert len(labels) == 8, "Not enough labels in hydmod file ()...".format( - os.path.basename(pth) - ) + assert len(labels) == 8, "Not enough labels in hydmod file ()...".format() print(labels) for idx in range(ntimes): diff --git a/autotest/test_mf6.py b/autotest/test_mf6.py index 080c939301..0e09c8258b 100644 --- a/autotest/test_mf6.py +++ b/autotest/test_mf6.py @@ -2249,10 +2249,10 @@ def test_multi_model(function_tmpdir): gwt2 = sim2.get_model("gwt_model_1") ssm2 = gwt2.get_package("ssm") fileinput = [ - ("RCH-1", f"gwt_model_1.rch1.spc"), - ("RCH-2", f"gwt_model_1.rch2.spc"), - ("RCH-3", f"gwt_model_1.rch3.spc", "MIXED"), - ("RCH-4", f"gwt_model_1.rch4.spc"), + ("RCH-1", "gwt_model_1.rch1.spc"), + ("RCH-2", "gwt_model_1.rch2.spc"), + ("RCH-3", "gwt_model_1.rch3.spc", "MIXED"), + ("RCH-4", "gwt_model_1.rch4.spc"), ] ssm2.fileinput = fileinput fi_out = ssm2.fileinput.get_data() diff --git a/autotest/test_mfsimlist.py b/autotest/test_mfsimlist.py index 150d07204d..6e52e39a79 100644 --- a/autotest/test_mfsimlist.py +++ b/autotest/test_mfsimlist.py @@ -104,13 +104,13 @@ def test_mfsimlist_memory(function_tmpdir): total_memory = mfsimlst.get_memory_usage() assert total_memory > 0.0, ( - f"total memory is not greater than 0.0 " + f"({total_memory})" + "total memory is not greater than 0.0 " + f"({total_memory})" ) total_memory_kb = mfsimlst.get_memory_usage(units="kilobytes") assert np.allclose(total_memory_kb, total_memory * 1e6), ( f"total memory in kilobytes ({total_memory_kb}) is not equal to " - + f"the total memory converted to kilobytes " + + "the total memory converted to kilobytes " + f"({total_memory * 1e6})" ) diff --git a/autotest/test_plot_cross_section.py b/autotest/test_plot_cross_section.py index 2c705b4644..eeb98df3a0 100644 --- a/autotest/test_plot_cross_section.py +++ b/autotest/test_plot_cross_section.py @@ -227,4 +227,4 @@ def test_plot_limits(): if (lims.x0, lims.x1, lims.y0, lims.y1) != pxc.extent: raise AssertionError("PlotMapView auto extent setting not working") - plt.close(fig) \ No newline at end of file + plt.close(fig) diff --git a/autotest/test_plot_map_view.py b/autotest/test_plot_map_view.py index f18adcb2a9..2303d24ece 100644 --- a/autotest/test_plot_map_view.py +++ b/autotest/test_plot_map_view.py @@ -276,4 +276,4 @@ def test_plot_limits(): if (lims.x0, lims.x1, lims.y0, lims.y1) != pmv.extent: raise AssertionError("PlotMapView auto extent setting not working") - plt.close(fig) \ No newline at end of file + plt.close(fig) diff --git a/autotest/test_specific_discharge.py b/autotest/test_specific_discharge.py index 3ffe4c85e5..7a389e6a39 100644 --- a/autotest/test_specific_discharge.py +++ b/autotest/test_specific_discharge.py @@ -205,7 +205,7 @@ def mf6_model(function_tmpdir): gwf = ModflowGwf( sim, modelname="mf6", - model_nam_file=f"mf6.nam", + model_nam_file="mf6.nam", ) gwf.name_file.save_flows = True diff --git a/autotest/test_util_geometry.py b/autotest/test_util_geometry.py index 2c70c730fe..60e3e2340e 100644 --- a/autotest/test_util_geometry.py +++ b/autotest/test_util_geometry.py @@ -46,7 +46,7 @@ def test_point_in_polygon_interior(): ypts = grid.ycellcenters mask = point_in_polygon(xpts, ypts, cell) assert mask.sum() == 1 - assert mask[0, 0] == True + assert mask[0, 0] debug_plot(grid, cell, xpts, ypts, mask) diff --git a/autotest/test_uzf.py b/autotest/test_uzf.py index 9a8f3ca17a..aa3018d703 100644 --- a/autotest/test_uzf.py +++ b/autotest/test_uzf.py @@ -369,8 +369,8 @@ def test_load_write_sfr_option_block(function_tmpdir, options_path): ext_unit_dict={}, ) - assert sfr3.options.strhc1kh == False - assert sfr3.options.strhc1kv == False + assert sfr3.options.strhc1kh is False + assert sfr3.options.strhc1kv is False def test_load_write_sfr_option_line(function_tmpdir, options_path): diff --git a/flopy/discretization/unstructuredgrid.py b/flopy/discretization/unstructuredgrid.py index 196bde995f..61aa499221 100644 --- a/flopy/discretization/unstructuredgrid.py +++ b/flopy/discretization/unstructuredgrid.py @@ -1025,7 +1025,7 @@ def split_line(): if not (len(header) == 1 and header[0] == "UNSTRUCTURED") or ( len(header) == 2 and header == ["UNSTRUCTURED", "GWF"] ): - raise ValueError(f"Invalid GSF file, no header") + raise ValueError("Invalid GSF file, no header") nnodes = int(split_line()[0]) verts_declared = int(split_line()[0]) diff --git a/flopy/export/longnames.py b/flopy/export/longnames.py index fe4df3fa72..f52c36ca77 100644 --- a/flopy/export/longnames.py +++ b/flopy/export/longnames.py @@ -1,4 +1,4 @@ -""" Human readable long names for netCDF variables. """ +"""Human readable long names for netCDF variables.""" NC_LONG_NAMES = { "botm": "Model layer bottom elevations", diff --git a/flopy/export/netcdf.py b/flopy/export/netcdf.py index 2caba116d3..6ad1daffb7 100644 --- a/flopy/export/netcdf.py +++ b/flopy/export/netcdf.py @@ -56,7 +56,7 @@ class Logger: def __init__(self, filename, echo=False): self.items = {} self.echo = bool(echo) - if filename == True: + if filename is True: self.echo = True self.filename = None elif filename: @@ -387,10 +387,9 @@ def append(self, other, suffix="_1"): else: for vname, array in other.items(): vname_norm = self.normalize_name(vname) - assert ( - vname_norm in self.nc.variables.keys() - ), f"dict var not in self.vars:{vname}-->" + ",".join( - self.nc.variables.keys() + assert vname_norm in self.nc.variables.keys(), ( + f"dict var not in self.vars:{vname}-->" + + ",".join(self.nc.variables.keys()) ) new_vname = vname_norm + suffix @@ -681,7 +680,7 @@ def initialize_geometry(self): "The FloPy NetCDF module requires pyproj >= 2.2.0." ) - print(f"initialize_geometry::") + print("initialize_geometry::") self.log(f"model crs: {self.model_crs}") print(f"model crs: {self.model_crs}") diff --git a/flopy/export/unitsformat.py b/flopy/export/unitsformat.py index ba208d5c03..e97560b99b 100644 --- a/flopy/export/unitsformat.py +++ b/flopy/export/unitsformat.py @@ -1,4 +1,4 @@ -""" unit format strings for netCDF variables. """ +"""unit format strings for netCDF variables.""" NC_UNITS_FORMAT = { "2D_cumulative_well_flux": "{0}^3/{1}", diff --git a/flopy/export/utils.py b/flopy/export/utils.py index ff77baadda..d64807c9e9 100644 --- a/flopy/export/utils.py +++ b/flopy/export/utils.py @@ -159,12 +159,12 @@ def _add_output_nc_variable( array = np.zeros( (len(times), shape3d[0], shape3d[1], shape3d[2]), dtype=np.float32 ) - array[:] = np.NaN + array[:] = np.nan if isinstance(out_obj, ZBNetOutput): a = np.asarray(out_obj.zone_array, dtype=np.float32) if mask_array3d is not None: - a[mask_array3d] = np.NaN + a[mask_array3d] = np.nan for i, _ in enumerate(times): array[i, :, :, :] = a @@ -187,7 +187,7 @@ def _add_output_nc_variable( print(estr) continue if mask_array3d is not None and a.shape == mask_array3d.shape: - a[mask_array3d] = np.NaN + a[mask_array3d] = np.nan try: array[i, :, :, :] = a.astype(np.float32) except Exception as e: @@ -203,7 +203,7 @@ def _add_output_nc_variable( logger.log(f"creating array for {var_name}") for mask_val in mask_vals: - array[np.where(array == mask_val)] = np.NaN + array[np.where(array == mask_val)] = np.nan mx, mn = np.nanmax(array), np.nanmin(array) array[np.isnan(array)] = netcdf.FILLVALUE @@ -1082,9 +1082,9 @@ def transient2d_export(f: Union[str, os.PathLike], t2d, fmt=None, **kwargs): with np.errstate(invalid="ignore"): if array.dtype not in [int, np.int32, np.int64]: if mask is not None: - array[:, 0, mask] = np.NaN - array[array <= min_valid] = np.NaN - array[array >= max_valid] = np.NaN + array[:, 0, mask] = np.nan + array[array <= min_valid] = np.nan + array[array >= max_valid] = np.nan mx, mn = np.nanmax(array), np.nanmin(array) else: mx, mn = np.nanmax(array), np.nanmin(array) @@ -1099,7 +1099,7 @@ def transient2d_export(f: Union[str, os.PathLike], t2d, fmt=None, **kwargs): var_name = t2d.name.replace("_", "") if isinstance(f, dict): - array[array == netcdf.FILLVALUE] = np.NaN + array[array == netcdf.FILLVALUE] = np.nan f[var_name] = array return f @@ -1243,7 +1243,7 @@ def array3d_export(f: Union[str, os.PathLike], u3d, fmt=None, **kwargs): # if isinstance(f,NetCdf) and array.shape != f.shape: # f.log("broadcasting 3D array for {0}".format(var_name)) # full_array = np.empty(f.shape) - # full_array[:] = np.NaN + # full_array[:] = np.nan # full_array[:array.shape[0]] = array # array = full_array # f.log("broadcasting 3D array for {0}".format(var_name)) @@ -1256,7 +1256,7 @@ def array3d_export(f: Union[str, os.PathLike], u3d, fmt=None, **kwargs): if mask is not None and array.shape != mask.shape: # f.log("broadcasting 3D array for {0}".format(var_name)) full_array = np.empty(mask.shape) - full_array[:] = np.NaN + full_array[:] = np.nan full_array[: array.shape[0]] = array array = full_array # f.log("broadcasting 3D array for {0}".format(var_name)) @@ -1268,13 +1268,13 @@ def array3d_export(f: Union[str, os.PathLike], u3d, fmt=None, **kwargs): # if u3d.model.modelgrid.bas6 is not None and "ibound" not # in var_name: # array[u3d.model.modelgrid.bas6.ibound.array == 0] = - # np.NaN + # np.nan # elif u3d.model.btn is not None and 'icbund' not in var_name: - # array[u3d.model.modelgrid.btn.icbund.array == 0] = np.NaN + # array[u3d.model.modelgrid.btn.icbund.array == 0] = np.nan if mask is not None: - array[mask] = np.NaN - array[array <= min_valid] = np.NaN - array[array >= max_valid] = np.NaN + array[mask] = np.nan + array[array <= min_valid] = np.nan + array[array >= max_valid] = np.nan mx, mn = np.nanmax(array), np.nanmin(array) else: mx, mn = np.nanmax(array), np.nanmin(array) @@ -1421,9 +1421,9 @@ def array2d_export( and "ibound" not in u2d.name.lower() and "idomain" not in u2d.name.lower() ): - array[modelgrid.idomain[0, :, :] == 0] = np.NaN - array[array <= min_valid] = np.NaN - array[array >= max_valid] = np.NaN + array[modelgrid.idomain[0, :, :] == 0] = np.nan + array[array <= min_valid] = np.nan + array[array >= max_valid] = np.nan mx, mn = np.nanmax(array), np.nanmin(array) else: mx, mn = np.nanmax(array), np.nanmin(array) diff --git a/flopy/export/vtk.py b/flopy/export/vtk.py index fd9cbf1232..83912eae8c 100644 --- a/flopy/export/vtk.py +++ b/flopy/export/vtk.py @@ -1458,7 +1458,7 @@ def write(self, f: Union[str, os.PathLike], kper=None): w.SetFileName(str(foo)) w.Update() - if not type(self.pvd) == bool: + if not isinstance(self.pvd, bool): if f.suffix not in (".vtk", ".vtu"): pvdfile = f.parent / f"{f.name}.pvd" else: diff --git a/flopy/mbase.py b/flopy/mbase.py index a412851378..c569944ff8 100644 --- a/flopy/mbase.py +++ b/flopy/mbase.py @@ -1507,7 +1507,7 @@ def write_input(self, SelPackList=False, check=False): if self.verbose: print("\nWriting packages:") - if SelPackList == False: + if SelPackList is False: for p in self.packagelist: if self.verbose: print(" Package: ", p.name[0]) @@ -1799,7 +1799,7 @@ def run_model( # make sure executable exists if exe_name is None: - raise ValueError(f"An executable name or path must be provided") + raise ValueError("An executable name or path must be provided") exe_path = resolve_exe(exe_name) if not silent: print( diff --git a/flopy/mf6/coordinates/modeldimensions.py b/flopy/mf6/coordinates/modeldimensions.py index 5b9460ecf8..8bf81351e9 100644 --- a/flopy/mf6/coordinates/modeldimensions.py +++ b/flopy/mf6/coordinates/modeldimensions.py @@ -466,9 +466,7 @@ def get_data_shape( data_item_struct, path=path, repeating_key=repeating_key, - )[ - 0 - ] + )[0] num_cols = num_cols + num shape_consistent = ( shape_consistent and consistent_shape diff --git a/flopy/mf6/coordinates/modelgrid.py b/flopy/mf6/coordinates/modelgrid.py index 538594a2ea..9536a6afbf 100644 --- a/flopy/mf6/coordinates/modelgrid.py +++ b/flopy/mf6/coordinates/modelgrid.py @@ -274,7 +274,7 @@ def _get_connection_number(self, cellid, reverse_connection=False): jas = self._simulation_data.mfdata[ (self._model_name, "disu8", "connectiondata", "ja") ] - if reverse_connection == False: + if reverse_connection is False: connection_list = jas[self._cellid - 1] connecting_cellid = cellid else: @@ -478,8 +478,9 @@ def get_idomain(self): (self._model_name, "disu", "griddata", "idomain") ].get_data() except_str = ( - "ERROR: Grid type {} for model {} not " - "recognized.".format(self._grid_type, self._model_name) + "ERROR: Grid type {} for model {} not " "recognized.".format( + self._grid_type, self._model_name + ) ) print(except_str) raise MFGridException(except_str) diff --git a/flopy/mf6/data/mfdata.py b/flopy/mf6/data/mfdata.py index bd24c5dc7a..532a31ca8a 100644 --- a/flopy/mf6/data/mfdata.py +++ b/flopy/mf6/data/mfdata.py @@ -160,7 +160,7 @@ def get_active_key_dict(self): def _verify_sp(self, sp_num): if self._path[0].lower() == "nam": return True - if not ("tdis", "dimensions", "nper") in self._simulation_data.mfdata: + if ("tdis", "dimensions", "nper") not in self._simulation_data.mfdata: raise FlopyException( "Could not find number of stress periods (nper)." ) diff --git a/flopy/mf6/data/mfdataarray.py b/flopy/mf6/data/mfdataarray.py index 8befe29c93..58a7ff4242 100644 --- a/flopy/mf6/data/mfdataarray.py +++ b/flopy/mf6/data/mfdataarray.py @@ -387,8 +387,9 @@ def set_layered_data(self, layered_data): comment = f"Layered option not available for unstructured grid. {self._path}" else: comment = ( - 'Data "{}" does not support layered option. ' - "{}".format(self._data_name, self._path) + 'Data "{}" does not support layered option. ' "{}".format( + self._data_name, self._path + ) ) type_, value_, traceback_ = sys.exc_info() raise MFDataException( @@ -436,8 +437,9 @@ def make_layered(self): comment = f"Layered option not available for unstructured grid. {self._path}" else: comment = ( - 'Data "{}" does not support layered option. ' - "{}".format(self._data_name, self._path) + 'Data "{}" does not support layered option. ' "{}".format( + self._data_name, self._path + ) ) type_, value_, traceback_ = sys.exc_info() raise MFDataException( @@ -544,8 +546,7 @@ def store_as_external_file( >= VerbosityLevel.verbose.value ): print( - "Storing {} layer {} to external file {}.." - ".".format( + "Storing {} layer {} to external file {}.." ".".format( self.structure.name, current_layer[0] + 1, file_path, @@ -634,8 +635,7 @@ def store_internal( >= VerbosityLevel.verbose.value ): print( - "Storing {} layer {} internally.." - ".".format( + "Storing {} layer {} internally.." ".".format( self.structure.name, current_layer[0] + 1, ) @@ -852,7 +852,7 @@ def _set_record(self, data_record): self._set_data(record, layer=layer, preserve_record=False) else: self._set_data(data_record, preserve_record=False) - elif type(data_record) == list: + elif isinstance(data_record, list): for layer, record in enumerate(data_record): self._set_data(record, layer=layer, preserve_record=False) else: @@ -1217,8 +1217,9 @@ def _get_file_entry( # set layer range if not shape_ml.in_shape(layer): comment = ( - 'Layer {} for variable "{}" does not exist' - ".".format(layer, self._data_name) + 'Layer {} for variable "{}" does not exist' ".".format( + layer, self._data_name + ) ) type_, value_, traceback_ = sys.exc_info() raise MFDataException( diff --git a/flopy/mf6/data/mfdatalist.py b/flopy/mf6/data/mfdatalist.py index e66146d484..a3627ace14 100644 --- a/flopy/mf6/data/mfdatalist.py +++ b/flopy/mf6/data/mfdatalist.py @@ -133,7 +133,7 @@ def to_array(self, kper=0, mask=False): MODFLOW zero-based stress period number to return. (default is zero) mask : bool - return array with np.NaN instead of zero + return array with np.nan instead of zero Returns ---------- @@ -221,8 +221,9 @@ def store_as_external_file( >= VerbosityLevel.verbose.value ): print( - "Storing {} to external file {}.." - ".".format(self.structure.name, external_file_path) + "Storing {} to external file {}.." ".".format( + self.structure.name, external_file_path + ) ) external_data = { "filename": external_file_path, @@ -712,7 +713,7 @@ def search_data(self, search_term, col=None): if ( val is not None and val.lower() == search_term - and (col == None or col == col_num) + and (col is None or col == col_num) ): return (row, col) col_num += 1 @@ -977,7 +978,7 @@ def _get_file_entry_record( ): data_complete_len = len(data_line) if data_complete_len <= index: - if data_item.optional == False: + if data_item.optional is False: message = ( "Not enough data provided " "for {}. Data for required data " diff --git a/flopy/mf6/data/mfdataplist.py b/flopy/mf6/data/mfdataplist.py index 45fdbde4a1..dd397699df 100644 --- a/flopy/mf6/data/mfdataplist.py +++ b/flopy/mf6/data/mfdataplist.py @@ -812,7 +812,7 @@ def to_array(self, kper=0, mask=False): MODFLOW zero-based stress period number to return (default is zero) mask : bool - return array with np.NaN instead of zero + return array with np.nan instead of zero Returns ---------- @@ -1065,8 +1065,9 @@ def store_as_external_file( >= VerbosityLevel.verbose.value ): print( - "Storing {} to external file {}.." - ".".format(self.structure.name, external_file_path) + "Storing {} to external file {}.." ".".format( + self.structure.name, external_file_path + ) ) external_data = { "filename": external_file_path, diff --git a/flopy/mf6/data/mfdatascalar.py b/flopy/mf6/data/mfdatascalar.py index c9ab08183c..8eb4824285 100644 --- a/flopy/mf6/data/mfdatascalar.py +++ b/flopy/mf6/data/mfdatascalar.py @@ -299,8 +299,7 @@ def add_one(self): ) else: message = ( - "{} of type {} does not support add one " - "operation.".format( + "{} of type {} does not support add one " "operation.".format( self._data_name, self.structure.get_datum_type() ) ) @@ -385,7 +384,7 @@ def get_file_entry( ex, ) if self.structure.type == DatumType.keyword: - if data is not None and data != False: + if data is not None and data is not False: # keyword appears alone return "{}{}\n".format( self._simulation_data.indent_string, @@ -408,7 +407,8 @@ def get_file_entry( ): data = data[0] if len(data) > index and ( - data[index] is not None and data[index] != False + data[index] is not None + and data[index] is not False ): text_line.append(data_item.name.upper()) if ( @@ -421,7 +421,7 @@ def get_file_entry( # assume the keyword was excluded index -= 1 else: - if data is not None and data != False: + if data is not None and data is not False: text_line.append(data_item.name.upper()) else: if data is not None and data != "": @@ -429,12 +429,12 @@ def get_file_entry( if len(data) > index: if ( data[index] is not None - and data[index] != False + and data[index] is not False ): current_data = data[index] else: break - elif data_item.optional == True: + elif data_item.optional is True: break else: message = ( @@ -462,7 +462,7 @@ def get_file_entry( if data_item.type == DatumType.keyword: if ( current_data is not None - and current_data != False + and current_data is not False ): if ( isinstance(data[index], str) diff --git a/flopy/mf6/data/mfdatastorage.py b/flopy/mf6/data/mfdatastorage.py index 2f37b36da5..5441936ffb 100644 --- a/flopy/mf6/data/mfdatastorage.py +++ b/flopy/mf6/data/mfdatastorage.py @@ -1388,16 +1388,16 @@ def store_internal( # convert numbers to be multiplied by the original factor data = data * adjustment if const: - self.layer_storage[layer].data_storage_type = ( - DataStorageType.internal_constant - ) + self.layer_storage[ + layer + ].data_storage_type = DataStorageType.internal_constant self.layer_storage[layer].data_const_value = [ mfdatautil.get_first_val(data) ] else: - self.layer_storage[layer].data_storage_type = ( - DataStorageType.internal_array - ) + self.layer_storage[ + layer + ].data_storage_type = DataStorageType.internal_array try: self.layer_storage[layer].internal_data = np.reshape( data, dimensions @@ -1426,11 +1426,11 @@ def store_internal( data_type = self.data_dimensions.structure.get_datum_type(True) dt = self.layer_storage[layer].internal_data.dtype if dt != data_type: - self.layer_storage[layer].internal_data = ( - self.layer_storage[layer].internal_data.astype( - data_type - ) - ) + self.layer_storage[ + layer + ].internal_data = self.layer_storage[ + layer + ].internal_data.astype(data_type) if not preserve_record: self.layer_storage[layer].factor = multiplier self.layer_storage[layer].iprn = print_format @@ -1818,9 +1818,9 @@ def store_external( if self._calc_data_size(data, 2) == 1 and data_size > 1: # constant data, need to expand self.layer_storage[layer_new].data_const_value = data - self.layer_storage[layer_new].data_storage_type = ( - DataStorageType.internal_constant - ) + self.layer_storage[ + layer_new + ].data_storage_type = DataStorageType.internal_constant data = self._fill_const_layer(layer) elif isinstance(data, list): data = self._to_ndarray(data, layer) @@ -1877,9 +1877,9 @@ def set_ext_file_attributes(self, layer, file_path, print_format, binary): self.layer_storage[layer].fname = file_path self.layer_storage[layer].iprn = print_format self.layer_storage[layer].binary = binary - self.layer_storage[layer].data_storage_type = ( - DataStorageType.external_file - ) + self.layer_storage[ + layer + ].data_storage_type = DataStorageType.external_file def point_to_existing_external_file(self, arr_line, layer): ( @@ -2106,8 +2106,9 @@ def resolve_shape_list( ) except Exception as se: comment = ( - 'Unable to resolve shape for data "{}" field "{}"' - ".".format(struct.name, data_item.name) + 'Unable to resolve shape for data "{}" field "{}"' ".".format( + struct.name, data_item.name + ) ) type_, value_, traceback_ = sys.exc_info() raise MFDataException( diff --git a/flopy/mf6/data/mfdatautil.py b/flopy/mf6/data/mfdatautil.py index bf9f571749..a1e00ad97c 100644 --- a/flopy/mf6/data/mfdatautil.py +++ b/flopy/mf6/data/mfdatautil.py @@ -151,7 +151,7 @@ def list_to_array(sarr, model_grid, kper=0, mask=False): MODFLOW zero-based stress period number to return. (default is zero) mask : bool - return array with np.NaN instead of zero + return array with np.nan instead of zero Returns ---------- @@ -192,7 +192,7 @@ def list_to_array(sarr, model_grid, kper=0, mask=False): if sarr[0] == 0: if mask: for name, arr in arrays.items(): - arrays[name][:] = np.NaN + arrays[name][:] = np.nan return arrays else: raise Exception("MfList: something bad happened") @@ -210,7 +210,7 @@ def list_to_array(sarr, model_grid, kper=0, mask=False): arr[idx] /= cnt[idx] if mask: arr = np.ma.masked_where(cnt == 0.0, arr) - arr[cnt == 0.0] = np.NaN + arr[cnt == 0.0] = np.nan arrays[name] = arr.copy() return arrays diff --git a/flopy/mf6/data/mffileaccess.py b/flopy/mf6/data/mffileaccess.py index a68a78a07c..639b815843 100644 --- a/flopy/mf6/data/mffileaccess.py +++ b/flopy/mf6/data/mffileaccess.py @@ -1469,9 +1469,7 @@ def read_list_data_from_file( current_key, self._data_line, False, - )[ - 0:2 - ] + )[0:2] elif ( data_item.name == "boundname" and self._data_dimensions.package_dim.boundnames() @@ -1720,9 +1718,7 @@ def load_list_line( for ( key, record, - ) in ( - data_item.keystring_dict.items() - ): + ) in data_item.keystring_dict.items(): if ( isinstance( record, @@ -2050,9 +2046,7 @@ def _process_aux( current_key, data_line, add_to_last_line, - )[ - 0:3 - ] + )[0:3] else: # read in aux variables ( @@ -2070,9 +2064,7 @@ def _process_aux( current_key, data_line, add_to_last_line, - )[ - 0:3 - ] + )[0:3] return data_index, data_line, more_data_expected def _append_data_list( @@ -2323,7 +2315,7 @@ def load_from_package( if ( len(arr_line) <= index + 1 or data_item_type[0] != DatumType.keyword - or (index > 0 and optional == True) + or (index > 0 and optional is True) ): break index += 1 diff --git a/flopy/mf6/data/mfstructure.py b/flopy/mf6/data/mfstructure.py index 576cb21483..0824923efc 100644 --- a/flopy/mf6/data/mfstructure.py +++ b/flopy/mf6/data/mfstructure.py @@ -1176,11 +1176,11 @@ def indicates_file_name(self): def is_file_name(self): if ( self.name.lower() in self.file_name_keywords - and self.file_name_keywords[self.name.lower()] == True + and self.file_name_keywords[self.name.lower()] is True ): return True for key, item in self.contained_keywords.items(): - if self.name.lower().find(key) != -1 and item == True: + if self.name.lower().find(key) != -1 and item is True: return True return False @@ -1557,7 +1557,7 @@ def add_item(self, item, record=False, dfn_list=None): item.type != DatumType.record and item.type != DatumType.repeating_record ) - or record == True + or record is True ): if item.name not in self.expected_data_items: raise StructException( diff --git a/flopy/mf6/mfbase.py b/flopy/mf6/mfbase.py index 3bdc6eba50..a1e6b3caf6 100644 --- a/flopy/mf6/mfbase.py +++ b/flopy/mf6/mfbase.py @@ -1,4 +1,4 @@ -""" Base classes for Modflow 6 """ +"""Base classes for Modflow 6""" import copy import inspect diff --git a/flopy/mf6/mfmodel.py b/flopy/mf6/mfmodel.py index 9745ec8109..df9124e766 100644 --- a/flopy/mf6/mfmodel.py +++ b/flopy/mf6/mfmodel.py @@ -284,7 +284,7 @@ def modeltime(self): last_ss_value = True elif index in tr_periods: last_ss_value = False - if last_ss_value == True: + if last_ss_value is True: steady[index] = True # build model time @@ -1036,7 +1036,7 @@ def inspect_cells( h_columns = ",".join(search_output.data_header) fd.write(f",{h_columns}\n") else: - fd.write(f",cellid,data\n") + fd.write(",cellid,data\n") # write data found for index, data_entry in enumerate( search_output.data_entries @@ -1068,7 +1068,7 @@ def inspect_cells( ) fd.write(f",{output}") fd.write(self._format_data_entry(data_entry)) - fd.write(f"\n") + fd.write("\n") return output_by_package def match_array_cells( @@ -1278,7 +1278,7 @@ def is_valid(self): for package_struct in self.structure.package_struct_objs.values(): if ( not package_struct.optional - and not package_struct.file_type in self.package_type_dict + and package_struct.file_type not in self.package_type_dict ): return False diff --git a/flopy/mf6/mfpackage.py b/flopy/mf6/mfpackage.py index 004a8ed77a..f52a38d425 100644 --- a/flopy/mf6/mfpackage.py +++ b/flopy/mf6/mfpackage.py @@ -1109,7 +1109,7 @@ def _find_data_by_keyword(self, line, fd, initial_comment): elif ( arr_line[0].lower() == "readasarrays" and self.path[-1].lower() == "options" - and self._container_package.structure.read_as_arrays == False + and self._container_package.structure.read_as_arrays is False ): error_msg = ( "ERROR: Attempting to read a ReadAsArrays " @@ -1243,7 +1243,7 @@ def _add_to_info_list( def _save_comments(self, arr_line, line, key, comments): # FIX: Save these comments somewhere in the data set - if not key in self.datasets_keyword: + if key not in self.datasets_keyword: if MFComment.is_comment(key, True): if comments: comments.append("\n") @@ -1489,8 +1489,9 @@ def _write_block(self, fd, block_header, ext_file_action): >= VerbosityLevel.verbose.value ): print( - " writing data {} ({}).." - ".".format(dataset.structure.name, transient_key) + " writing data {} ({}).." ".".format( + dataset.structure.name, transient_key + ) ) if basic_list: ext_fname = dataset.external_file_name(transient_key) @@ -2096,8 +2097,8 @@ def check(self, f=None, verbose=True, level=1, checktype=None): not datautil.DatumUtil.is_float( row[data_index] ) - and not row[data_index] - in time_series_name_dict + and row[data_index] + not in time_series_name_dict ): desc = ( f"Invalid non-numeric " @@ -2120,8 +2121,8 @@ def check(self, f=None, verbose=True, level=1, checktype=None): val = np.isnan(np.sum(data)) if val: desc = ( - f"One or more nan values were " - f"found in auxiliary data." + "One or more nan values were " + "found in auxiliary data." ) chk._add_to_summary( "Warning", @@ -2165,8 +2166,7 @@ def _get_data_str(self, formal, show_data=True): bl_repr = repr(block) if len(bl_repr.strip()) > 0: data_str = ( - "{}Block {}\n--------------------\n{}" - "\n".format( + "{}Block {}\n--------------------\n{}" "\n".format( data_str, block.structure.name, repr(block) ) ) @@ -2174,8 +2174,7 @@ def _get_data_str(self, formal, show_data=True): bl_str = str(block) if len(bl_str.strip()) > 0: data_str = ( - "{}Block {}\n--------------------\n{}" - "\n".format( + "{}Block {}\n--------------------\n{}" "\n".format( data_str, block.structure.name, str(block) ) ) diff --git a/flopy/mf6/mfsimbase.py b/flopy/mf6/mfsimbase.py index 898e42836e..f817f4f532 100644 --- a/flopy/mf6/mfsimbase.py +++ b/flopy/mf6/mfsimbase.py @@ -614,9 +614,9 @@ def __str__(self): def _get_data_str(self, formal): file_mgt = self.simulation_data.mfpath data_str = ( - "sim_name = {}\nsim_path = {}\nexe_name = " - "{}\n" - "\n".format(self.name, file_mgt.get_sim_path(), self.exe_name) + "sim_name = {}\nsim_path = {}\nexe_name = " "{}\n" "\n".format( + self.name, file_mgt.get_sim_path(), self.exe_name + ) ) for package in self._packagelist: diff --git a/flopy/mf6/modflow/__init__.py b/flopy/mf6/modflow/__init__.py index e5a5ce1668..991b29d667 100644 --- a/flopy/mf6/modflow/__init__.py +++ b/flopy/mf6/modflow/__init__.py @@ -58,7 +58,6 @@ from .mfmvr import ModflowMvr from .mfmvt import ModflowMvt from .mfnam import ModflowNam -from .mfsimulation import MFSimulation from .mftdis import ModflowTdis from .mfutlats import ModflowUtlats from .mfutllaktab import ModflowUtllaktab diff --git a/flopy/mf6/utils/createpackages.py b/flopy/mf6/utils/createpackages.py index 539361784d..fe3306b655 100644 --- a/flopy/mf6/utils/createpackages.py +++ b/flopy/mf6/utils/createpackages.py @@ -844,8 +844,9 @@ def create_packages(): # write out child packages class chld_cls = ( - "\n\nclass {}Packages(mfpackage.MFChildPackage" - "s):\n".format(package_name.title()) + "\n\nclass {}Packages(mfpackage.MFChildPackage" "s):\n".format( + package_name.title() + ) ) chld_var = ( f" package_abbr = " @@ -1073,7 +1074,7 @@ def create_packages(): load_txt, ) sim_file = open( - os.path.join(util_path, "..", "modflow", f"mfsimulation.py"), + os.path.join(util_path, "..", "modflow", "mfsimulation.py"), "w", newline="\n", ) diff --git a/flopy/mf6/utils/model_splitter.py b/flopy/mf6/utils/model_splitter.py index 090a388b09..02f469ffd6 100644 --- a/flopy/mf6/utils/model_splitter.py +++ b/flopy/mf6/utils/model_splitter.py @@ -1410,9 +1410,9 @@ def _remap_uzf(self, package, mapped_data): mapped_data[mkey]["packagedata"] = new_recarray mapped_data[mkey]["nuzfcells"] = len(new_recarray) - mapped_data[mkey][ - "ntrailwaves" - ] = package.ntrailwaves.array + mapped_data[mkey]["ntrailwaves"] = ( + package.ntrailwaves.array + ) mapped_data[mkey]["nwavesets"] = package.nwavesets.array mapped_data[mkey]["perioddata"] = spd @@ -2399,7 +2399,7 @@ def _remap_obs(self, package, mapped_data, remapper, pkg_type=None): new_model1[mm_idx] = tmp_models cellid2 = recarray.id2 - conv_idx = np.where((cellid2 != None))[0] + conv_idx = np.where((cellid2 is not None))[0] if len(conv_idx) > 0: # do stuff # need to trap layers... if pkg_type is None: @@ -2456,7 +2456,7 @@ def _remap_obs(self, package, mapped_data, remapper, pkg_type=None): for mkey, model in self._model_dict.items(): idx = np.where(new_model2 == mkey) tmp_node = new_node2[idx] - cidx = np.where((tmp_node != None)) + cidx = np.where((tmp_node is not None)) tmp_cellid = model.modelgrid.get_lrc( tmp_node[cidx].to_list() ) @@ -2561,9 +2561,9 @@ def _remap_obs(self, package, mapped_data, remapper, pkg_type=None): ofile: new_recarray } else: - mapped_data[mkey]["continuous"][ - ofile - ] = new_recarray + mapped_data[mkey]["continuous"][ofile] = ( + new_recarray + ) else: if "observations" not in mapped_data: mapped_data["observations"] = { diff --git a/flopy/mf6/utils/output_util.py b/flopy/mf6/utils/output_util.py index 5577a23a87..42bfe47517 100644 --- a/flopy/mf6/utils/output_util.py +++ b/flopy/mf6/utils/output_util.py @@ -126,11 +126,7 @@ def __init__(self, obj): [ obj._simulation_data.mfdata[ ky - ].array[ - 0 - ][ - -2 - ] + ].array[0][-2] ] ] break @@ -215,7 +211,7 @@ def __repr__(self): name = name[0] l = [ f"MF6Output Class for {name}", - f"Available output methods include:", + "Available output methods include:", ] l += [f".{m}" for m in self.methods()] s = "\n".join(l) diff --git a/flopy/mf6/utils/testutils.py b/flopy/mf6/utils/testutils.py index eeb66bf17d..11723a1b5b 100644 --- a/flopy/mf6/utils/testutils.py +++ b/flopy/mf6/utils/testutils.py @@ -67,8 +67,7 @@ def read_gncrecarray(gnc_file, cellid_size=3, cellid_size_2=3): ), make_int_tuple( linesp[ - cellid_size - + cellid_size_2 : cellid_size * 2 + cellid_size + cellid_size_2 : cellid_size * 2 + cellid_size_2 ] ), diff --git a/flopy/mfusg/mfusgcln.py b/flopy/mfusg/mfusgcln.py index 2bfe94cc2d..645264a38c 100644 --- a/flopy/mfusg/mfusgcln.py +++ b/flopy/mfusg/mfusgcln.py @@ -19,6 +19,7 @@ volume finite-difference formulation: U.S. Geological Survey Techniques and Methods, book 6, chap. A45, 66 p. """ + import numpy as np from ..pakbase import Package diff --git a/flopy/mfusg/mfusgsms.py b/flopy/mfusg/mfusgsms.py index ace15c15e3..0866a7ae33 100644 --- a/flopy/mfusg/mfusgsms.py +++ b/flopy/mfusg/mfusgsms.py @@ -5,6 +5,7 @@ Contains the MfUsgSms class. Note that the user can access the MfUsgSms class as `flopy.mfusg.MfUsgSms`. """ + from ..pakbase import Package from ..utils.flopy_io import line_parse from .mfusg import MfUsg diff --git a/flopy/modflow/mfbcf.py b/flopy/modflow/mfbcf.py index a7aed46a83..f52b738bf6 100644 --- a/flopy/modflow/mfbcf.py +++ b/flopy/modflow/mfbcf.py @@ -272,7 +272,7 @@ def write_file(self, f=None): f_bcf.write(self.trpy.get_file_entry()) transient = not dis.steady.all() for k in range(nlay): - if transient == True: + if transient: f_bcf.write(self.sf1[k].get_file_entry()) if (self.laycon[k] == 0) or (self.laycon[k] == 2): f_bcf.write(self.tran[k].get_file_entry()) @@ -280,9 +280,7 @@ def write_file(self, f=None): f_bcf.write(self.hy[k].get_file_entry()) if k < nlay - 1: f_bcf.write(self.vcont[k].get_file_entry()) - if (transient == True) and ( - (self.laycon[k] == 2) or (self.laycon[k] == 3) - ): + if transient and ((self.laycon[k] == 2) or (self.laycon[k] == 3)): f_bcf.write(self.sf2[k].get_file_entry()) if (self.iwdflg != 0) and ( (self.laycon[k] == 1) or (self.laycon[k] == 3) diff --git a/flopy/modflow/mfdis.py b/flopy/modflow/mfdis.py index 541d710df4..16550d2965 100644 --- a/flopy/modflow/mfdis.py +++ b/flopy/modflow/mfdis.py @@ -612,9 +612,7 @@ def write_file(self, check=True): None """ - if ( - check - ): # allows turning off package checks when writing files at model level + if check: # allows turning off package checks when writing files at model level self.check( f=f"{self.name[0]}.chk", verbose=self.parent.verbose, diff --git a/flopy/modflow/mfdrn.py b/flopy/modflow/mfdrn.py index 7e83553ee2..1639457340 100644 --- a/flopy/modflow/mfdrn.py +++ b/flopy/modflow/mfdrn.py @@ -223,9 +223,7 @@ def write_file(self, check=True): None """ - if ( - check - ): # allows turning off package checks when writing files at model level + if check: # allows turning off package checks when writing files at model level self.check( f=f"{self.name[0]}.chk", verbose=self.parent.verbose, diff --git a/flopy/modflow/mfdrt.py b/flopy/modflow/mfdrt.py index f165381a3f..c4988afefa 100644 --- a/flopy/modflow/mfdrt.py +++ b/flopy/modflow/mfdrt.py @@ -215,9 +215,7 @@ def write_file(self, check=True): None """ - if ( - check - ): # allows turning off package checks when writing files at model level + if check: # allows turning off package checks when writing files at model level self.check( f=f"{self.name[0]}.chk", verbose=self.parent.verbose, diff --git a/flopy/modflow/mffhb.py b/flopy/modflow/mffhb.py index b29ffadff3..2aec2aa099 100644 --- a/flopy/modflow/mffhb.py +++ b/flopy/modflow/mffhb.py @@ -237,8 +237,9 @@ def __init__( # perform some simple verification if len(self.bdtime) != self.nbdtim: raise ValueError( - "bdtime has {} entries but requires " - "{} entries.".format(len(self.bdtime), self.nbdtim) + "bdtime has {} entries but requires " "{} entries.".format( + len(self.bdtime), self.nbdtim + ) ) if self.nflw > 0: @@ -249,8 +250,9 @@ def __init__( if self.ds5.shape[0] != self.nflw: raise ValueError( - "dataset 5 has {} rows but requires " - "{} rows.".format(self.ds5.shape[0], self.nflw) + "dataset 5 has {} rows but requires " "{} rows.".format( + self.ds5.shape[0], self.nflw + ) ) nc = self.nbdtim if model.structured: @@ -270,8 +272,9 @@ def __init__( ) if self.ds7.shape[0] != self.nhed: raise ValueError( - "dataset 7 has {} rows but requires " - "{} rows.".format(self.ds7.shape[0], self.nhed) + "dataset 7 has {} rows but requires " "{} rows.".format( + self.ds7.shape[0], self.nhed + ) ) nc = self.nbdtim if model.structured: diff --git a/flopy/modflow/mfghb.py b/flopy/modflow/mfghb.py index 4ba6d2935d..33b9e99fd7 100644 --- a/flopy/modflow/mfghb.py +++ b/flopy/modflow/mfghb.py @@ -179,9 +179,7 @@ def write_file(self, check=True): None """ - if ( - check - ): # allows turning off package checks when writing files at model level + if check: # allows turning off package checks when writing files at model level self.check( f=f"{self.name[0]}.chk", verbose=self.parent.verbose, diff --git a/flopy/modflow/mflak.py b/flopy/modflow/mflak.py index cde1952d74..1491119e7f 100644 --- a/flopy/modflow/mflak.py +++ b/flopy/modflow/mflak.py @@ -376,8 +376,9 @@ def __init__( if self.dis.steady[0]: if stage_range.shape != (nlakes, 2): raise Exception( - "stages shape should be ({},2) but is only " - "{}.".format(nlakes, stage_range.shape) + "stages shape should be ({},2) but is only " "{}.".format( + nlakes, stage_range.shape + ) ) self.stage_range = stage_range diff --git a/flopy/modflow/mflpf.py b/flopy/modflow/mflpf.py index 397f7f79f6..0b192bcd77 100644 --- a/flopy/modflow/mflpf.py +++ b/flopy/modflow/mflpf.py @@ -371,7 +371,7 @@ def write_file(self, check=True, f=None): f.write(f"{self.heading}\n") # Item 1: IBCFCB, HDRY, NPLPF, , OPTIONS - if self.parent.version == "mfusg" and self.parent.structured == False: + if self.parent.version == "mfusg" and not self.parent.structured: f.write( "{:10d}{:10.6G}{:10d}{:10d} {:s}\n".format( self.ipakcb, @@ -405,7 +405,7 @@ def write_file(self, check=True, f=None): if self.chani[k] <= 0.0: f.write(self.hani[k].get_file_entry()) f.write(self.vka[k].get_file_entry()) - if transient == True: + if transient: f.write(self.ss[k].get_file_entry()) if self.laytyp[k] != 0: f.write(self.sy[k].get_file_entry()) @@ -477,7 +477,7 @@ def load(cls, f, model, ext_unit_dict=None, check=True): t = line_parse(line) ipakcb, hdry, nplpf = int(t[0]), float(t[1]), int(t[2]) item1_len = 3 - if model.version == "mfusg" and model.structured == False: + if model.version == "mfusg" and not model.structured: ikcflag = int(t[3]) item1_len = 4 # if ipakcb != 0: diff --git a/flopy/modflow/mfmnw2.py b/flopy/modflow/mfmnw2.py index 2df6478716..e3921d6cfb 100644 --- a/flopy/modflow/mfmnw2.py +++ b/flopy/modflow/mfmnw2.py @@ -1352,9 +1352,7 @@ def load(cls, f, model, nper=None, gwt=False, nsol=1, ext_unit_dict=None): np.recarray ) - stress_period_data = ( - {} - ) # stress period data table for package (flopy convention) + stress_period_data = {} # stress period data table for package (flopy convention) itmp = [] for per in range(0, nper): # dataset 3 diff --git a/flopy/modflow/mfoc.py b/flopy/modflow/mfoc.py index 820fd729df..df2dd9ff8d 100644 --- a/flopy/modflow/mfoc.py +++ b/flopy/modflow/mfoc.py @@ -817,7 +817,7 @@ def load( # process each line lines = [] - if numericformat == True: + if numericformat: for iperoc in range(nper): for itsoc in range(nstp[iperoc]): line = f.readline() @@ -978,7 +978,7 @@ def load( else: if itsoc != itsoc1: iempty = True - if iempty == True: + if iempty: kperkstp = (iperoc1 - 1, itsoc1 - 1) stress_period_data[kperkstp] = [] # dataset 3 @@ -1004,7 +1004,7 @@ def load( else: if itsoc != itsoc1: iempty = True - if iempty == True: + if iempty: kperkstp = (iperoc1 - 1, itsoc1 - 1) stress_period_data[kperkstp] = [] diff --git a/flopy/modflow/mfpar.py b/flopy/modflow/mfpar.py index d866977b0b..0b61758ec8 100644 --- a/flopy/modflow/mfpar.py +++ b/flopy/modflow/mfpar.py @@ -306,7 +306,7 @@ def parameter_fill(model, shape, findkey, parm_dict, findlayer=None): for [layer, mltarr, zonarr, izones] in clusters: # print layer, mltarr, zonarr, izones foundlayer = False - if findlayer == None: + if findlayer is None: foundlayer = True else: if layer == (findlayer + 1): diff --git a/flopy/modflow/mfpks.py b/flopy/modflow/mfpks.py index 905c33e654..566898ff30 100644 --- a/flopy/modflow/mfpks.py +++ b/flopy/modflow/mfpks.py @@ -183,7 +183,7 @@ def write_file(self): f.write(f"DROPTOL {self.droptol}\n") f.write(f"HCLOSEPKS {self.hclose}\n") f.write(f"RCLOSEPKS {self.rclose}\n") - if self.l2norm != None: + if self.l2norm is not None: if self.l2norm.lower() == "l2norm" or self.l2norm == "1": f.write("L2NORM\n") elif self.l2norm.lower() == "rl2norm" or self.l2norm == "2": diff --git a/flopy/modflow/mfsfr2.py b/flopy/modflow/mfsfr2.py index fad587b07d..7766ac48eb 100644 --- a/flopy/modflow/mfsfr2.py +++ b/flopy/modflow/mfsfr2.py @@ -905,9 +905,7 @@ def load(cls, f, model, nper=None, gwt=False, nsol=1, ext_unit_dict=None): channel_geometry_data = {} channel_flow_data = {} dataset_5 = {} - aux_variables = ( - {} - ) # not sure where the auxiliary variables are supposed to go + aux_variables = {} # not sure where the auxiliary variables are supposed to go for i in range(0, nper): # Dataset 5 dataset_5[i] = _get_dataset(f.readline(), [-1, 0, 0, 0]) diff --git a/flopy/modflow/mfswi2.py b/flopy/modflow/mfswi2.py index dfe4de9f98..4e4672458b 100644 --- a/flopy/modflow/mfswi2.py +++ b/flopy/modflow/mfswi2.py @@ -419,7 +419,7 @@ def write_file(self, check=True, f=None): ) # write SWI2 options - if self.options != None: + if self.options is not None: for o in self.options: f.write(f" {o}") f.write("\n") diff --git a/flopy/modpath/mp6.py b/flopy/modpath/mp6.py index 389a3d89d8..fe4c96868b 100644 --- a/flopy/modpath/mp6.py +++ b/flopy/modpath/mp6.py @@ -202,7 +202,7 @@ def next_ext_unit(self): return self.__next_ext_unit def getsim(self): - if self.__sim == None: + if self.__sim is None: for p in self.packagelist: if isinstance(p, Modpath6Sim): self.__sim = p diff --git a/flopy/modpath/mp6bas.py b/flopy/modpath/mp6bas.py index e15f7192df..7e9333f114 100644 --- a/flopy/modpath/mp6bas.py +++ b/flopy/modpath/mp6bas.py @@ -189,7 +189,7 @@ def _create_ltype(self, laytyp): # run though flow packages flow_package = self.parent.getmf().get_package("BCF6") - if flow_package != None: + if flow_package is not None: lc = Util2d( self.parent, (nlay,), @@ -201,7 +201,7 @@ def _create_ltype(self, laytyp): have_layertype = True flow_package = self.parent.getmf().get_package("LPF") - if flow_package != None and not have_layertype: + if flow_package is not None and not have_layertype: lc = Util2d( self.parent, (nlay,), @@ -212,7 +212,7 @@ def _create_ltype(self, laytyp): ) have_layertype = True flow_package = self.parent.getmf().get_package("UPW") - if flow_package != None and have_layertype: + if flow_package is not None and have_layertype: lc = Util2d( self.parent, (nlay,), diff --git a/flopy/modpath/mp7particledata.py b/flopy/modpath/mp7particledata.py index e388a128be..e799a0b524 100644 --- a/flopy/modpath/mp7particledata.py +++ b/flopy/modpath/mp7particledata.py @@ -384,7 +384,7 @@ def cvt_xy(p, vs): if grid.grid_type == "structured": if not hasattr(self.particledata, "k"): raise ValueError( - f"Particle representation is not structured but grid is" + "Particle representation is not structured but grid is" ) def cvt_z(p, k, i, j): @@ -407,7 +407,7 @@ def convert(row) -> Tuple[float, float, float]: else: if hasattr(self.particledata, "k"): raise ValueError( - f"Particle representation is structured but grid is not" + "Particle representation is structured but grid is not" ) def cvt_z(p, nn): @@ -776,7 +776,7 @@ def write(self, f=None): def get_release_points(subdivisiondata, grid, k=None, i=None, j=None, nn=None): if nn is None and (k is None or i is None or j is None): raise ValueError( - f"A cell (node) must be specified by indices (for structured grids) or node number (for vertex/unstructured)" + "A cell (node) must be specified by indices (for structured grids) or node number (for vertex/unstructured)" ) rpts = [] @@ -802,7 +802,7 @@ def get_release_points(subdivisiondata, grid, k=None, i=None, j=None, nn=None): ) else: raise ValueError( - f"A cell (node) must be specified by indices (for structured grids) or node number (for vertex/unstructured)" + "A cell (node) must be specified by indices (for structured grids) or node number (for vertex/unstructured)" ) xs, ys = list(zip(*verts)) minx, maxx = min(xs), max(xs) @@ -1131,7 +1131,7 @@ def to_prp(self, grid) -> Iterator[tuple]: if grid.grid_type != "structured": raise ValueError( - f"Particle representation is structured but grid is not" + "Particle representation is structured but grid is not" ) irpt_offset = 0 diff --git a/flopy/mt3d/mtbtn.py b/flopy/mt3d/mtbtn.py index 5b9298f29b..baddf1931c 100644 --- a/flopy/mt3d/mtbtn.py +++ b/flopy/mt3d/mtbtn.py @@ -715,23 +715,23 @@ def write_file(self): f_btn.write(f"{self.tunit:4s}{self.lunit:4s}{self.munit:4s}\n") # A5 - if self.parent.adv != None: + if self.parent.adv is not None: f_btn.write("T ") else: f_btn.write("F ") - if self.parent.dsp != None: + if self.parent.dsp is not None: f_btn.write("T ") else: f_btn.write("F ") - if self.parent.ssm != None: + if self.parent.ssm is not None: f_btn.write("T ") else: f_btn.write("F ") - if self.parent.rct != None: + if self.parent.rct is not None: f_btn.write("T ") else: f_btn.write("F ") - if self.parent.gcg != None: + if self.parent.gcg is not None: f_btn.write("T ") else: f_btn.write("F ") @@ -771,10 +771,7 @@ def write_file(self): f_btn.write( f"{self.ifmtcn:10d}{self.ifmtnp:10d}{self.ifmtrf:10d}{self.ifmtdp:10d}" ) - if self.savucn == True: - ss = "T" - else: - ss = "F" + ss = "T" if self.savucn else "F" f_btn.write(f"{ss:>10s}\n") # A16, A17 @@ -809,7 +806,7 @@ def write_file(self): ) # A20 CHKMAS, NPRMAS - if self.chkmas == True: + if self.chkmas: ss = "T" else: ss = "F" diff --git a/flopy/mt3d/mtlkt.py b/flopy/mt3d/mtlkt.py index 7304ac4b16..749744b8d0 100644 --- a/flopy/mt3d/mtlkt.py +++ b/flopy/mt3d/mtlkt.py @@ -258,7 +258,7 @@ def write_file(self): # (Loop through each stress period and write LKT information) nper = self.parent.nper for kper in range(nper): - if f_lkt.closed == True: + if f_lkt.closed: f_lkt = open(f_lkt.name, "a") # List of concentrations associated with fluxes in/out of lake diff --git a/flopy/mt3d/mtsft.py b/flopy/mt3d/mtsft.py index 11127d1fda..1aeade5b9a 100644 --- a/flopy/mt3d/mtsft.py +++ b/flopy/mt3d/mtsft.py @@ -431,7 +431,7 @@ def write_file(self): # Loop through each stress period and assign source & sink concentrations to stream features nper = self.parent.nper for kper in range(nper): - if f.closed == True: + if f.closed: f = open(f.name, "a") # List of concentrations associated with various boundaries diff --git a/flopy/mt3d/mtssm.py b/flopy/mt3d/mtssm.py index cad5c2c099..7bc8416f73 100644 --- a/flopy/mt3d/mtssm.py +++ b/flopy/mt3d/mtssm.py @@ -254,9 +254,9 @@ def __init__( self.mxss += (self.parent.btn.icbund < 0).sum() for p in self.__SsmPackages: - if (p.label == "BAS6") and (p.instance != None): + if (p.label == "BAS6") and (p.instance is not None): self.mxss += (p.instance.ibound.array < 0).sum() - elif p.instance != None: + elif p.instance is not None: self.mxss += p.instance._ncells() else: self.mxss = mxss @@ -454,7 +454,7 @@ def write_file(self): # Loop through each stress period and write ssm information nper = self.parent.nper for kper in range(nper): - if f_ssm.closed == True: + if f_ssm.closed: f_ssm = open(f_ssm.name, "a") # Distributed sources and sinks (Recharge and Evapotranspiration) @@ -494,7 +494,7 @@ def write_file(self): if self.stress_period_data is not None: self.stress_period_data.write_transient(f_ssm, single_per=kper) else: - f_ssm.write(f"0\n") + f_ssm.write("0\n") f_ssm.close() return diff --git a/flopy/mt3d/mtuzt.py b/flopy/mt3d/mtuzt.py index c8ff814202..e979aa9472 100644 --- a/flopy/mt3d/mtuzt.py +++ b/flopy/mt3d/mtuzt.py @@ -339,7 +339,7 @@ def write_file(self): # (Loop through each stress period and write uzt information) nper = self.parent.nper for kper in range(nper): - if f_uzt.closed == True: + if f_uzt.closed: f_uzt = open(f_uzt.name, "a") # Concentrations associated with distributed stresses (Infil, ET) diff --git a/flopy/pakbase.py b/flopy/pakbase.py index 27fb1592df..0b592888d0 100644 --- a/flopy/pakbase.py +++ b/flopy/pakbase.py @@ -210,7 +210,7 @@ def _get_kparams(self): if kp in self.__dict__: kparams[kp] = name if "hk" in self.__dict__: - if self.hk.shape[1] == None: + if self.hk.shape[1] is None: hk = np.asarray( [a.array.flatten() for a in self.hk], dtype=object ) @@ -219,7 +219,7 @@ def _get_kparams(self): else: hk = self.k.array.copy() if "vka" in self.__dict__ and self.layvka.sum() > 0: - if self.vka.shape[1] == None: + if self.vka.shape[1] is None: vka = np.asarray( [a.array.flatten() for a in self.vka], dtype=object ) @@ -509,7 +509,7 @@ def __repr__(self): s = self.__doc__ exclude_attributes = ["extension", "heading", "name", "parent", "url"] for attr, value in sorted(self.__dict__.items()): - if not (attr in exclude_attributes): + if attr not in exclude_attributes: if isinstance(value, list): if len(value) == 1: s += f" {attr} = {value[0]!s}\n" diff --git a/flopy/plot/__init__.py b/flopy/plot/__init__.py index 90473aee1e..c5a61d12c6 100644 --- a/flopy/plot/__init__.py +++ b/flopy/plot/__init__.py @@ -1,25 +1,25 @@ """ - the main entry point of utils +the main entry point of utils - Parameters - ---------- +Parameters +---------- - Attributes - ---------- +Attributes +---------- - Methods - ------- +Methods +------- - See Also - -------- +See Also +-------- - Notes - ----- +Notes +----- - Examples - -------- +Examples +-------- - """ +""" from .crosssection import PlotCrossSection from .map import PlotMapView diff --git a/flopy/plot/crosssection.py b/flopy/plot/crosssection.py index 6730433e51..6068fc9d74 100644 --- a/flopy/plot/crosssection.py +++ b/flopy/plot/crosssection.py @@ -141,7 +141,7 @@ def __init__( ln = line[onkey] if not PlotCrossSection._is_valid(ln): - raise ValueError(f"Invalid line representation") + raise ValueError("Invalid line representation") gu = GeoSpatialUtil(ln, shapetype="linestring") verts = gu.points diff --git a/flopy/plot/plotutil.py b/flopy/plot/plotutil.py index cef94770c7..84841f4e86 100644 --- a/flopy/plot/plotutil.py +++ b/flopy/plot/plotutil.py @@ -2417,12 +2417,10 @@ def intersect_modpath_with_crosssection( oppts[cell], ) idx = [ - i - for i, (x, y) in enumerate(zip(m0[0], m1[0])) - if x == y == True + i for i, (x, y) in enumerate(zip(m0[0], m1[0])) if x == y ] else: - idx = [i for i, x in enumerate(m0[0]) if x == True] + idx = [i for i, x in enumerate(m0[0]) if x] if idx: if cell not in idict: @@ -2685,7 +2683,7 @@ def parse_modpath_selection_options( def to_mp7_pathlines( - data: Union[np.recarray, pd.DataFrame] + data: Union[np.recarray, pd.DataFrame], ) -> Union[np.recarray, pd.DataFrame]: """ Convert MODFLOW 6 PRT pathline data to MODPATH 7 pathline format. @@ -2767,7 +2765,7 @@ def to_mp7_pathlines( def to_mp7_endpoints( - data: Union[np.recarray, pd.DataFrame] + data: Union[np.recarray, pd.DataFrame], ) -> Union[np.recarray, pd.DataFrame]: """ Convert MODFLOW 6 PRT pathline data to MODPATH 7 endpoint format. @@ -2886,7 +2884,7 @@ def to_mp7_endpoints( def to_prt_pathlines( - data: Union[np.recarray, pd.DataFrame] + data: Union[np.recarray, pd.DataFrame], ) -> Union[np.recarray, pd.DataFrame]: """ Convert MODPATH 7 pathline or endpoint data to MODFLOW 6 PRT pathline format. diff --git a/flopy/utils/__init__.py b/flopy/utils/__init__.py index cbab04dd9b..87e0b6e5c6 100644 --- a/flopy/utils/__init__.py +++ b/flopy/utils/__init__.py @@ -1,25 +1,25 @@ """ - the main entry point of utils +the main entry point of utils - Parameters - ---------- +Parameters +---------- - Attributes - ---------- +Attributes +---------- - Methods - ------- +Methods +------- - See Also - -------- +See Also +-------- - Notes - ----- +Notes +----- - Examples - -------- +Examples +-------- - """ +""" from .utl_import import import_optional_dependency # isort:skip from . import get_modflow as get_modflow_module diff --git a/flopy/utils/compare.py b/flopy/utils/compare.py index 61fd2f65c3..7aad59637d 100644 --- a/flopy/utils/compare.py +++ b/flopy/utils/compare.py @@ -564,7 +564,7 @@ def compare_heads( if files1 is None: # Get oc info, and return if OC not included in models ocf1 = get_entries_from_namefile(namefile1, "OC") - if not any(ocf1) is None: + if any(ocf1) is not None: return True hu1, hfpth1, du1, _ = ModflowOc.get_ocoutput_units(ocf1[0][0]) diff --git a/flopy/utils/crs.py b/flopy/utils/crs.py index a2009d62d0..fb4b33b5d2 100644 --- a/flopy/utils/crs.py +++ b/flopy/utils/crs.py @@ -1,5 +1,4 @@ -"""Utilities related to coordinate reference system handling. -""" +"""Utilities related to coordinate reference system handling.""" import warnings from pathlib import Path diff --git a/flopy/utils/datafile.py b/flopy/utils/datafile.py index 6541d4ba60..6477ecfe02 100644 --- a/flopy/utils/datafile.py +++ b/flopy/utils/datafile.py @@ -274,7 +274,7 @@ def to_shapefile( kstpkper=kstpkper, totim=totim, mflay=mflay ).transpose() ).transpose() - if mflay != None: + if mflay is not None: attrib_dict = {f"{attrib_name}{mflay}": plotarray[0, :, :]} else: attrib_dict = {} diff --git a/flopy/utils/flopy_io.py b/flopy/utils/flopy_io.py index caa8532ed8..126d47e904 100644 --- a/flopy/utils/flopy_io.py +++ b/flopy/utils/flopy_io.py @@ -291,7 +291,7 @@ def flux_to_wel(cbc_file, text, precision="single", model=None, verbose=False): # create a empty numpy array of shape (time,layer,row,col) m4d = np.zeros((cbf.nper, cbf.nlay, cbf.nrow, cbf.ncol), dtype=np.float32) - m4d[:] = np.NaN + m4d[:] = np.nan # process the records in the cell budget file iper = -1 @@ -305,7 +305,7 @@ def flux_to_wel(cbc_file, text, precision="single", model=None, verbose=False): arr = arr[0] print(arr.max(), arr.min(), arr.sum()) # masked where zero - arr[np.where(arr == 0.0)] = np.NaN + arr[np.where(arr == 0.0)] = np.nan m4d[iper + 1] = arr iper += 1 diff --git a/flopy/utils/get_modflow.py b/flopy/utils/get_modflow.py index d2b13122c0..871879baa6 100755 --- a/flopy/utils/get_modflow.py +++ b/flopy/utils/get_modflow.py @@ -7,6 +7,7 @@ See https://developer.github.com/v3/repos/releases/ for GitHub Releases API. """ + import json import os import shutil diff --git a/flopy/utils/gridutil.py b/flopy/utils/gridutil.py index bd428c8fe2..4c1366aa4d 100644 --- a/flopy/utils/gridutil.py +++ b/flopy/utils/gridutil.py @@ -33,9 +33,9 @@ def get_lni(ncpl, nodes) -> List[Tuple[int, int]]: """ if not isinstance(ncpl, (int, list, tuple, np.ndarray)): - raise ValueError(f"ncpl must be int or array-like") + raise ValueError("ncpl must be int or array-like") if not isinstance(nodes, (list, tuple, np.ndarray)): - raise ValueError(f"nodes must be array-like") + raise ValueError("nodes must be array-like") if len(nodes) == 0: return [] diff --git a/flopy/utils/mflistfile.py b/flopy/utils/mflistfile.py index b24cab7a2a..38d4b21936 100644 --- a/flopy/utils/mflistfile.py +++ b/flopy/utils/mflistfile.py @@ -706,7 +706,7 @@ def _set_entries(self): for entry in self.entries: incdict[entry] = [] cumdict[entry] = [] - null_entries[entry] = np.NaN + null_entries[entry] = np.nan self.null_entries = [null_entries, null_entries] return incdict, cumdict @@ -863,12 +863,12 @@ def _parse_budget_line(self, line): cumu = float(cu_str) except: if "NAN" in cu_str.strip().upper(): - cumu = np.NaN + cumu = np.nan try: flux = float(fx_str) except: if "NAN" in fx_str.strip().upper(): - flux = np.NaN + flux = np.nan return entry, flux, cumu def _get_totim(self, ts, sp, seekpoint): @@ -883,7 +883,7 @@ def _get_totim(self, ts, sp, seekpoint): "end of file found while seeking budget " "information for ts,sp: {} {}".format(ts, sp) ) - return np.NaN, np.NaN, np.NaN + return np.nan, np.nan, np.nan elif ( ihead == 2 and "SECONDS MINUTES HOURS DAYS YEARS" @@ -902,22 +902,22 @@ def _get_totim(self, ts, sp, seekpoint): line = self.f.readline() if translen is None: print("error parsing translen for ts,sp", ts, sp) - return np.NaN, np.NaN, np.NaN + return np.nan, np.nan, np.nan tslen = self._parse_time_line(line) if tslen is None: print("error parsing tslen for ts,sp", ts, sp) - return np.NaN, np.NaN, np.NaN + return np.nan, np.nan, np.nan sptim = self._parse_time_line(self.f.readline()) if sptim is None: print("error parsing sptim for ts,sp", ts, sp) - return np.NaN, np.NaN, np.NaN + return np.nan, np.nan, np.nan totim = self._parse_time_line(self.f.readline()) if totim is None: print("error parsing totim for ts,sp", ts, sp) - return np.NaN, np.NaN, np.NaN + return np.nan, np.nan, np.nan return tslen, sptim, totim def _parse_time_line(self, line): diff --git a/flopy/utils/rasters.py b/flopy/utils/rasters.py index dbba705108..72e32eabff 100644 --- a/flopy/utils/rasters.py +++ b/flopy/utils/rasters.py @@ -45,7 +45,7 @@ class Raster: """ - FLOAT32 = (float, np.float32, np.float_) + FLOAT32 = (float, np.float32, np.float64) FLOAT64 = (np.float64,) INT8 = (np.int8, np.uint8) INT16 = (np.int16, np.uint16) @@ -688,7 +688,7 @@ def get_array(self, band, masked=True): """ Method to get a numpy array corresponding to the provided raster band. Nodata vals are set to - np.NaN + np.nan Parameters ---------- diff --git a/flopy/utils/recarray_utils.py b/flopy/utils/recarray_utils.py index 0712eda8fc..27114c732d 100644 --- a/flopy/utils/recarray_utils.py +++ b/flopy/utils/recarray_utils.py @@ -34,7 +34,7 @@ def create_empty_recarray(length, dtype, default_value=0): assert isinstance(dtype, np.dtype), msg for name in dtype.names: dt = dtype.fields[name][0] - if np.issubdtype(dt, np.float_): + if np.issubdtype(dt, np.float64): r[name] = default_value return r.view(np.recarray) diff --git a/flopy/utils/util_array.py b/flopy/utils/util_array.py index 18923e8aa9..3d999e75f8 100644 --- a/flopy/utils/util_array.py +++ b/flopy/utils/util_array.py @@ -1405,7 +1405,7 @@ def from_4d(cls, model, pak_name, m4ds): pak_name : str package name (e.g. RCH) m4ds : dict(name,(masked) 4d numpy.ndarray) each ndarray must have shape (nper,1,nrow,ncol). - if an entire (nrow,ncol) slice is np.NaN, then + if an entire (nrow,ncol) slice is np.nan, then that kper is skipped. Returns ------- diff --git a/flopy/utils/util_list.py b/flopy/utils/util_list.py index dad0b7a5da..d1274cc0cb 100644 --- a/flopy/utils/util_list.py +++ b/flopy/utils/util_list.py @@ -1028,7 +1028,7 @@ def to_array(self, kper=0, mask=False): kper : int MODFLOW zero-based stress period number to return. (default is zero) mask : boolean - return array with np.NaN instead of zero + return array with np.nan instead of zero Returns ---------- out : dict of numpy.ndarrays @@ -1079,7 +1079,7 @@ def to_array(self, kper=0, mask=False): if kper < kpers[0]: if mask: for name, arr in arrays.items(): - arrays[name][:] = np.NaN + arrays[name][:] = np.nan return arrays # find the last kper else: @@ -1094,7 +1094,7 @@ def to_array(self, kper=0, mask=False): if sarr == 0: if mask: for name, arr in arrays.items(): - arrays[name][:] = np.NaN + arrays[name][:] = np.nan return arrays raise ValueError( f"MfList: expected no entries for period {kper} but found {sarr}" @@ -1124,12 +1124,12 @@ def to_array(self, kper=0, mask=False): arr[idx] /= cnt[idx] if mask: arr = np.ma.masked_where(cnt == 0.0, arr) - arr[cnt == 0.0] = np.NaN + arr[cnt == 0.0] = np.nan arrays[name] = arr.copy() # elif mask: # for name, arr in arrays.items(): - # arrays[name][:] = np.NaN + # arrays[name][:] = np.nan return arrays @property diff --git a/pyproject.toml b/pyproject.toml index 0069f510ab..3728c793a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,11 +38,8 @@ dynamic = ["version", "readme"] [project.optional-dependencies] dev = ["flopy[lint,test,optional,doc]"] lint = [ - "black", "cffconvert", - "flake8", - "isort", - "pylint", + "ruff" ] test = [ "flopy[lint]", @@ -115,11 +112,31 @@ include = ["flopy", "flopy.*"] "flopy.mf6.data" = ["dfn/*.dfn"] "flopy.plot" = ["mplstyle/*.mplstyle"] -[tool.black] +[tool.ruff] line-length = 79 -target_version = ["py38"] +target-version = "py38" +include = [ + "pyproject.toml", + "flopy/**/*.py", + "autotest/**/*.py", + "examples/**/*.py", + "scripts/**/*.py", + ".docs/**/*.py", +] +extend-include = [ + "examples/**/*.ipynb" +] -[tool.isort] -profile = "black" -src_paths = ["flopy"] -line_length = 79 \ No newline at end of file +[tool.ruff.lint] +ignore = [ + "E402", # module level import not at top of file + "E712", # Avoid equality comparisons to `True` + "E722", # do not use bare `except` + "E741", # ambiguous variable name + "F401", # unused import + "F403", # unable to detect undefined names (star imports) + "F524", # `.format` missing argument(s) for placeholder(s) + "F811", # Redefinition of unused variable + "F821", # undefined name TODO FIXME + "F841", # local variable assigned but never used +] \ No newline at end of file diff --git a/scripts/process_benchmarks.py b/scripts/process_benchmarks.py index d61e8b4532..1b29da52e2 100644 --- a/scripts/process_benchmarks.py +++ b/scripts/process_benchmarks.py @@ -62,7 +62,7 @@ def get_benchmarks(paths): # create data frame and save to CSV benchmarks_df = pd.DataFrame(get_benchmarks(json_paths)) benchmarks_df["time"] = pd.to_datetime(benchmarks_df["time"]) -benchmarks_df.to_csv(str(outdir / f"benchmarks.csv"), index=False) +benchmarks_df.to_csv(str(outdir / "benchmarks.csv"), index=False) def matplotlib_plot(stats): diff --git a/scripts/update_version.py b/scripts/update_version.py index 4720d98fbe..241591ff94 100644 --- a/scripts/update_version.py +++ b/scripts/update_version.py @@ -93,7 +93,7 @@ def get_software_citation( sb = "" if not approved: - sb = f" (preliminary)" + sb = " (preliminary)" # format author names authors = [] for author in citation["authors"]: @@ -168,7 +168,7 @@ def update_readme_markdown( if "### Version " in line: line = f"### Version {version}" if not approved: - line += f" (preliminary)" + line += " (preliminary)" elif "[flopy continuous integration]" in line: line = ( "[![flopy continuous integration](https://github.com/"