diff --git a/.docs/Notebooks/export_vtk_tutorial.py b/.docs/Notebooks/export_vtk_tutorial.py index b95c095199..a45c3b5b07 100644 --- a/.docs/Notebooks/export_vtk_tutorial.py +++ b/.docs/Notebooks/export_vtk_tutorial.py @@ -211,16 +211,16 @@ # Create a vtk object vtkobj = vtk.Vtk(ml, vertical_exageration=10) -## create some random array data +# create some random array data r_array = np.random.random(ml.modelgrid.nnodes) * 100 -## add random data to the VTK object +# add random data to the VTK object vtkobj.add_array(r_array, "random_data") -## add the model botom data to the VTK object +# add the model botom data to the VTK object vtkobj.add_array(ml.dis.botm.array, "botm") -## write the vtk object to file +# write the vtk object to file vtkobj.write(output_dir / "Array_example" / "model.vtu") # - @@ -237,12 +237,12 @@ # create a vtk object vtkobj = vtk.Vtk(ml, xml=True, pvd=True, vertical_exageration=10) -## add recharge to the VTK object +# add recharge to the VTK object subset = list(range(10)) recharge = {k: v for k, v in ml.rch.rech.transient_2ds.items() if k in subset} vtkobj.add_transient_array(recharge, "recharge", masked_values=[0]) -## write vtk files +# write vtk files vtkobj.write(output_dir / "tr_array_example" / "recharge.vtu") # - @@ -258,11 +258,11 @@ # create the vtk object vtkobj = vtk.Vtk(ml, xml=True, pvd=True, vertical_exageration=10) -## add well fluxes to the VTK object +# add well fluxes to the VTK object spd = ml.wel.stress_period_data vtkobj.add_transient_list(spd, masked_values=[0]) -## write vtk files (skipped, slow) +# write vtk files (skipped, slow) # vtkobj.write(output_dir / "tr_list_example" / "wel_flux.vtu") # - diff --git a/.docs/Notebooks/groundwater2023_watershed_example.py b/.docs/Notebooks/groundwater2023_watershed_example.py index a0311330df..b6e9e8e49a 100644 --- a/.docs/Notebooks/groundwater2023_watershed_example.py +++ b/.docs/Notebooks/groundwater2023_watershed_example.py @@ -101,7 +101,7 @@ def set_idomain(grid, boundary): nr = idx.shape[0] if idx.ndim == 1: idx = idx.reshape((nr, 1)) - idx = tuple([idx[:, i] for i in range(idx.shape[1])]) + idx = tuple(idx[:, i] for i in range(idx.shape[1])) idomain = np.zeros(grid.shape[1:], dtype=int) idomain[idx] = 1 idomain = idomain.reshape(grid.shape) diff --git a/.docs/Notebooks/mf6_support_example.py b/.docs/Notebooks/mf6_support_example.py index faad6f3a2b..3a914be6ee 100644 --- a/.docs/Notebooks/mf6_support_example.py +++ b/.docs/Notebooks/mf6_support_example.py @@ -521,7 +521,7 @@ # + # get hydraulic conductivity data object from the data dictionary -hk = sim.simulation_data.mfdata[(model_name, "npf", "griddata", "k")] +hk = sim.simulation_data.mfdata[model_name, "npf", "griddata", "k"] # get specific yield data object from the storage package sy = sto_package.sy diff --git a/.docs/Notebooks/mf_tutorial02.py b/.docs/Notebooks/mf_tutorial02.py index 345d329aab..a6fe3a7295 100644 --- a/.docs/Notebooks/mf_tutorial02.py +++ b/.docs/Notebooks/mf_tutorial02.py @@ -176,7 +176,7 @@ stress_period_data = {} for kper in range(nper): for kstp in range(nstp[kper]): - stress_period_data[(kper, kstp)] = [ + stress_period_data[kper, kstp] = [ "save head", "save drawdown", "save budget", diff --git a/.docs/Notebooks/mfusg_conduit_examples.py b/.docs/Notebooks/mfusg_conduit_examples.py index 4d50423829..bda7588b6e 100644 --- a/.docs/Notebooks/mfusg_conduit_examples.py +++ b/.docs/Notebooks/mfusg_conduit_examples.py @@ -85,7 +85,7 @@ spd = {} for i in range(mf.nper): for j in range(mf.dis.nstp[i]): - spd[(i, j)] = ["save head", "save budget"] + spd[i, j] = ["save head", "save budget"] oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, unitnumber=[22, 30, 31, 50]) @@ -240,7 +240,7 @@ spd = {} for i in range(mf.nper): for j in range(mf.dis.nstp[i]): - spd[(i, j)] = ["save head", "save budget"] + spd[i, j] = ["save head", "save budget"] oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd) diff --git a/.docs/Notebooks/mfusg_transport_Ex8_Lake.py b/.docs/Notebooks/mfusg_transport_Ex8_Lake.py index f7e22b2f16..eddbb170bb 100644 --- a/.docs/Notebooks/mfusg_transport_Ex8_Lake.py +++ b/.docs/Notebooks/mfusg_transport_Ex8_Lake.py @@ -147,13 +147,13 @@ ibound = [] for ilay in range(nlay): laybnd = np.ones((nrow, ncol)) - laybnd[0, :] = -1 ##CHD cells - laybnd[-1, :] = -1 ##CHD cells - laybnd[:, 0] = -1 ##CHD cells - laybnd[:, -1] = -1 ##CHD cells - if ilay == 0: ##Lake cells + laybnd[0, :] = -1 # CHD cells + laybnd[-1, :] = -1 # CHD cells + laybnd[:, 0] = -1 # CHD cells + laybnd[:, -1] = -1 # CHD cells + if ilay == 0: # Lake cells laybnd[6:11, 6:11] = 0 - if ilay == 1: ##Lake cells + if ilay == 1: # Lake cells laybnd[7:10, 7:10] = 0 laybnd = laybnd.reshape(-1) ibound.append(laybnd) @@ -166,13 +166,13 @@ wetdry = [] for ilay in range(nlay): layv = np.ones((nrow, ncol)) - layv[0, :] = 0.0 ##CHD cells - layv[-1, :] = 0.0 ##CHD cells - layv[:, 0] = 0.0 ##CHD cells - layv[:, -1] = 0.0 ##CHD cells - if ilay == 0: ##Lake cells + layv[0, :] = 0.0 # CHD cells + layv[-1, :] = 0.0 # CHD cells + layv[:, 0] = 0.0 # CHD cells + layv[:, -1] = 0.0 # CHD cells + if ilay == 0: # Lake cells layv[6:11, 6:11] = 0.0 - if ilay == 1: ##Lake cells + if ilay == 1: # Lake cells layv[7:10, 7:10] = 0.0 layv = layv.reshape(-1) wetdry.append(layv) diff --git a/.docs/Notebooks/mt3dms_sft_lkt_uzt_tutorial.py b/.docs/Notebooks/mt3dms_sft_lkt_uzt_tutorial.py index 7732c50b31..5c4725276b 100644 --- a/.docs/Notebooks/mt3dms_sft_lkt_uzt_tutorial.py +++ b/.docs/Notebooks/mt3dms_sft_lkt_uzt_tutorial.py @@ -208,7 +208,7 @@ # Next variables are: LAYTYP, LAYAVG, CHANI, LAYVKA, LAYWET laytyp = [1, 3, 3] # >0: convertible -layavg = 0 # 0: harmonic mean +layavg = 0 # 0: harmonic mean chani = 1.0 # >0: CHANI is the horizontal anisotropy for the entire layer layvka = 0 # =0: indicates VKA is vertical hydraulic conductivity laywet = 0 # Always set equal to zero in UPW package diff --git a/.docs/Notebooks/plot_cross_section_example.py b/.docs/Notebooks/plot_cross_section_example.py index 75df9a323b..38f3062bbd 100644 --- a/.docs/Notebooks/plot_cross_section_example.py +++ b/.docs/Notebooks/plot_cross_section_example.py @@ -1058,8 +1058,8 @@ def run_vertex_grid_example(ws): obs1 = (49, 1, 119) # Layer, row, and column for observation 1 obs2 = (77, 1, 359) # Layer, row, and column for observation 2 -obs1 = tuple([i - 1 for i in obs1]) -obs2 = tuple([i - 1 for i in obs2]) +obs1 = tuple(i - 1 for i in obs1) +obs2 = tuple(i - 1 for i in obs2) seconds_to_days = 24.0 * 60.0 * 60.0 permeability_to_conductivity = 1000.0 * 9.81 / 1.0e-3 * seconds_to_days hka = hka * permeability_to_conductivity diff --git a/.docs/Notebooks/shapefile_export_example.py b/.docs/Notebooks/shapefile_export_example.py index 99f3b21518..c542a71a84 100644 --- a/.docs/Notebooks/shapefile_export_example.py +++ b/.docs/Notebooks/shapefile_export_example.py @@ -224,7 +224,7 @@ # + from flopy.utils.geometry import LineString -### make up a linestring shapefile of the river reaches +# make up a linestring shapefile of the river reaches i, j = m.riv.stress_period_data[0].i, m.riv.stress_period_data[0].j x0 = grid.xyzcellcenters[0][i[0], j[0]] x1 = grid.xyzcellcenters[0][i[-1], j[-1]] diff --git a/.docs/Notebooks/swi2package_example1.py b/.docs/Notebooks/swi2package_example1.py index 9cc1b9a962..755ab29fae 100644 --- a/.docs/Notebooks/swi2package_example1.py +++ b/.docs/Notebooks/swi2package_example1.py @@ -104,8 +104,8 @@ # + spd = {} for istp in range(49, nstp + 1, 50): - spd[(0, istp)] = ["save head", "print budget"] - spd[(0, istp + 1)] = [] + spd[0, istp] = ["save head", "print budget"] + spd[0, istp + 1] = [] oc = flopy.modflow.ModflowOc(ml, stress_period_data=spd) pcg = flopy.modflow.ModflowPcg(ml) diff --git a/.docs/Notebooks/swi2package_example5.py b/.docs/Notebooks/swi2package_example5.py index 2a54f70f4c..c4095df536 100644 --- a/.docs/Notebooks/swi2package_example5.py +++ b/.docs/Notebooks/swi2package_example5.py @@ -186,10 +186,10 @@ for j in range(0, nstp[i]): icnt += 1 if icnt == 365: - ocspd[(i, j)] = ["save head"] + ocspd[i, j] = ["save head"] icnt = 0 else: - ocspd[(i, j)] = [] + ocspd[i, j] = [] solver2params = { "mxiter": 100, diff --git a/.docs/Notebooks/vtk_pathlines_example.py b/.docs/Notebooks/vtk_pathlines_example.py index 738dc412b6..5fc17652d8 100644 --- a/.docs/Notebooks/vtk_pathlines_example.py +++ b/.docs/Notebooks/vtk_pathlines_example.py @@ -279,7 +279,7 @@ def fill_zone_1(): release_locs = np.array(release_locs) tracks = {k: np.array(v, dtype=object) for k, v in tracks.items()} -max_track_len = max([len(v) for v in tracks.values()]) +max_track_len = max(len(v) for v in tracks.values()) print("The maximum number of locations per particle track is", max_track_len) # - diff --git a/.docs/pysrc/tutorial2.py b/.docs/pysrc/tutorial2.py index 4c08fd3853..6e3f8b2d27 100644 --- a/.docs/pysrc/tutorial2.py +++ b/.docs/pysrc/tutorial2.py @@ -101,7 +101,7 @@ stress_period_data = {} for kper in range(nper): for kstp in range(nstp[kper]): - stress_period_data[(kper, kstp)] = [ + stress_period_data[kper, kstp] = [ "save head", "save drawdown", "save budget", diff --git a/autotest/conftest.py b/autotest/conftest.py index 9c44d46b6a..036ce9e675 100644 --- a/autotest/conftest.py +++ b/autotest/conftest.py @@ -114,7 +114,7 @@ def pytest_report_header(config): extra = {} for item in metadata.requires("flopy"): pkg_name = re.findall(r"[a-z0-9_\-]+", item, re.IGNORECASE)[0] - if res := re.findall("extra == ['\"](.+)['\"]", item): + if res := re.findall(r"extra == ['\"](.+)['\"]", item): assert len(res) == 1, item pkg_extra = res[0] if pkg_extra not in extra: diff --git a/autotest/regression/test_mf6.py b/autotest/regression/test_mf6.py index 10e40afa09..49a5fcf020 100644 --- a/autotest/regression/test_mf6.py +++ b/autotest/regression/test_mf6.py @@ -3508,11 +3508,11 @@ def test001a_tharmonic(function_tmpdir, example_data_path): head_new = function_tmpdir / "flow15_flow.hds" assert compare_heads(None, None, files1=[expected_head_file_a], files2=[head_new]) - budget_frf = sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] + budget_frf = sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"] assert array_util.array_comp(budget_frf_valid, budget_frf) # change some settings - hk_data = sim.simulation_data.mfdata[(model_name, "npf", "griddata", "k")] + hk_data = sim.simulation_data.mfdata[model_name, "npf", "griddata", "k"] hk_array = hk_data.get_data() hk_array[0, 0, 1] = 20.0 hk_data.set_data(hk_array) @@ -3558,7 +3558,7 @@ def test001a_tharmonic(function_tmpdir, example_data_path): head_new = os.path.join(save_folder, "flow15_flow.hds") assert compare_heads(None, None, files1=[expected_head_file_b], files2=[head_new]) - budget_frf = sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] + budget_frf = sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"] assert array_util.array_comp(budget_frf_valid, budget_frf) @@ -3600,7 +3600,7 @@ def test003_gwfs_disv(function_tmpdir, example_data_path): head_new = os.path.join(function_tmpdir, "model.hds") assert compare_heads(None, None, files1=[expected_head_file_a], files2=[head_new]) - budget_frf = sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] + budget_frf = sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"] assert array_util.array_comp(budget_fjf_valid, budget_frf) model = sim.get_model(model_name) @@ -3636,7 +3636,7 @@ def test003_gwfs_disv(function_tmpdir, example_data_path): head_new = os.path.join(save_folder, "model.hds") assert compare_heads(None, None, files1=[expected_head_file_b], files2=[head_new]) - budget_frf = sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] + budget_frf = sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"] assert array_util.array_comp(budget_fjf_valid, budget_frf) @@ -3965,9 +3965,7 @@ def test006_gwf3(function_tmpdir, example_data_path): files2=[head_new], ) - budget_fjf = np.array( - sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] - ) + budget_fjf = np.array(sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"]) assert array_util.array_comp(np.array(budget_fjf_valid), np.array(budget_fjf)) # change some settings @@ -4010,9 +4008,7 @@ def test006_gwf3(function_tmpdir, example_data_path): files2=[head_new], ) - budget_fjf = np.array( - sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] - ) + budget_fjf = np.array(sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"]) assert array_util.array_comp(np.array(budget_fjf_valid), np.array(budget_fjf)) # confirm that files did move @@ -4054,9 +4050,7 @@ def test006_gwf3(function_tmpdir, example_data_path): files2=[head_new], ) - budget_fjf = np.array( - sim.simulation_data.mfdata[(model_name, "CBC", "FLOW-JA-FACE")] - ) + budget_fjf = np.array(sim.simulation_data.mfdata[model_name, "CBC", "FLOW-JA-FACE"]) assert array_util.array_comp(np.array(budget_fjf_valid), np.array(budget_fjf)) # confirm that files did not move @@ -4550,22 +4544,20 @@ def test036_twrihfb(function_tmpdir, example_data_path): # change some settings hydchr = sim.simulation_data.mfdata[ - (model_name, "hfb", "period", "stress_period_data") + model_name, "hfb", "period", "stress_period_data" ] hydchr_data = hydchr.get_data() hydchr_data[0][2][2] = 0.000002 hydchr_data[0][3][2] = 0.000003 hydchr_data[0][4][2] = 0.0000004 hydchr.set_data(hydchr_data[0], 0) - cond = sim.simulation_data.mfdata[ - (model_name, "drn", "period", "stress_period_data") - ] + cond = sim.simulation_data.mfdata[model_name, "drn", "period", "stress_period_data"] cond_data = cond.get_data() for index in range(0, len(cond_data[0])): cond_data[0][index][2] = 2.1 cond.set_data(cond_data[0], 0) - rch = sim.simulation_data.mfdata[(model_name, "rcha", "period", "recharge")] + rch = sim.simulation_data.mfdata[model_name, "rcha", "period", "recharge"] rch_data = rch.get_data() assert rch_data[0][5, 1] == 0.00000003 diff --git a/autotest/regression/test_modflow.py b/autotest/regression/test_modflow.py index 97fefe6195..5c27991501 100644 --- a/autotest/regression/test_modflow.py +++ b/autotest/regression/test_modflow.py @@ -44,11 +44,11 @@ def test_uzf_unit_numbers(function_tmpdir, uzf_example_path): spd = {} for iper in range(1, m.dis.nper): for istp in [0, 4, 9, 14]: - spd[(iper, istp)] = output - spd[(0, 0)] = output - spd[(1, 1)] = output - spd[(1, 2)] = output - spd[(1, 3)] = output + spd[iper, istp] = output + spd[0, 0] = output + spd[1, 1] = output + spd[1, 2] = output + spd[1, 3] = output oc = ModflowOc(m, stress_period_data=spd) oc.write_file() diff --git a/autotest/test_binaryfile_reverse.py b/autotest/test_binaryfile_reverse.py index 5ed5c848be..fc32a8e31b 100644 --- a/autotest/test_binaryfile_reverse.py +++ b/autotest/test_binaryfile_reverse.py @@ -189,3 +189,7 @@ def test_reverse(case, make_sim, function_tmpdir): bud = budget_file.get_data(text=BUDTXT, totim=t)[0] bud_rev = budget_file_rev.get_data(text=BUDTXT, totim=rt)[0] assert np.allclose(bud, -bud_rev) + + # reverse inplace + budget_file_rev = CellBudgetFile(budget_file_rev_path) + budget_file_rev.reverse(budget_file_rev_path) diff --git a/autotest/test_binarygrid_util.py b/autotest/test_binarygrid_util.py index 1b231e3c75..fb4f09aa22 100644 --- a/autotest/test_binarygrid_util.py +++ b/autotest/test_binarygrid_util.py @@ -51,7 +51,7 @@ def test_mfgrddis_modelgrid(mfgrd_test_path): nvert = modelgrid.nvert iverts = modelgrid.iverts - maxvertex = max([max(sublist[1:]) for sublist in iverts]) + maxvertex = max(max(sublist[1:]) for sublist in iverts) assert maxvertex + 1 == nvert, f"nvert ({maxvertex + 1}) does not equal {nvert}" verts = modelgrid.verts assert nvert == verts.shape[0], ( @@ -99,7 +99,7 @@ def test_mfgrddisv_modelgrid(mfgrd_test_path): nvert = mg.nvert iverts = mg.iverts - maxvertex = max([max(sublist[1:]) for sublist in iverts]) + maxvertex = max(max(sublist[1:]) for sublist in iverts) assert maxvertex + 1 == nvert, f"nvert ({maxvertex + 1}) does not equal {nvert}" verts = mg.verts assert nvert == verts.shape[0], ( @@ -153,7 +153,7 @@ def test_mfgrddisu_modelgrid(mfgrd_test_path): nvert = mg.nvert iverts = mg.iverts - maxvertex = max([max(sublist[1:]) for sublist in iverts]) + maxvertex = max(max(sublist[1:]) for sublist in iverts) assert maxvertex + 1 == nvert, f"nvert ({maxvertex + 1}) does not equal {nvert}" verts = mg.verts assert nvert == verts.shape[0], ( diff --git a/autotest/test_compare.py b/autotest/test_compare.py index ffa3aaae5c..36353d603c 100644 --- a/autotest/test_compare.py +++ b/autotest/test_compare.py @@ -15,8 +15,8 @@ ModflowWel, ) from flopy.utils.compare import ( - _diffmax, - _difftol, + _diffmax, # noqa: PLC2701 + _difftol, # noqa: PLC2701 compare_budget, compare_heads, ) diff --git a/autotest/test_copy.py b/autotest/test_copy.py index ec10738da7..e466d5007f 100644 --- a/autotest/test_copy.py +++ b/autotest/test_copy.py @@ -113,7 +113,7 @@ def package_is_copy(pk1, pk2): return False elif isinstance(v, ModelInterface): # weak, but calling model_eq would result in recursion - if v.__repr__() != v2.__repr__(): + if repr(v) != repr(v2): return False elif isinstance(v, DataInterface): if v != v2: diff --git a/autotest/test_example_notebooks.py b/autotest/test_example_notebooks.py index 04654a9648..5721a042e6 100644 --- a/autotest/test_example_notebooks.py +++ b/autotest/test_example_notebooks.py @@ -38,10 +38,10 @@ def test_notebooks(notebook): # expect all dependencies to be present and notebooks to pass in ci tests. if returncode != 0 and not is_in_ci(): if "Missing optional dependency" in stderr: - pkg = re.findall("Missing optional dependency '(.*)'", stderr)[0] + pkg = re.findall(r"Missing optional dependency '(.*)'", stderr)[0] pytest.skip(f"notebook requires optional dependency {pkg!r}") elif "No module named " in stderr: - pkg = re.findall("No module named '(.*)'", stderr)[0] + pkg = re.findall(r"No module named '(.*)'", stderr)[0] pytest.skip(f"notebook requires package {pkg!r}") if returncode != 0: diff --git a/autotest/test_export.py b/autotest/test_export.py index 4dc8bd718e..fa5064f2bd 100644 --- a/autotest/test_export.py +++ b/autotest/test_export.py @@ -1545,7 +1545,7 @@ def test_vtk_to_pyvista(function_tmpdir): vtk.add_pathline_points(pls) grid, pathlines = vtk.to_pyvista() - n_pts = sum([pl.shape[0] for pl in pls]) + n_pts = sum(pl.shape[0] for pl in pls) assert pathlines.n_points == n_pts assert pathlines.n_cells == n_pts + len(pls) assert "particleid" in pathlines.point_data diff --git a/autotest/test_grid.py b/autotest/test_grid.py index cfae55a21d..f85693557c 100644 --- a/autotest/test_grid.py +++ b/autotest/test_grid.py @@ -451,7 +451,7 @@ def test_structured_from_gridspec(example_data_path, spc_file): nvert = modelgrid.nvert iverts = modelgrid.iverts - maxvertex = max([max(sublist[1:]) for sublist in iverts]) + maxvertex = max(max(sublist[1:]) for sublist in iverts) assert maxvertex + 1 == nvert, f"nvert ({maxvertex + 1}) does not equal {nvert}" verts = modelgrid.verts assert nvert == verts.shape[0], ( @@ -554,8 +554,8 @@ def unstructured_from_gridspec_driver(example_data_path, gsf_file): assert any(ycc == en[2] for ycc in grid.ycellcenters) # check elevation - assert max(grid.top) == max([xyz[2] for xyz in expected_verts]) - assert min(grid.botm) == min([xyz[2] for xyz in expected_verts]) + assert max(grid.top) == max(xyz[2] for xyz in expected_verts) + assert min(grid.botm) == min(xyz[2] for xyz in expected_verts) def test_unstructured_from_gridspec(example_data_path): diff --git a/autotest/test_lgr.py b/autotest/test_lgr.py index fc20a1ae43..ee37f99a27 100644 --- a/autotest/test_lgr.py +++ b/autotest/test_lgr.py @@ -137,7 +137,7 @@ def singleModel( spd = {} for kper in range(nper): for kstp in range(nstp[kper]): - spd[(kper, kstp)] = ["save head", "save budget"] + spd[kper, kstp] = ["save head", "save budget"] oc = flopy.modflow.ModflowOc( mf, stress_period_data=spd, diff --git a/autotest/test_lgrutil.py b/autotest/test_lgrutil.py index e064fc4d87..1afe86ec03 100644 --- a/autotest/test_lgrutil.py +++ b/autotest/test_lgrutil.py @@ -197,10 +197,10 @@ def test_lgrutil3(): lgrtodisv = LgrToDisv(lgr) # test guts of LgrToDisv to make sure hanging vertices added correctly - assert lgrtodisv.right_face_hanging[(1, 0)] == [0, 4, 8, 12] - assert lgrtodisv.left_face_hanging[(1, 2)] == [3, 7, 11, 15] - assert lgrtodisv.back_face_hanging[(2, 1)] == [12, 13, 14, 15] - assert lgrtodisv.front_face_hanging[(0, 1)] == [0, 1, 2, 3] + assert lgrtodisv.right_face_hanging[1, 0] == [0, 4, 8, 12] + assert lgrtodisv.left_face_hanging[1, 2] == [3, 7, 11, 15] + assert lgrtodisv.back_face_hanging[2, 1] == [12, 13, 14, 15] + assert lgrtodisv.front_face_hanging[0, 1] == [0, 1, 2, 3] assert lgrtodisv.iverts[1] == [1, 2, 6, 18, 17, 5] assert lgrtodisv.iverts[3] == [4, 5, 20, 24, 9, 8] diff --git a/autotest/test_modflow.py b/autotest/test_modflow.py index 029acecd8e..6e8ecea38e 100644 --- a/autotest/test_modflow.py +++ b/autotest/test_modflow.py @@ -1340,7 +1340,7 @@ def test_model_init_time(function_tmpdir, benchmark): def test_model_write_time(function_tmpdir, benchmark): name = inspect.getframeinfo(inspect.currentframe()).function model = get_perftest_model(ws=function_tmpdir, name=name) - benchmark(lambda: model.write_input()) + benchmark(model.write_input) @pytest.mark.slow diff --git a/autotest/test_mp6.py b/autotest/test_mp6.py index e17a4ab953..d2d99e0b0a 100644 --- a/autotest/test_mp6.py +++ b/autotest/test_mp6.py @@ -589,9 +589,9 @@ def get_mf2005_model(name, ws, alt=False): ocspd = {} for p in range(nper): - ocspd[(p, 0)] = ["save head", "save budget"] + ocspd[p, 0] = ["save head", "save budget"] # pretty sure it just uses the last for everything - ocspd[(0, 0)] = ["save head", "save budget"] + ocspd[0, 0] = ["save head", "save budget"] flopy.modflow.ModflowOc(m, stress_period_data=ocspd) return m, ctx diff --git a/autotest/test_mt3d.py b/autotest/test_mt3d.py index 874a3608c4..a6aef7e8a3 100644 --- a/autotest/test_mt3d.py +++ b/autotest/test_mt3d.py @@ -623,7 +623,7 @@ def test_lkt_with_multispecies(function_tmpdir): options="SIMPLE", ) - ## discretization (DIS) package + # discretization (DIS) package top1 = np.array( [ 0, @@ -3077,11 +3077,11 @@ def test_lkt_with_multispecies(function_tmpdir): perlen=86400.0, ) - ## Instantiate upstream weighting (UPW) flow package + # Instantiate upstream weighting (UPW) flow package upw = ModflowUpw( mf, laytyp=[1, 1, 1], # >0: convertible - layavg=0, # 0: harmonic mean + layavg=0, # 0: harmonic mean chani=1.0, # >0: CHANI is the horizontal anis for entire layer layvka=0, # =0: indicates VKA is vertical hydraulic conductivity laywet=0, # Always set equal to zero in UPW package @@ -3094,7 +3094,7 @@ def test_lkt_with_multispecies(function_tmpdir): sy=0.30, ) - ## Instantiate basic (BAS or BA6) package for MODFLOW-NWT + # Instantiate basic (BAS or BA6) package for MODFLOW-NWT ibnd1 = [ 0, @@ -12805,7 +12805,7 @@ def test_lkt_with_multispecies(function_tmpdir): strt=np.array([sthd1, sthd2, sthd3]), ) - ## Instantiate Lake (LAK) package for MODFLOW-NWT + # Instantiate Lake (LAK) package for MODFLOW-NWT lkarr1 = [ 0, @@ -17705,7 +17705,7 @@ def test_lkt_with_multispecies(function_tmpdir): package_flows=["lak"], ) - ## Now work on MT3D-USGS file creation + # Now work on MT3D-USGS file creation mt = Mt3dms( modflowmodel=mf, @@ -17718,7 +17718,7 @@ def test_lkt_with_multispecies(function_tmpdir): ftlfree=True, ) - ## Instantiate basic transport (BTN) package for MT3D-USGS + # Instantiate basic transport (BTN) package for MT3D-USGS ncomp = 2 mcomp = 2 @@ -17764,7 +17764,7 @@ def test_lkt_with_multispecies(function_tmpdir): sconc2=sconc2, ) - ## Instantiate advection (ADV) package for MT3D-USGS + # Instantiate advection (ADV) package for MT3D-USGS mixelm = 0 percel = 0.7500 @@ -17773,7 +17773,7 @@ def test_lkt_with_multispecies(function_tmpdir): adv = Mt3dAdv(mt, mixelm=mixelm, percel=percel, mxpart=mxpart, nadvfd=nadvfd) - ## Instantiate generalized conjugate gradient solver (GCG) + # Instantiate generalized conjugate gradient solver (GCG) # package for MT3D-USGS mxiter = 1 @@ -17795,12 +17795,12 @@ def test_lkt_with_multispecies(function_tmpdir): iprgcg=iprgcg, ) - ## Instantiate source-sink mixing (SSM) package for MT3D-USGS + # Instantiate source-sink mixing (SSM) package for MT3D-USGS mxss = 0 ssm = Mt3dSsm(mt, mxss=mxss) - ## Instantiate LKT package + # Instantiate LKT package nlkinit = 3 mxlkbc = 12 diff --git a/autotest/test_util_2d_and_3d.py b/autotest/test_util_2d_and_3d.py index 09056f1a51..0913026c0b 100644 --- a/autotest/test_util_2d_and_3d.py +++ b/autotest/test_util_2d_and_3d.py @@ -559,7 +559,7 @@ def test_mflist(function_tmpdir, example_data_path): assert len(df.groupby("per").sum()) == 4 assert df.groupby("per")["cond"].sum().loc[3] == 100.0 assert df.groupby("per")["stage"].mean().loc[0] == 2.0 - assert df.groupby(["k", "i", "j"])["rbot"].count()[(1, 2, 4)] == 10 + assert df.groupby(["k", "i", "j"])["rbot"].count()[1, 2, 4] == 10 def test_how(function_tmpdir): diff --git a/autotest/test_uzf.py b/autotest/test_uzf.py index 2fd0b0fd57..1fb676da32 100644 --- a/autotest/test_uzf.py +++ b/autotest/test_uzf.py @@ -170,13 +170,13 @@ def test_create_uzf(function_tmpdir, mf2005_test_path, uzf_test_path): if not callable(getattr(uzf, attr)) and not attr.startswith("__") ] for attr in attrs: - a1 = uzf.__getattribute__(attr) + a1 = getattr(uzf, attr) if isinstance(a1, Util2d): - a2 = m2.uzf.__getattribute__(attr) + a2 = getattr(m2.uzf, attr) assert np.array_equal(a1.array, a2.array) elif attr in {"finf", "extwc", "pet", "extdp"}: if isinstance(a1, list): - l2 = m2.uzf.__getattribute__(attr) + l2 = getattr(m2.uzf, attr) for i, a in enumerate(a1): # the created finf arrays all have a mult of 1 assert np.array_equal(a.array, l2[i].array) @@ -202,14 +202,14 @@ def test_create_uzf(function_tmpdir, mf2005_test_path, uzf_test_path): uzf2 = ModflowUzf1.load(os.path.join(ws, "UZFtest2.uzf"), m2) attrs = dir(uzf) for attr in attrs: - a1 = uzf.__getattribute__(attr) + a1 = getattr(uzf, attr) if isinstance(a1, Util2d): - a2 = uzf2.__getattribute__(attr) + a2 = getattr(uzf2, attr) assert a1 == a2 # some parameters such as finf are stored as lists of util2d arrays elif attr in {"finf", "extwc", "pet", "extdp"}: if isinstance(a1, list): - l2 = uzf2.__getattribute__(attr) + l2 = getattr(uzf2, attr) for i, a in enumerate(a1): assert a == l2[i] diff --git a/flopy/discretization/modeltime.py b/flopy/discretization/modeltime.py index bfa6586dea..f072d11070 100644 --- a/flopy/discretization/modeltime.py +++ b/flopy/discretization/modeltime.py @@ -533,7 +533,7 @@ def get_elapsed_time( f"stress period and time step" ) - return self._totim_dict[(kper, kstp)] + return self._totim_dict[kper, kstp] def get_datetime( self, kper: int, kstp: int | None = None, start: bool = False @@ -578,7 +578,7 @@ def get_datetime( f"stress period and time step" ) - return self._datetime_dict[(kper, kstp)] + return self._datetime_dict[kper, kstp] def intersect( self, diff --git a/flopy/discretization/structuredgrid.py b/flopy/discretization/structuredgrid.py index 2a1c7b2085..a96aac8241 100644 --- a/flopy/discretization/structuredgrid.py +++ b/flopy/discretization/structuredgrid.py @@ -801,7 +801,7 @@ def convert_grid(self, factor): raise AssertionError("Grid is not complete and cannot be converted") ############### - ### Methods ### + # Methods ############### def neighbors(self, *args, **kwargs): """ @@ -1214,7 +1214,7 @@ def array_at_verts(self, a): rel_tol = 1.0e-5 delz = np.diff(zedges) rel_diff = (delz - delz[0]) / delz[0] - _is_regular_z = np.count_nonzero(np.abs(rel_diff) > rel_tol) == 0 + is_regular_z = np.count_nonzero(np.abs(rel_diff) > rel_tol) == 0 # test equality of first grid spacing in x and z, and in y and z first_equal_xz = np.abs(self.__delr[0] - delz[0]) / delz[0] <= rel_tol @@ -1241,7 +1241,7 @@ def array_at_verts(self, a): # perform basic interpolation (this will be useful in all cases) averts_basic = self.array_at_verts_basic(a) - if self.is_regular_xy and _is_regular_z and first_equal_xz: + if self.is_regular_xy and is_regular_z and first_equal_xz: # in this case, basic interpolation is the correct one averts = averts_basic basic = True @@ -1328,7 +1328,7 @@ def array_at_verts(self, a): # perform basic interpolation (will be useful in all cases) averts_basic[:, :, j] = array_at_verts_basic2d(a[:, :, j]) - if self.is_regular_y and _is_regular_z and first_equal_yz: + if self.is_regular_y and is_regular_z and first_equal_yz: # in this case, basic interpolation is the correct one averts2d = averts_basic[:, :, j] basic = True @@ -1379,7 +1379,7 @@ def array_at_verts(self, a): # perform basic interpolation (will be useful in all cases) averts_basic[:, i, :] = array_at_verts_basic2d(a[:, i, :]) - if self.is_regular_x and _is_regular_z and first_equal_xz: + if self.is_regular_x and is_regular_z and first_equal_xz: # in this case, basic interpolation is the correct one averts2d = averts_basic[:, i, :] basic = True diff --git a/flopy/export/netcdf.py b/flopy/export/netcdf.py index 6f3d539425..53c3541d9e 100644 --- a/flopy/export/netcdf.py +++ b/flopy/export/netcdf.py @@ -313,9 +313,6 @@ def __mul__(self, other): new_net.nc.sync() return new_net - def __div__(self, other): - return self.__truediv__(other) - def __truediv__(self, other): new_net = NetCdf.zeros_like(self) with np.errstate(invalid="ignore"): @@ -950,7 +947,7 @@ def initialize_group( self.log(f"created {group} group dimensions") - dim_names = tuple([i for i in dimensions if i != "time"]) + dim_names = tuple(i for i in dimensions if i != "time") for dim in dimensions: if dim.lower() == "time": if "time" not in attributes: @@ -1213,7 +1210,7 @@ def add_sciencebase_metadata(self, id, check=True): } towrite = sorted(attr.difference(skip)) for k in towrite: - v = md.__getattribute__(k) + v = getattr(md, k) if v is not None: # convert everything to strings if not isinstance(v, str): diff --git a/flopy/export/shapefile_utils.py b/flopy/export/shapefile_utils.py index f9dae9afef..3c0e188279 100644 --- a/flopy/export/shapefile_utils.py +++ b/flopy/export/shapefile_utils.py @@ -299,7 +299,7 @@ def model_attributes_to_shapefile( if "start_datetime" in attrs: attrs.remove("start_datetime") for attr in attrs: - a = pak.__getattribute__(attr) + a = getattr(pak, attr) if a is None or not hasattr(a, "data_type") or a.name == "thickness": continue if a.data_type == DataType.array2d: diff --git a/flopy/export/utils.py b/flopy/export/utils.py index e65f9ad15d..6a99e550fe 100644 --- a/flopy/export/utils.py +++ b/flopy/export/utils.py @@ -544,8 +544,6 @@ def output_helper( attrib_name = "FFF" elif attrib_name == "FLOW LOWER FACE": attrib_name = "FLF" - else: - pass for per in range(plotarray.shape[0]): for k in range(plotarray.shape[1]): if kper is not None and per != kper: diff --git a/flopy/export/vtk.py b/flopy/export/vtk.py index ca25db9d67..1155f49c2f 100644 --- a/flopy/export/vtk.py +++ b/flopy/export/vtk.py @@ -1032,9 +1032,6 @@ def add_package(self, pkg, masked_values=None): elif value.data_type == DataType.transientlist: self.add_transient_list(value, masked_values) - else: - pass - def add_model(self, model, selpaklist=None, masked_values=None): """ Method to add all array and transient list data from a modflow model @@ -1194,8 +1191,6 @@ def add_heads(self, hds, kstpkper=None, masked_values=None): elif isinstance(kstpkper, (list, tuple)): if not isinstance(kstpkper[0], (list, tuple)): kstpkper = [kstpkper] - else: - pass # reset totim based on values read from head file times = hds.get_times() @@ -1252,8 +1247,6 @@ def add_cell_budget(self, cbc, text=None, kstpkper=None, masked_values=None): elif isinstance(kstpkper, tuple): if not isinstance(kstpkper[0], (list, tuple)): kstpkper = [kstpkper] - else: - pass # reset totim based on values read from budget file times = cbc.get_times() diff --git a/flopy/mbase.py b/flopy/mbase.py index 3692ad5270..ef5a26b4be 100644 --- a/flopy/mbase.py +++ b/flopy/mbase.py @@ -37,7 +37,7 @@ flopy_bin = os.path.join(os.path.expanduser("~"), ".local/share/flopy/bin") os.environ["PATH"] = os.environ.get("PATH", "") + os.path.pathsep + flopy_bin -## Global variables +# Global variables # Multiplier for individual array elements in integer and real arrays read by # MODFLOW's U2DREL, U1DREL and U2DINT. iconst = 1 diff --git a/flopy/mf6/utils/codegen/filters.py b/flopy/mf6/utils/codegen/filters.py index 83638dc335..1882227d9a 100644 --- a/flopy/mf6/utils/codegen/filters.py +++ b/flopy/mf6/utils/codegen/filters.py @@ -234,7 +234,10 @@ def attrs(dfn: dict, component_name: tuple[str, str]) -> List[str]: where applicable. TODO: this should get much simpler if we can drop all the `ListTemplateGenerator`/`ArrayTemplateGenerator` attributes. """ - from modflow_devtools.dfn import _SCALAR_TYPES + try: + from modflow_devtools.dfn import SCALAR_TYPES + except ImportError: + from modflow_devtools.dfn import _SCALAR_TYPES as SCALAR_TYPES # noqa: PLC2701 component_base = base(component_name) component_vars = _get_vars(dfn) @@ -247,7 +250,7 @@ def _attr(var: dict) -> Optional[str]: var_subpkg = var.get("ref", None) if ( - (var_type in _SCALAR_TYPES and not var_shape) + (var_type in SCALAR_TYPES and not var_shape) or var_name in ["cvoptions", "output"] # or (component_name[1] == "dis" and var_name == "packagedata") ): diff --git a/flopy/mfusg/mfusgbcf.py b/flopy/mfusg/mfusgbcf.py index 3cbb3651e9..94e511ce88 100644 --- a/flopy/mfusg/mfusgbcf.py +++ b/flopy/mfusg/mfusgbcf.py @@ -703,35 +703,35 @@ def _load_hy_tran_kv_vcont(f_obj, model, laycon_k, ext_unit_dict, ikvflag): util2d_shape = get_util2d_shape_for_layer(model, layer=layer) # hy or tran - _tran = 0 - _hy = 0 + tran = 0 + hy = 0 if laycon_k in {0, 2}: if model.verbose: print(f" loading tran layer {layer + 1:3d}...") - _tran = Util2d.load( + tran = Util2d.load( f_obj, model, util2d_shape, np.float32, "tran", ext_unit_dict ) else: if model.verbose: print(f" loading hy layer {layer + 1:3d}...") - _hy = Util2d.load( + hy = Util2d.load( f_obj, model, util2d_shape, np.float32, "hy", ext_unit_dict ) # kv or vcont - _kv = 0 - _vcont = 0 + kv = 0 + vcont = 0 if layer < (model.nlay - 1): if model.verbose: print(f" loading vcont layer {layer + 1:3d}...") - _vcont = Util2d.load( + vcont = Util2d.load( f_obj, model, util2d_shape, np.float32, "vcont", ext_unit_dict ) elif (ikvflag == 1) and (model.nlay > 1): if model.verbose: print(f" loading kv layer {layer + 1:3d}...") - _kv = Util2d.load( + kv = Util2d.load( f_obj, model, util2d_shape, np.float32, "kv", ext_unit_dict ) - return _hy, _tran, _kv, _vcont + return hy, tran, kv, vcont diff --git a/flopy/mfusg/mfusgbct.py b/flopy/mfusg/mfusgbct.py index e19c680b6c..93de791786 100644 --- a/flopy/mfusg/mfusgbct.py +++ b/flopy/mfusg/mfusgbct.py @@ -243,7 +243,7 @@ def __init__( nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper shape_3d = (nlay, nrow, ncol) - ## Options + # Options opts = [] self.timeweight = None if "timeweight" in kwargs: @@ -313,7 +313,7 @@ def __init__( self.options = " ".join(opts) - ## Assign input parameter array values + # Assign input parameter array values if self.iheat: self.htcondw = kwargs["htcondw"] self.rhow = kwargs["rhow"] diff --git a/flopy/mfusg/mfusglak.py b/flopy/mfusg/mfusglak.py index dd9a618524..33c6507e4e 100644 --- a/flopy/mfusg/mfusglak.py +++ b/flopy/mfusg/mfusglak.py @@ -892,14 +892,14 @@ def load(cls, f, model, nper=None, ext_unit_dict=None): tds.append(float(t[1])) # CRNF if wthdrw < 0: tds.append(float(t[2])) # CAUG - ds9b[(n, icomp)] = tds + ds9b[n, icomp] = tds if mcomp > 0 and transportboundary: - ## CLAKBC The concentration of solute for lake boundary + # CLAKBC The concentration of solute for lake boundary line = f.readline().rstrip() t = line.split() for icomp in range(mcomp): - ds9b[(n, icomp)] = t[icomp] + ds9b[n, icomp] = t[icomp] flux_data[iper] = ds9 conc_data[iper] = ds9b diff --git a/flopy/mfusg/mfusglpf.py b/flopy/mfusg/mfusglpf.py index 42a4f57076..a965a41389 100644 --- a/flopy/mfusg/mfusglpf.py +++ b/flopy/mfusg/mfusglpf.py @@ -648,8 +648,8 @@ def _load_item1(line, model): bubblept = "BUBBLEPT" in text_list fullydry = "FULLYDRY" in text_list - ### Not implemented --- Richards equation uses a tabular input for the - ### moisture retention and relative permeability curves + # Not implemented --- Richards equation uses a tabular input for the + # moisture retention and relative permeability curves if "TABRICH" in text_list: i = text_list.index("TABRICH") nuzones = np.float32(text_list[i + 1]) diff --git a/flopy/mfusg/mfusgoc.py b/flopy/mfusg/mfusgoc.py index 40b1b68bf8..8b60b6bd0d 100644 --- a/flopy/mfusg/mfusgoc.py +++ b/flopy/mfusg/mfusgoc.py @@ -165,10 +165,10 @@ def __init__( icnt = save_start for kstp in range(dis.nstp[kper]): if icnt == save_every: - stress_period_data[(kper, kstp)] = save_types + stress_period_data[kper, kstp] = save_types icnt = 0 else: - stress_period_data[(kper, kstp)] = [] + stress_period_data[kper, kstp] = [] icnt += 1 # adaptive time stepping @@ -971,7 +971,7 @@ def load(cls, f, model, nper=None, nstp=None, nlay=None, ext_unit_dict=None): # less than 0. if incode < 0: if len(lines) > 0: - stress_period_data[(iperoc, itsoc)] = list(lines) + stress_period_data[iperoc, itsoc] = list(lines) continue # set print and save budget flags if ibudfl != 0: @@ -1035,7 +1035,7 @@ def load(cls, f, model, nper=None, nstp=None, nlay=None, ext_unit_dict=None): lines.append(f"PRINT CONC{spcprint}") if len(spcsave) > 0: lines.append(f"SAVE CONC{spcsave}") - stress_period_data[(iperoc, itsoc)] = list(lines) + stress_period_data[iperoc, itsoc] = list(lines) # Output Control Using Words else: @@ -1045,7 +1045,7 @@ def load(cls, f, model, nper=None, nstp=None, nlay=None, ext_unit_dict=None): line = f.readline().upper() if not line: if len(lines) > 0: - stress_period_data[(iperoc, itsoc)] = list(lines) + stress_period_data[iperoc, itsoc] = list(lines) break lnlst = line.strip().split() if line[0] == "#": diff --git a/flopy/modflow/mfag.py b/flopy/modflow/mfag.py index bf88c6d46f..da4237a8ed 100644 --- a/flopy/modflow/mfag.py +++ b/flopy/modflow/mfag.py @@ -273,12 +273,12 @@ def _update_attrs_from_option_block(self, options): for key, ctx in options._context.items(): if key in options.__dict__: val = options.__dict__[key] - self.__setattr__(key, val) + setattr(self, key, val) if ctx[OptionBlock.nested]: for k2, _ in ctx[OptionBlock.vars].items(): if k2 in options.__dict__: v2 = options.__dict__[k2] - self.__setattr__(k2, v2) + setattr(self, k2, v2) def write_file(self, check=False): """ diff --git a/flopy/modflow/mfmnw1.py b/flopy/modflow/mfmnw1.py index fe4f78f052..81a862ccf2 100644 --- a/flopy/modflow/mfmnw1.py +++ b/flopy/modflow/mfmnw1.py @@ -172,8 +172,6 @@ def get_default_dtype(structured=True): ("label", object), ] ) - else: - pass @classmethod def load(cls, f, model, nper=None, gwt=False, nsol=1, ext_unit_dict=None): diff --git a/flopy/modflow/mfoc.py b/flopy/modflow/mfoc.py index afa13cc8c1..5e8b45e4a3 100644 --- a/flopy/modflow/mfoc.py +++ b/flopy/modflow/mfoc.py @@ -200,10 +200,10 @@ def __init__( icnt = save_start for kstp in range(dis.nstp[kper]): if icnt == save_every: - stress_period_data[(kper, kstp)] = save_types + stress_period_data[kper, kstp] = save_types icnt = 0 else: - stress_period_data[(kper, kstp)] = [] + stress_period_data[kper, kstp] = [] icnt += 1 # set output unit numbers based on oc settings @@ -824,7 +824,7 @@ def load(cls, f, model, nper=None, nstp=None, nlay=None, ext_unit_dict=None): # use print options from the last time step else: if len(lines) > 0: - stress_period_data[(iperoc, itsoc)] = list(lines) + stress_period_data[iperoc, itsoc] = list(lines) continue # set print and save budget flags if ibudfl != 0: @@ -870,7 +870,7 @@ def load(cls, f, model, nper=None, nstp=None, nlay=None, ext_unit_dict=None): lines.append(f"SAVE HEAD{headsave}") if len(ddnsave) > 0: lines.append(f"SAVE DRAWDOWN{ddnsave}") - stress_period_data[(iperoc, itsoc)] = list(lines) + stress_period_data[iperoc, itsoc] = list(lines) else: iperoc, itsoc = 0, 0 while True: diff --git a/flopy/modflow/mfsfr2.py b/flopy/modflow/mfsfr2.py index 5e742908db..306d77a661 100644 --- a/flopy/modflow/mfsfr2.py +++ b/flopy/modflow/mfsfr2.py @@ -412,8 +412,6 @@ def __init__( nss = len(segment_data) segment_data = {0: segment_data} nss = len(set(reach_data["iseg"])) - else: - pass # use atleast_1d for length since segment_data might be a 0D array # this seems to be OK, because self.segment_data is produced by the # constructor (never 0D) @@ -1775,8 +1773,6 @@ def _write_6bc(self, i, j, f_sfr, cols=()): if self.isfropt == 5: f_sfr.write(fmts[8].format(uhc) + " ") - else: - pass elif self.isfropt == 1 and icalc <= 1: f_sfr.write(fmts[3].format(width) + " ") if icalc <= 0: @@ -1823,8 +1819,6 @@ def write_file(self, filename=None): self.options.update_from_package(self) self.options.block = False self.options.write_options(f_sfr) - else: - pass self._write_1c(f_sfr) @@ -2357,8 +2351,8 @@ def overlapping_conductance(self, tol=1e-6): uniquerc = {} for i, (r, c) in enumerate(reach_data[["i", "j"]]): if (r, c) not in uniquerc: - uniquerc[(r, c)] = i + 1 - reach_data["node"] = [uniquerc[(r, c)] for r, c in reach_data[["i", "j"]]] + uniquerc[r, c] = i + 1 + reach_data["node"] = [uniquerc[r, c] for r, c in reach_data[["i", "j"]]] K = reach_data["strhc1"] if K.max() == 0: @@ -3217,7 +3211,7 @@ def _parse_6bc(line, icalc, nstrm, isfropt, reachinput, per=0): a list of length 9 containing all variables for Data Set 6b """ - nvalues = sum([_isnumeric(s) for s in line_parse(line)]) + nvalues = sum(_isnumeric(s) for s in line_parse(line)) line = _get_dataset(line, [0] * nvalues) hcond, thickm, elevupdn, width, depth, thts, thti, eps, uhc = [0.0] * 9 @@ -3257,8 +3251,6 @@ def _parse_6bc(line, icalc, nstrm, isfropt, reachinput, per=0): eps = _pop_item(line) if isfropt == 5: uhc = _pop_item(line) - else: - pass elif isfropt == 1 and icalc <= 1: width = line.pop(0) if icalc <= 0: @@ -3274,10 +3266,6 @@ def _parse_6bc(line, icalc, nstrm, isfropt, reachinput, per=0): else: width = line.pop(0) - else: - pass - else: - pass return hcond, thickm, elevupdn, width, depth, thts, thti, eps, uhc diff --git a/flopy/pakbase.py b/flopy/pakbase.py index f71939df5b..70c6a23ddc 100644 --- a/flopy/pakbase.py +++ b/flopy/pakbase.py @@ -648,7 +648,7 @@ def data_list(self): for attr in attrs: if "__" in attr or "data_list" in attr: continue - dl.append(self.__getattribute__(attr)) + dl.append(getattr(self, attr)) return dl def export(self, f, **kwargs): diff --git a/flopy/plot/plotutil.py b/flopy/plot/plotutil.py index 060201d1ef..e8085cc8f2 100644 --- a/flopy/plot/plotutil.py +++ b/flopy/plot/plotutil.py @@ -490,12 +490,6 @@ def _plot_package_helper(package, **kwargs): ) ) - else: - pass - - else: - pass - # unroll nested lists os axes into a single list of axes if isinstance(caxs, list): for c in caxs: @@ -1620,8 +1614,6 @@ def line_intersect_grid(ptsin, xgrid, ygrid): cvert_ix.append(vx - 1) elif cpv[vx - 1] == 0 and cpv[vx] == 0: cvert_ix += [vx - 1, vx] - else: - pass if cvert_ix: cells.append(cell) diff --git a/flopy/utils/binaryfile/__init__.py b/flopy/utils/binaryfile/__init__.py index b017584012..f2fdb2bb75 100644 --- a/flopy/utils/binaryfile/__init__.py +++ b/flopy/utils/binaryfile/__init__.py @@ -547,8 +547,8 @@ def reverse_header(header): kper = header["kper"] - 1 kstp = header["kstp"] - 1 seen.add((kper, kstp)) - header["pertim"] = trev._pertim_dict[(kper, kstp)] - header["totim"] = trev._totim_dict[(kper, kstp)] + header["pertim"] = trev._pertim_dict[kper, kstp] + header["totim"] = trev._totim_dict[kper, kstp] return header target = filename @@ -2126,8 +2126,8 @@ def reverse_header(header): kper = header["kper"] - 1 kstp = header["kstp"] - 1 seen.add((kper, kstp)) - header["pertim"] = trev._pertim_dict[(kper, kstp)] - header["totim"] = trev._totim_dict[(kper, kstp)] + header["pertim"] = trev._pertim_dict[kper, kstp] + header["totim"] = trev._totim_dict[kper, kstp] return header # if rewriting the same file, write @@ -2206,4 +2206,4 @@ def reverse_header(header): # if we rewrote the original file, reinitialize if inplace: move(target, filename) - self.__init__(filename, self.precision, self.verbose) + self.__init__(filename, self.precision, self.verbose) # noqa: PLC2801 diff --git a/flopy/utils/gridintersect.py b/flopy/utils/gridintersect.py index cc096ac6fa..9effe75dc1 100644 --- a/flopy/utils/gridintersect.py +++ b/flopy/utils/gridintersect.py @@ -1016,7 +1016,7 @@ def _intersect_linestring_structured( if inode in parsed_nodes: continue templengths.append( - sum([l for l, i in zip(lengths, nodelist) if i == inode]) + sum(l for l, i in zip(lengths, nodelist) if i == inode) ) tempverts.append([v for v, i in zip(vertices, nodelist) if i == inode]) tempshapes.append( diff --git a/flopy/utils/gridutil.py b/flopy/utils/gridutil.py index 938a29e43f..81bdbbe335 100644 --- a/flopy/utils/gridutil.py +++ b/flopy/utils/gridutil.py @@ -51,7 +51,7 @@ def get_lni(ncpl, nodes) -> list[tuple[int, int]]: for nn in nodes if nodes else range(sum(counts)): csum = np.cumsum([0] + counts) layer = max(0, np.searchsorted(csum, nn) - 1) - nidx = nn - sum([counts[l] for l in range(0, layer)]) + nidx = nn - sum(counts[l] for l in range(0, layer)) # np.searchsorted assigns the first index of each layer # to the previous layer in layer 2+, so correct for it diff --git a/flopy/utils/lgrutil.py b/flopy/utils/lgrutil.py index 9cd927335c..04f1874498 100644 --- a/flopy/utils/lgrutil.py +++ b/flopy/utils/lgrutil.py @@ -691,7 +691,7 @@ def find_hanging_vertices(self): for iv in (ivlist[0], ivlist[3]): if iv not in hlist: hlist.append(iv) - self.right_face_hanging[(ip, jp)] = hlist + self.right_face_hanging[ip, jp] = hlist elif idir == 1: # child vertices 1 and 2 added as hanging nodes @@ -703,7 +703,7 @@ def find_hanging_vertices(self): for iv in (ivlist[1], ivlist[2]): if iv not in hlist: hlist.append(iv) - self.left_face_hanging[(ip, jp)] = hlist + self.left_face_hanging[ip, jp] = hlist elif idir == 2: # child vertices 0 and 1 added as hanging nodes @@ -715,7 +715,7 @@ def find_hanging_vertices(self): for iv in (ivlist[0], ivlist[1]): if iv not in hlist: hlist.append(iv) - self.front_face_hanging[(ip, jp)] = hlist + self.front_face_hanging[ip, jp] = hlist elif idir == -2: # child vertices 3 and 2 added as hanging nodes @@ -727,7 +727,7 @@ def find_hanging_vertices(self): for iv in (ivlist[3], ivlist[2]): if iv not in hlist: hlist.append(iv) - self.back_face_hanging[(ip, jp)] = hlist + self.back_face_hanging[ip, jp] = hlist nodec += 1 @@ -762,7 +762,7 @@ def build_verts_iverts(self): ivlist = self.merge_hanging_vertices(i, j, ivlist) iverts.append(ivlist) - self.parent_ij_to_global[(i, j)] = iglo + self.parent_ij_to_global[i, j] = iglo iglo += 1 # now add active child cells @@ -774,7 +774,7 @@ def build_verts_iverts(self): for iv in self.cgrid._build_structured_iverts(i, j) ] iverts.append(ivlist) - self.child_ij_to_global[(i, j)] = iglo + self.child_ij_to_global[i, j] = iglo iglo += 1 self.verts = verts self.iverts = iverts @@ -814,7 +814,7 @@ def merge_hanging_vertices(self, ip, jp, ivlist): face_hanging = self.back_face_hanging back_edge = [ivlist[idx]] if (ip, jp) in face_hanging: - hlist = face_hanging[(ip, jp)] + hlist = face_hanging[ip, jp] if len(hlist) > 2: hlist = hlist[1:-1] # do not include two ends hlist = [h + child_ivlist_offset for h in hlist] @@ -830,7 +830,7 @@ def merge_hanging_vertices(self, ip, jp, ivlist): face_hanging = self.right_face_hanging right_edge = [ivlist[idx]] if (ip, jp) in face_hanging: - hlist = face_hanging[(ip, jp)] + hlist = face_hanging[ip, jp] if len(hlist) > 2: hlist = hlist[1:-1] # do not include two ends hlist = [h + child_ivlist_offset for h in hlist] @@ -846,7 +846,7 @@ def merge_hanging_vertices(self, ip, jp, ivlist): face_hanging = self.front_face_hanging front_edge = [ivlist[idx]] if (ip, jp) in face_hanging: - hlist = face_hanging[(ip, jp)] + hlist = face_hanging[ip, jp] if len(hlist) > 2: hlist = hlist[1:-1] # do not include two ends hlist = [h + child_ivlist_offset for h in hlist] @@ -862,7 +862,7 @@ def merge_hanging_vertices(self, ip, jp, ivlist): face_hanging = self.left_face_hanging left_edge = [ivlist[idx]] if (ip, jp) in face_hanging: - hlist = face_hanging[(ip, jp)] + hlist = face_hanging[ip, jp] if len(hlist) > 2: hlist = hlist[1:-1] # do not include two ends hlist = [h + child_ivlist_offset for h in hlist] diff --git a/flopy/utils/mflistfile.py b/flopy/utils/mflistfile.py index bf1ac8ea35..ff2c626f51 100644 --- a/flopy/utils/mflistfile.py +++ b/flopy/utils/mflistfile.py @@ -759,7 +759,7 @@ def _get_sp(self, ts, sp, seekpoint): return self.null_entries # --if there are two '=' in this line, then it is a budget line - if len(re.findall("=", line)) == 2: + if len(re.findall(r"=", line)) == 2: break tag = "IN" @@ -773,7 +773,7 @@ def _get_sp(self, ts, sp, seekpoint): f"information for ts,sp: {ts} {sp}" ) return self.null_entries - if len(re.findall("=", line)) == 2: + if len(re.findall(r"=", line)) == 2: try: entry, flux, cumu = self._parse_budget_line(line) except Exception: diff --git a/flopy/utils/optionblock.py b/flopy/utils/optionblock.py index 5c680f42c6..edb7eb47fa 100644 --- a/flopy/utils/optionblock.py +++ b/flopy/utils/optionblock.py @@ -91,12 +91,12 @@ def update_from_package(self, pak): for key, ctx in self._context.items(): if key in pak.__dict__: val = pak.__dict__[key] - self.__setattr__(key, val) + setattr(self, key, val) if ctx[OptionBlock.nested]: for k2, ctx2 in ctx[OptionBlock.vars].items(): if k2 in pak.__dict__: v2 = pak.__dict__[k2] - self.__setattr__(k2, v2) + setattr(self, k2, v2) def __repr__(self): """ @@ -252,17 +252,17 @@ def _set_attributes(self): """ # set up all attributes for the class! for key, ctx in self._context.items(): + val = None if ctx[OptionBlock.dtype] in (np.bool_, bool): - self.__setattr__(key, False) - else: - self.__setattr__(key, None) + val = False + setattr(self, key, val) if ctx[OptionBlock.nested]: for k, d in ctx[OptionBlock.vars].items(): + val = None if d[OptionBlock.dtype] in (np.bool_, bool): - self.__setattr__(k, False) - else: - self.__setattr__(k, None) + val = False + setattr(self, k, val) t = self.options_line.split() nested = False @@ -278,9 +278,10 @@ def _set_attributes(self): OptionUtil.isvalid(dtype, t[ix]) if dtype == np.bool_: - self.__setattr__(key, True) + val = True else: - self.__setattr__(key, dtype(t[ix])) + val = dtype(t[ix]) + setattr(self, key, val) ix += 1 @@ -305,9 +306,10 @@ def _set_attributes(self): OptionUtil.isvalid(dtype, t[ix]) if dtype == np.bool_: - self.__setattr__(key, True) + val = True else: - self.__setattr__(key, dtype(t[ix])) + val = dtype(t[ix]) + setattr(self, key, val) ix += 1 @@ -484,8 +486,6 @@ def isvalid(dtype, val): valid = OptionUtil.isint(val) elif dtype == float: valid = OptionUtil.isfloat(val) - else: - pass if not valid: err_msg = f"Invalid type set to variable {val} in option block" diff --git a/flopy/utils/parse_version.py b/flopy/utils/parse_version.py index 8be314c794..0372d54fd2 100644 --- a/flopy/utils/parse_version.py +++ b/flopy/utils/parse_version.py @@ -398,18 +398,18 @@ def __str__(self) -> str: @property def epoch(self) -> int: - _epoch: int = self._version.epoch - return _epoch + epoch: int = self._version.epoch + return epoch @property def release(self) -> tuple[int, ...]: - _release: tuple[int, ...] = self._version.release - return _release + release: tuple[int, ...] = self._version.release + return release @property def pre(self) -> tuple[str, int] | None: - _pre: tuple[str, int] | None = self._version.pre - return _pre + pre: tuple[str, int] | None = self._version.pre + return pre @property def post(self) -> int | None: @@ -531,7 +531,7 @@ def _cmpkey( # leading zeros until we come to something non zero, then take the rest # re-reverse it back into the correct order and make it a tuple and use # that for our sorting key. - _release = tuple( + release_ = tuple( reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release)))) ) @@ -540,31 +540,31 @@ def _cmpkey( # if there is not a pre or a post segment. If we have one of those then # the normal sorting rules will handle this case correctly. if pre is None and post is None and dev is not None: - _pre: PrePostDevType = NegativeInfinity + pre_: PrePostDevType = NegativeInfinity # Versions without a pre-release (except as noted above) should sort after # those with one. elif pre is None: - _pre = Infinity + pre_ = Infinity else: - _pre = pre + pre_ = pre # Versions without a post segment should sort before those with one. if post is None: - _post: PrePostDevType = NegativeInfinity + post_: PrePostDevType = NegativeInfinity else: - _post = post + post_ = post # Versions without a development segment should sort after those with one. if dev is None: - _dev: PrePostDevType = Infinity + dev_: PrePostDevType = Infinity else: - _dev = dev + dev_ = dev if local is None: # Versions without a local segment should sort before those with one. - _local: LocalType = NegativeInfinity + local_: LocalType = NegativeInfinity else: # Versions with a local segment need that segment parsed to implement # the sorting rules in PEP440. @@ -573,8 +573,8 @@ def _cmpkey( # - Numeric segments sort numerically # - Shorter versions sort before longer versions when the prefixes # match exactly - _local = tuple( + local_ = tuple( (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local ) - return epoch, _release, _pre, _post, _dev, _local + return epoch, release_, pre_, post_, dev_, local_ diff --git a/flopy/utils/triangle.py b/flopy/utils/triangle.py index 4ad20f9e14..906333a9c4 100644 --- a/flopy/utils/triangle.py +++ b/flopy/utils/triangle.py @@ -764,6 +764,6 @@ def _create_edge_dict(self): edgedict = {} for _, iv1, iv2, iseg in self.edge: if iseg != 0: - edgedict[(iv1, iv2)] = iseg - edgedict[(iv2, iv1)] = iseg + edgedict[iv1, iv2] = iseg + edgedict[iv2, iv1] = iseg self.edgedict = edgedict diff --git a/flopy/utils/util_array.py b/flopy/utils/util_array.py index c8b288aeeb..3823260615 100644 --- a/flopy/utils/util_array.py +++ b/flopy/utils/util_array.py @@ -2032,7 +2032,7 @@ def __getitem__(self, k): if len(k) == 1: return self.array[k] else: - return self.array[(k,)] + return self.array[k,] def __setitem__(self, k, value): """ diff --git a/flopy/utils/zonbud.py b/flopy/utils/zonbud.py index df839d5fe6..b8dd2a8aea 100644 --- a/flopy/utils/zonbud.py +++ b/flopy/utils/zonbud.py @@ -1612,16 +1612,6 @@ def __truediv__(self, other): newobj._budget = newbud return newobj - def __div__(self, other): - newbud = self._budget.copy() - for f in self._zonenamedict.values(): - newbud[f] = np.array(list(newbud[f])) / float(other) - idx = np.isin(self._budget["name"], "PERCENT_DISCREPANCY") - newbud[:][idx] = self._budget[:][idx] - newobj = self.copy() - newobj._budget = newbud - return newobj - def __add__(self, other): newbud = self._budget.copy() for f in self._zonenamedict.values(): @@ -1764,11 +1754,8 @@ def add_package(self, pkg_name, pkg): else: pkg = func.load(pkg, self) - else: - pass - pkg_name = f"_{pkg_name}" - self.__setattr__(pkg_name, pkg) + setattr(self, pkg_name, pkg) if pkg is not None: self.package_dict[pkg_name[1:]] = pkg @@ -2544,18 +2531,12 @@ def _read_zb_zblst(fname): elif "OUT:" in line: prefix = "TO_" - else: - pass - elif flow_budget: if "IN:" in line: prefix = "FROM_" read_data = True flow_budget = False - else: - pass - if empty >= 30: break @@ -2638,9 +2619,6 @@ def _read_zb_csv(fname): elif line in {"", " "}: empty += 1 - else: - pass - if empty >= 25: break @@ -2913,15 +2891,15 @@ def _volumetric_flux(recarray, modeltime, extrapolate_kper=False): if len(idx[0]) == 0: continue elif n == 0: - tslen[(stp, ix)] = totim[n] + tslen[stp, ix] = totim[n] else: - tslen[(stp, ix)] = totim[n] - totim[n - 1] - dtotim[(stp, ix)] = totim[n] + tslen[stp, ix] = totim[n] - totim[n - 1] + dtotim[stp, ix] = totim[n] n += 1 - ltslen = [tslen[(rec["kstp"], rec["kper"])] for rec in recarray] + ltslen = [tslen[rec["kstp"], rec["kper"]] for rec in recarray] if len(np.unique(recarray["totim"])) == 1: - ltotim = [dtotim[(rec["kstp"], rec["kper"])] for rec in recarray] + ltotim = [dtotim[rec["kstp"], rec["kper"]] for rec in recarray] recarray["totim"] = ltotim for name in recarray.dtype.names: diff --git a/pyproject.toml b/pyproject.toml index 00bf9e6f32..6e1f29aede 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -176,17 +176,22 @@ ignore = [ "F811", # Redefinition of unused variable "F841", # local variable assigned but never used "PLC0415", # `import` should be at the top-level of a file + "PLC1901", # `var == ""` can be simplified to `not var` as an empty string + "PLW1514", # `open` in text mode without explicit `encoding` argument "PLW1641", # Object does not implement `__hash__` method "PLW2901", # `for` loop variable `col` overwritten by assignment target "RUF005", # collection literal concatenation "RUF012", # mutable class default "RUF017", # quadratic-list-summation "RUF059", # Unpacked variable `name` is never used + "RUF100", # Unused `noqa` directive ] [tool.ruff.lint.per-file-ignores] ".docs/**/*.py" = ["E501"] "flopy/mf6/**/*.py" = ["C4", "E", "F", "ISC", "RUF"] +"flopy/utils/geometry.py" = ["PLW3201"] +"flopy/utils/geospatial_utils.py" = ["PLW3201"] [tool.codespell] skip = "cliff.toml,./examples/data/*,./autotest/test_modeltime.py" diff --git a/scripts/update_version.py b/scripts/update_version.py index c30164efab..30f36eef58 100644 --- a/scripts/update_version.py +++ b/scripts/update_version.py @@ -32,7 +32,7 @@ def split_nonnumeric(s): - match = re.compile("[^0-9]").search(s) + match = re.compile(r"[^0-9]").search(s) return [s[: match.start()], s[match.start() :]] if match else s