From bb9824e8aaea04a43d911724445cf0610301d236 Mon Sep 17 00:00:00 2001 From: Mike Taves Date: Fri, 15 Nov 2024 03:54:38 +1300 Subject: [PATCH] refactor: fix long lines to resolve check E501 (#2368) This refactor resolves long line checks. See ruff check code E501 for more. --- autotest/conftest.py | 14 +++-- autotest/regression/test_mf6.py | 3 +- autotest/regression/test_modflow.py | 3 +- autotest/test_cellbudgetfile.py | 22 +++---- autotest/test_export.py | 3 +- autotest/test_get_modflow.py | 8 ++- autotest/test_grid.py | 16 ++--- autotest/test_lgr.py | 4 +- autotest/test_mf6.py | 10 +-- autotest/test_model_splitter.py | 3 +- autotest/test_modflow.py | 5 +- autotest/test_mp6.py | 6 +- autotest/test_particlegroup.py | 3 +- autotest/test_plot_cross_section.py | 3 +- autotest/test_specific_discharge.py | 2 +- autotest/test_template_writer.py | 3 +- autotest/test_uzf.py | 3 +- flopy/discretization/grid.py | 2 +- flopy/discretization/unstructuredgrid.py | 3 +- flopy/export/metadata.py | 5 +- flopy/export/netcdf.py | 9 ++- flopy/export/shapefile_utils.py | 3 +- flopy/export/utils.py | 9 ++- flopy/export/vtk.py | 3 +- flopy/mbase.py | 11 ++-- flopy/mfusg/mfusgbcf.py | 3 +- flopy/mfusg/mfusglpf.py | 6 +- flopy/modflow/mf.py | 3 +- flopy/modflow/mfdrn.py | 4 +- flopy/modflow/mfdrt.py | 4 +- flopy/modflow/mfmnw1.py | 18 ++++-- flopy/modflow/mfmnw2.py | 11 ++-- flopy/modflow/mfnwt.py | 4 +- flopy/modflow/mfoc.py | 3 +- flopy/modflow/mfpar.py | 4 +- flopy/modflow/mfsfr2.py | 79 ++++++++++++++---------- flopy/modflow/mfstr.py | 2 +- flopy/modpath/mp6.py | 17 +++-- flopy/modpath/mp6bas.py | 3 +- flopy/modpath/mp6sim.py | 14 +++-- flopy/modpath/mp7.py | 2 +- flopy/modpath/mp7particledata.py | 9 ++- flopy/mt3d/mtbtn.py | 2 +- flopy/mt3d/mtlkt.py | 3 +- flopy/mt3d/mtsft.py | 3 +- flopy/pakbase.py | 3 +- flopy/utils/binaryfile.py | 3 +- flopy/utils/check.py | 2 +- flopy/utils/crs.py | 3 +- flopy/utils/get_modflow.py | 3 +- flopy/utils/gridgen.py | 6 +- flopy/utils/lgrutil.py | 14 +++-- flopy/utils/mfreadnam.py | 3 +- flopy/utils/modpathfile.py | 9 ++- flopy/utils/mtlistfile.py | 3 +- flopy/utils/swroutputfile.py | 3 +- flopy/utils/util_array.py | 9 +-- flopy/utils/utl_import.py | 1 + pyproject.toml | 4 +- 59 files changed, 255 insertions(+), 161 deletions(-) diff --git a/autotest/conftest.py b/autotest/conftest.py index 1706e52d10..327f518292 100644 --- a/autotest/conftest.py +++ b/autotest/conftest.py @@ -71,8 +71,8 @@ def close_plot(request): @pytest.fixture(scope="session", autouse=True) def patch_macos_ci_matplotlib(): - # use noninteractive matplotlib backend if in Mac OS CI to avoid pytest-xdist node failure - # e.g. https://github.com/modflowpy/flopy/runs/7748574375?check_suite_focus=true#step:9:57 + # use noninteractive matplotlib backend if in Mac OS CI to avoid pytest-xdist + # node failure if is_in_ci() and system().lower() == "darwin": import matplotlib @@ -86,7 +86,7 @@ def patch_macos_ci_matplotlib(): def pytest_runtest_makereport(item, call): # this is necessary so temp dir fixtures can # inspect test results and check for failure - # (see https://doc.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures) + # (see https://doc.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures) # noqa outcome = yield rep = outcome.get_result() @@ -101,8 +101,9 @@ def pytest_addoption(parser): "--show-plots", action="store_true", default=False, - help="Show any figure windows created by test cases. (Useful to display plots for visual inspection, " - "but automated tests should probably also check patch collections or figure & axis properties.)", + help="Show any figure windows created by test cases. (Useful to display " + "plots for visual inspection, but automated tests should probably also " + "check patch collections or figure & axis properties.)", ) # for test_generate_classes.py @@ -110,7 +111,8 @@ def pytest_addoption(parser): "--ref", action="append", type=str, - help="Include extra refs to test. Useful for testing branches on a fork, e.g. /modflow6/.", + help="Include extra refs to test. Useful for testing branches on a fork, " + "e.g. /modflow6/.", ) diff --git a/autotest/regression/test_mf6.py b/autotest/regression/test_mf6.py index f2e62408be..8c1ac4a544 100644 --- a/autotest/regression/test_mf6.py +++ b/autotest/regression/test_mf6.py @@ -4085,7 +4085,8 @@ def test006_gwf3(function_tmpdir, example_data_path): save_folder.mkdir() sim.set_sim_path(save_folder) - # write with "copy_external_files" turned off so external files do not get copied to new location + # write with "copy_external_files" turned off so external files + # do not get copied to new location sim.write_simulation(ext_file_action=ExtFileAction.copy_none) # store strt in an external binary file diff --git a/autotest/regression/test_modflow.py b/autotest/regression/test_modflow.py index 2b15a93995..69e7aede2d 100644 --- a/autotest/regression/test_modflow.py +++ b/autotest/regression/test_modflow.py @@ -377,7 +377,8 @@ def test_mf2005_lake(function_tmpdir, namfile, mf2005_test_path): fn0 = join(ws, Path(namfile).name) - # write free format files - won't run without resetting to free format - evt external file issue + # write free format files - + # won't run without resetting to free format - evt external file issue m.free_format_input = True # rewrite files diff --git a/autotest/test_cellbudgetfile.py b/autotest/test_cellbudgetfile.py index 3eb64447e7..6a2bc42578 100644 --- a/autotest/test_cellbudgetfile.py +++ b/autotest/test_cellbudgetfile.py @@ -114,7 +114,7 @@ def test_cellbudgetfile_build_index_compact(example_data_path): 52, ) assert list_recorddict[-1] == ( - (1, 1097, b"FLOW LOWER FACE ", 20, 40, -3, 1, 1.0, 1.0, 1097.0, b"", b"", b"", b""), + (1, 1097, b"FLOW LOWER FACE ", 20, 40, -3, 1, 1.0, 1.0, 1097.0, b"", b"", b"", b""), # noqa 42648784, ) # fmt: on @@ -209,7 +209,7 @@ def test_cellbudgetfile_build_index_mf6(example_data_path): assert list_recorddict[-1] == ( (120, 4, b" EVT", 10, 15, -3, 6, 0.08333333333333333, 10.000000000000002, 30.99999999999983, - b"GWF_1 ", b"GWF_1 ", b"GWF_1 ", b"EVT "), + b"GWF_1 ", b"GWF_1 ", b"GWF_1 ", b"EVT "), # noqa 13414144, ) # fmt: on @@ -515,11 +515,10 @@ def test_cellbudgetfile_readrecord(example_data_path): for idx, kk in enumerate(kstpkper): t0 = v.get_data(kstpkper=kk, text=record.strip())[0] t1 = v.get_data(idx=indices[idx], text=record)[0] - assert np.array_equal( - t0, t1 - ), "binary budget item {0} read using kstpkper != binary budget item {0} read using idx".format( - record - ) + assert np.array_equal(t0, t1), ( + "binary budget item {0} read using kstpkper != " + "binary budget item {0} read using idx" + ).format(record) # idx can be either an int or a list of ints s9 = v.get_data(idx=9) @@ -577,11 +576,10 @@ def test_cellbudgetfile_readrecord_waux(example_data_path): for idx, kk in enumerate(kstpkper): t0 = v.get_data(kstpkper=kk, text=record.strip())[0] t1 = v.get_data(idx=indices[idx], text=record)[0] - assert np.array_equal( - t0, t1 - ), "binary budget item {0} read using kstpkper != binary budget item {0} read using idx".format( - record - ) + assert np.array_equal(t0, t1), ( + "binary budget item {0} read using kstpkper != " + "binary budget item {0} read using idx" + ).format(record) v.close() diff --git a/autotest/test_export.py b/autotest/test_export.py index 25b7c022c9..4f40a58243 100644 --- a/autotest/test_export.py +++ b/autotest/test_export.py @@ -1600,7 +1600,8 @@ def test_vtk_pathline(function_tmpdir, example_data_path): def grid2disvgrid(nrow, ncol): - """Simple function to create disv verts and iverts for a regular grid of size nrow, ncol""" + """Simple function to create disv verts and iverts for a regular grid of + size nrow, ncol""" def lower_left_point(i, j, ncol): return i * (ncol + 1) + j diff --git a/autotest/test_get_modflow.py b/autotest/test_get_modflow.py index 58d8e27d94..830d2da8b4 100644 --- a/autotest/test_get_modflow.py +++ b/autotest/test_get_modflow.py @@ -20,9 +20,11 @@ flopy_dir = get_project_root_path() get_modflow_script = flopy_dir / "flopy" / "utils" / "get_modflow.py" bindir_options = { - "flopy": Path(expandvars(r"%LOCALAPPDATA%\flopy")) / "bin" - if system() == "Windows" - else Path.home() / ".local" / "share" / "flopy" / "bin", + "flopy": ( + Path(expandvars(r"%LOCALAPPDATA%\flopy")) / "bin" + if system() == "Windows" + else Path.home() / ".local" / "share" / "flopy" / "bin" + ), "python": Path(sys.prefix) / ("Scripts" if system() == "Windows" else "bin"), "home": Path.home() / ".local" / "bin", } diff --git a/autotest/test_grid.py b/autotest/test_grid.py index 0cec2fa2c1..dd2b140160 100644 --- a/autotest/test_grid.py +++ b/autotest/test_grid.py @@ -33,6 +33,12 @@ import pyproj +epsg_3070_proj4_str = ( + "+proj=tmerc +lat_0=0 +lon_0=-90 +k=0.9996 +x_0=520000 " + "+y_0=-4480000 +datum=NAD83 +units=m +no_defs " +) + + @pytest.fixture def minimal_unstructured_grid_info(): d = { @@ -579,10 +585,7 @@ def test_unstructured_from_gridspec_comments(example_data_path): (None, None), (26916, "EPSG:26916"), ("epsg:5070", "EPSG:5070"), - ( - "+proj=tmerc +lat_0=0 +lon_0=-90 +k=0.9996 +x_0=520000 +y_0=-4480000 +datum=NAD83 +units=m +no_defs ", - "EPSG:3070", - ), + (epsg_3070_proj4_str, "EPSG:3070"), pytest.param(4269, None, marks=pytest.mark.xfail), ), ) @@ -649,10 +652,7 @@ def do_checks(g): (None, None), (26916, "EPSG:26916"), ("epsg:5070", "EPSG:5070"), - ( - "+proj=tmerc +lat_0=0 +lon_0=-90 +k=0.9996 +x_0=520000 +y_0=-4480000 +datum=NAD83 +units=m +no_defs ", - "EPSG:3070", - ), + (epsg_3070_proj4_str, "EPSG:3070"), ("ESRI:102733", "ESRI:102733"), pytest.param(4269, None, marks=pytest.mark.xfail), ), diff --git a/autotest/test_lgr.py b/autotest/test_lgr.py index 2a01b8ae8c..fc20a1ae43 100644 --- a/autotest/test_lgr.py +++ b/autotest/test_lgr.py @@ -84,7 +84,9 @@ def singleModel( # Variables for the BAS package ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) if iChild > 0: - iBndBnd = 59 # code for child cell to be linked to parent; value assigned to ibflg in the LGR-data + # code for child cell to be linked to parent; + # value assigned to ibflg in the LGR-data + iBndBnd = 59 else: iBndBnd = -1 ibound[:, 0, :] = iBndBnd diff --git a/autotest/test_mf6.py b/autotest/test_mf6.py index 003d2fc22f..5afd033e69 100644 --- a/autotest/test_mf6.py +++ b/autotest/test_mf6.py @@ -838,9 +838,10 @@ def test_binary_read(function_tmpdir): bf, data_shape, data_size, np.float64, modelgrid )[0] - assert np.allclose( - arr, arr2 - ), f"Binary read for layered structured failed with {'Path' if isinstance(binfile, Path) else 'str'}" + assert np.allclose(arr, arr2), ( + "Binary read for layered structured failed with " + + ("Path" if isinstance(binfile, Path) else "str") + ) binfile = function_tmpdir / "structured_flat.hds" with open(binfile, "wb") as foo: @@ -2335,7 +2336,8 @@ def test_remove_model(function_tmpdir, example_data_path): files = list(function_tmpdir.glob("*")) assert not any("model2" in f.name for f in files) - # there should be no model or solver entry for the child model in the simulation namefile + # there should be no model or solver entry for the child model + # in the simulation namefile lines = open(function_tmpdir / "mfsim.nam").readlines() lines = [l.lower().strip() for l in lines] assert not any("model2" in l for l in lines) diff --git a/autotest/test_model_splitter.py b/autotest/test_model_splitter.py index dc19a45e5b..6255f54ccd 100644 --- a/autotest/test_model_splitter.py +++ b/autotest/test_model_splitter.py @@ -1295,5 +1295,6 @@ def build_gwt_model(sim, gwtname, rch_package): diff = np.nansum(diff) if diff > 10.25: raise AssertionError( - f"Difference between output arrays: {diff :.2f} greater than tolerance" + "Difference between output arrays: " + f"{diff :.2f} greater than tolerance" ) diff --git a/autotest/test_modflow.py b/autotest/test_modflow.py index cadf978f3c..c2e955633d 100644 --- a/autotest/test_modflow.py +++ b/autotest/test_modflow.py @@ -94,7 +94,7 @@ def test_modflow_load(namfile, example_data_path): pytest.param( _example_data_path / "freyberg_multilayer_transient" / "freyberg.nam", { - "proj4": "+proj=utm +zone=14 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", + "proj4": "+proj=utm +zone=14 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", # noqa "angrot": 15.0, "xoffset": 622241.1904510253, "yoffset": 3343617.741737109, @@ -1225,7 +1225,8 @@ def test_load_with_list_reader(function_tmpdir): ["recarray", "dataframe", "dict_of_recarray", "dict_of_dataframe"], ) def test_pkg_data_containers(function_tmpdir, container): - """Test various containers for package data (list, ndarray, recarray, dataframe, dict of such)""" + """Test various containers for package data + (list, ndarray, recarray, dataframe, dict of such)""" nlay = 1 nrow = 10 diff --git a/autotest/test_mp6.py b/autotest/test_mp6.py index e5c44300a4..9c8123ce5e 100644 --- a/autotest/test_mp6.py +++ b/autotest/test_mp6.py @@ -682,7 +682,8 @@ def test_data_pass_no_modflow(function_tmpdir, alt): @pytest.mark.parametrize("alt", [True, False]) def test_data_pass_with_modflow(function_tmpdir, alt): """ - test that user specified head files etc. are preferred over files from the modflow model + test that user specified head files etc. are preferred + over files from the modflow model """ ml, ctx = get_mf2005_model("data_pass", function_tmpdir, alt) @@ -760,7 +761,8 @@ def test_data_pass_with_modflow(function_tmpdir, alt): @pytest.mark.parametrize("alt", [True, False]) def test_just_from_model(function_tmpdir, alt): """ - test that user specified head files etc. are preferred over files from the modflow model + test that user specified head files etc. are preferred + over files from the modflow model """ ml, ctx = get_mf2005_model("data_pass", function_tmpdir, alt) diff --git a/autotest/test_particlegroup.py b/autotest/test_particlegroup.py index a664d74e7f..e98b9ab379 100644 --- a/autotest/test_particlegroup.py +++ b/autotest/test_particlegroup.py @@ -44,7 +44,8 @@ def test_pgroup_release_data(): ) assert type(pgrd2.releaseinterval) == type(ripg2), ( f"mp7: pgroup with releaseoption 2 returned " - f"type(releaseinterval)={type(pgrd2.releaseinterval)}. Should remain as {type(ripg2)}" + f"type(releaseinterval)={type(pgrd2.releaseinterval)}. " + f"Should remain as {type(ripg2)}" ) assert len(pgrd3.releasetimes) == nripg3, ( f"mp7: pgroup with releaseoption 3 returned " diff --git a/autotest/test_plot_cross_section.py b/autotest/test_plot_cross_section.py index 2da5eadff7..a0f058e665 100644 --- a/autotest/test_plot_cross_section.py +++ b/autotest/test_plot_cross_section.py @@ -84,7 +84,8 @@ def test_cross_section_bc_UZF_3lay(example_data_path): def structured_square_grid(side: int = 10, thick: int = 10): """ - Creates a basic 1-layer structured grid with the given thickness and number of cells per side + Creates a basic 1-layer structured grid with the given thickness and number of + cells per side Parameters ---------- side : The number of cells per side diff --git a/autotest/test_specific_discharge.py b/autotest/test_specific_discharge.py index e0f0596e44..6ccf4d8d14 100644 --- a/autotest/test_specific_discharge.py +++ b/autotest/test_specific_discharge.py @@ -485,7 +485,7 @@ def specific_discharge_comprehensive(function_tmpdir): @pytest.mark.mf6 @pytest.mark.xfail( - reason="occasional Unexpected collection type: " + reason="occasional Unexpected collection type: " # noqa ) def test_specific_discharge_mf6(mf6_model): # build and run MODFLOW 6 model diff --git a/autotest/test_template_writer.py b/autotest/test_template_writer.py index f6e7ae39c9..cfd7c7a95a 100644 --- a/autotest/test_template_writer.py +++ b/autotest/test_template_writer.py @@ -56,7 +56,8 @@ def test_tpl_layered(function_tmpdir): partype = "hk" parname = "HK_LAYER_1-3" - # Span indicates that the hk parameter applies as a multiplier to layers 0 and 2 (MODFLOW layers 1 and 3) + # Span indicates that the hk parameter applies as a multiplier to layers 0 and 2 + # (MODFLOW layers 1 and 3) span = {"layers": [0, 2]} # These parameters have not affect yet, but may in the future diff --git a/autotest/test_uzf.py b/autotest/test_uzf.py index d49a2b3a47..9d9873ceb1 100644 --- a/autotest/test_uzf.py +++ b/autotest/test_uzf.py @@ -213,7 +213,8 @@ def test_create_uzf(function_tmpdir, mf2005_test_path, uzf_test_path): for i, a in enumerate(a1): assert a == l2[i] - # load uzf test problem for nwt model with 'nwt_11_fmt'-style options and 'open/close' array types + # load uzf test problem for nwt model with 'nwt_11_fmt'-style options + # and 'open/close' array types tpth = uzf_test_path / "load_uzf_for_nwt" [shutil.copy(os.path.join(tpth, f), os.path.join(ws, f)) for f in os.listdir(tpth)] m3 = Modflow("UZFtest3", version="mfnwt", verbose=True) diff --git a/flopy/discretization/grid.py b/flopy/discretization/grid.py index ea98aae808..b29868f494 100644 --- a/flopy/discretization/grid.py +++ b/flopy/discretization/grid.py @@ -871,7 +871,7 @@ def map_polygons(self): def get_lni(self, nodes): """ - Get the layer index and within-layer node index (both 0-based) for the given nodes + Get the 0-based layer index and within-layer node index for the given nodes Parameters ---------- diff --git a/flopy/discretization/unstructuredgrid.py b/flopy/discretization/unstructuredgrid.py index 18d7b1ce97..3c24706467 100644 --- a/flopy/discretization/unstructuredgrid.py +++ b/flopy/discretization/unstructuredgrid.py @@ -1177,7 +1177,8 @@ def split_line(): verts_provided = len(line) - 6 if verts_declared != verts_provided: raise ValueError( - f"Cell {nn} declares {verts_declared} vertices but provides {verts_provided}" + f"Cell {nn} declares {verts_declared} vertices " + f"but provides {verts_provided}" ) verts = [int(vert) - 1 for vert in line[6 : 6 + verts_declared]] diff --git a/flopy/export/metadata.py b/flopy/export/metadata.py index 6c80943309..c1cdb462a3 100644 --- a/flopy/export/metadata.py +++ b/flopy/export/metadata.py @@ -82,7 +82,10 @@ def __init__(self, sciencebase_id, model): if "publisher" in d.get("type").lower() ][0] self.publisher_email = self.sb["provenance"]["linkProcess"].get("processedBy") - self.publisher_url = "https://www2.usgs.gov/water/" # self.sb['provenance']['linkProcess'].get('linkReference') + # TODO: should publisher_url be obtained from linkReference? + # publisher_url = self.sb['provenance']['linkProcess'].get('linkReference') + publisher_url = "https://www2.usgs.gov/water/" + self.publisher_url = publisher_url self.geospatial_bounds_crs = "EPSG:4326" self.geospatial_lat_min = self.bounds.get("minY") self.geospatial_lat_max = self.bounds.get("maxY") diff --git a/flopy/export/netcdf.py b/flopy/export/netcdf.py index 54a168478d..a40ac85101 100644 --- a/flopy/export/netcdf.py +++ b/flopy/export/netcdf.py @@ -877,7 +877,8 @@ def initialize_file(self, time_values=None): delc.comments = ( "This is the row spacing that applied to the UNROTATED grid. " "This grid HAS been rotated before being saved to NetCDF. " - "To compute the unrotated grid, use the origin point and this array." + "To compute the unrotated grid, use the origin point and " + "this array." ) # delr @@ -893,7 +894,8 @@ def initialize_file(self, time_values=None): delr.comments = ( "This is the col spacing that applied to the UNROTATED grid. " "This grid HAS been rotated before being saved to NetCDF. " - "To compute the unrotated grid, use the origin point and this array." + "To compute the unrotated grid, use the origin point and " + "this array." ) # Workaround for CF/CDM. @@ -1267,7 +1269,8 @@ def add_sciencebase_metadata(self, id, check=True): return md def _check_vs_sciencebase(self, md): - """Check that model bounds read from flopy are consistent with those in ScienceBase.""" + """Check that model bounds read from flopy are consistent with + those in ScienceBase.""" xmin, ymin, xmax, ymax = self.bounds tol = 1e-5 assert md.geospatial_lon_min - xmin < tol diff --git a/flopy/export/shapefile_utils.py b/flopy/export/shapefile_utils.py index bef3bbcb65..0d2e84da80 100644 --- a/flopy/export/shapefile_utils.py +++ b/flopy/export/shapefile_utils.py @@ -326,7 +326,8 @@ def model_attributes_to_shapefile( if a.array.shape == horz_shape: if hasattr(a, "shape"): if a.shape[1] is None: # usg unstructured Util3d - # return a flattened array, with a.name[0] (a per-layer list) + # return a flattened array, + # with a.name[0] (a per-layer list) array_dict[a.name[0]] = a.array else: array_dict[a.name] = a.array diff --git a/flopy/export/utils.py b/flopy/export/utils.py index 9aef5ff987..7533601ad8 100644 --- a/flopy/export/utils.py +++ b/flopy/export/utils.py @@ -301,7 +301,8 @@ def output_helper( Parameters ---------- f : str or PathLike or NetCdf or dict - filepath to write output to (must have .shp or .nc extension), NetCDF object, or dictionary + filepath to write output to (must have .shp or .nc extension), + NetCDF object, or dictionary ml : flopy.mbase.ModelInterface derived type oudic : dict output_filename,flopy datafile/cellbudgetfile instance @@ -574,7 +575,8 @@ def model_export(f: Union[str, os.PathLike, NetCdf, dict], ml, fmt=None, **kwarg Parameters ---------- f : str or PathLike or NetCdf or dict - file path (".nc" for netcdf or ".shp" for shapefile) or NetCDF object or dictionary + file path (".nc" for netcdf or ".shp" for shapefile), + NetCDF object, or dictionary ml : flopy.modflow.mbase.ModelInterface object flopy model object fmt : str @@ -661,7 +663,8 @@ def package_export( Parameters ---------- f : str or PathLike or NetCdf or dict - output file path (extension .shp for shapefile or .nc for netcdf) or NetCDF object or dictionary + output file path (extension .shp for shapefile or .nc for netcdf), + NetCDF object, or dictionary pak : flopy.pakbase.Package object package to export fmt : str diff --git a/flopy/export/vtk.py b/flopy/export/vtk.py index 579a2990ca..6f29f379f2 100644 --- a/flopy/export/vtk.py +++ b/flopy/export/vtk.py @@ -1128,7 +1128,8 @@ def add_pathline_points(self, pathlines, timeseries=False): raise ValueError("Unrecognized pathline dtype") else: raise ValueError( - "Unsupported pathline format, expected array, recarray, dataframe, or list" + "Unsupported pathline format, expected array, recarray, " + "dataframe, or list" ) if not timeseries: diff --git a/flopy/mbase.py b/flopy/mbase.py index f0bfbdaac9..528c89fc05 100644 --- a/flopy/mbase.py +++ b/flopy/mbase.py @@ -46,8 +46,9 @@ def resolve_exe(exe_name: Union[str, os.PathLike], forgive: bool = False) -> str: """ - Resolves the absolute path of the executable, raising FileNotFoundError if the executable - cannot be found (set forgive to True to return None and warn instead of raising an error). + Resolves the absolute path of the executable, raising FileNotFoundError + if the executable cannot be found (set forgive to True to return None + and warn instead of raising an error). Parameters ---------- @@ -1274,7 +1275,8 @@ def change_model_ws( if not os.path.exists(new_pth): try: print( - f"\ncreating model workspace...\n {flopy_io.relpath_safe(new_pth)}" + "\ncreating model workspace...\n " + + flopy_io.relpath_safe(new_pth) ) os.makedirs(new_pth) except: @@ -1704,7 +1706,8 @@ def run_model( exe_path = resolve_exe(exe_name) if not silent: print( - f"FloPy is using the following executable to run the model: {flopy_io.relpath_safe(exe_path, model_ws)}" + "FloPy is using the following executable to run the model: " + + flopy_io.relpath_safe(exe_path, model_ws) ) # make sure namefile exists diff --git a/flopy/mfusg/mfusgbcf.py b/flopy/mfusg/mfusgbcf.py index e60742bdb8..ae0edc2b80 100644 --- a/flopy/mfusg/mfusgbcf.py +++ b/flopy/mfusg/mfusgbcf.py @@ -342,7 +342,8 @@ def load(cls, f, model, ext_unit_dict=None): >>> import flopy >>> m = flopy.mfusg.MfUsg() >>> disu = flopy.mfusg.MfUsgDisU( - model=m, nlay=1, nodes=1, iac=[1], njag=1,ja=np.array([0]), fahl=[1.0], cl12=[1.0]) + ... model=m, nlay=1, nodes=1, iac=[1], njag=1,ja=np.array([0]), + ... fahl=[1.0], cl12=[1.0]) >>> bcf = flopy.mfusg.MfUsgBcf.load('test.bcf', m) """ msg = ( diff --git a/flopy/mfusg/mfusglpf.py b/flopy/mfusg/mfusglpf.py index be91d48129..9b5dbac8d5 100644 --- a/flopy/mfusg/mfusglpf.py +++ b/flopy/mfusg/mfusglpf.py @@ -197,7 +197,8 @@ class MfUsgLpf(ModflowLpf): >>> import flopy >>> m = flopy.mfusg.MfUsg() >>> disu = flopy.mfusg.MfUsgDisU( - model=m, nlay=1, nodes=1, iac=[1], njag=1,ja=np.array([0]), fahl=[1.0], cl12=[1.0]) + ... model=m, nlay=1, nodes=1, iac=[1], njag=1,ja=np.array([0]), + ... fahl=[1.0], cl12=[1.0]) >>> lpf = flopy.mfusg.MfUsgLpf(m) """ @@ -440,7 +441,8 @@ def load(cls, f, model, ext_unit_dict=None, check=True): >>> import flopy >>> m = flopy.mfusg.MfUsg() >>> disu = flopy.mfusg.MfUsgDisU( - model=m, nlay=1, nodes=1, iac=[1], njag=1,ja=np.array([0]), fahl=[1.0], cl12=[1.0]) + ... model=m, nlay=1, nodes=1, iac=[1], njag=1, + ... ja=np.array([0]), fahl=[1.0], cl12=[1.0]) >>> lpf = flopy.mfusg.MfUsgLpf.load('test.lpf', m) """ msg = ( diff --git a/flopy/modflow/mf.py b/flopy/modflow/mf.py index f4c3836e85..e883a08343 100644 --- a/flopy/modflow/mf.py +++ b/flopy/modflow/mf.py @@ -734,7 +734,8 @@ def load( # DEPRECATED since version 3.3.4 if ml.version == "mfusg": raise ValueError( - "flopy.modflow.Modflow no longer supports mfusg; use flopy.mfusg.MfUsg() instead" + "flopy.modflow.Modflow no longer supports mfusg; " + "use flopy.mfusg.MfUsg() instead" ) # reset unit number for glo file diff --git a/flopy/modflow/mfdrn.py b/flopy/modflow/mfdrn.py index 7a57ed5be1..b99e4b77c9 100644 --- a/flopy/modflow/mfdrn.py +++ b/flopy/modflow/mfdrn.py @@ -92,8 +92,8 @@ class ModflowDrn(Package): Notes ----- Parameters are not supported in FloPy. - If "RETURNFLOW" in passed in options, the drain return package (DRT) activated, which expects - a different (longer) dtype for stress_period_data + If "RETURNFLOW" in passed in options, the drain return package (DRT) + activated, which expects a different (longer) dtype for stress_period_data Examples -------- diff --git a/flopy/modflow/mfdrt.py b/flopy/modflow/mfdrt.py index af507d5e3f..9638d5ccdd 100644 --- a/flopy/modflow/mfdrt.py +++ b/flopy/modflow/mfdrt.py @@ -98,8 +98,8 @@ class ModflowDrt(Package): >>> import flopy >>> ml = flopy.modflow.Modflow() - >>> lrcec = {0:[2, 3, 4, 10., 100., 1 ,1 ,1, 1.0]} #this drain will be applied to all - >>> #stress periods + >>> # this drain will be applied to all stress periods + >>> lrcec = {0:[2, 3, 4, 10., 100., 1 ,1 ,1, 1.0]} >>> drt = flopy.modflow.ModflowDrt(ml, stress_period_data=lrcec) """ diff --git a/flopy/modflow/mfmnw1.py b/flopy/modflow/mfmnw1.py index a141b3ee54..dcdc4736e8 100644 --- a/flopy/modflow/mfmnw1.py +++ b/flopy/modflow/mfmnw1.py @@ -119,17 +119,24 @@ def __init__( self._generate_heading() self.mxmnw = mxmnw # -maximum number of multi-node wells to be simulated self.iwelpt = iwelpt # -verbosity flag - self.nomoiter = nomoiter # -integer indicating the number of iterations for which flow in MNW wells is calculated - self.kspref = kspref # -alphanumeric key indicating which set of water levels are to be used as reference values for calculating drawdown + # integer indicating the number of iterations for which flow in MNW wells + # is calculated + self.nomoiter = nomoiter + # alphanumeric key indicating which set of water levels are to be used as + # reference values for calculating drawdown + self.kspref = kspref self.losstype = losstype # -string indicating head loss type for each well - self.wel1_bynode_qsum = wel1_bynode_qsum # -nested list containing file names, unit numbers, and ALLTIME flag for auxiliary output, e.g. [['test.ByNode',92,'ALLTIME']] + # nested list containing file names, unit numbers, and ALLTIME flag for + # auxiliary output, e.g. [['test.ByNode',92,'ALLTIME']] + self.wel1_bynode_qsum = wel1_bynode_qsum if dtype is not None: self.dtype = dtype else: self.dtype = self.get_default_dtype(structured=self.parent.structured) self.stress_period_data = MfList(self, stress_period_data) - self.mnwname = mnwname # -string prefix name of file for outputting time series data from MNW1 + # string prefix name of file for outputting time series data from MNW1 + self.mnwname = mnwname # -input format checks: lossTypes = ["skin", "linear", "nonlinear"] @@ -310,7 +317,8 @@ def write_file(self): ) spd = self.stress_period_data.drop("mnw_no") - # force write_transient to keep the list arrays internal because MNW1 doesn't allow open/close + # force write_transient to keep the list arrays internal because MNW1 + # doesn't allow open/close spd.write_transient(f, forceInternal=True) # -Un-numbered section PREFIX:MNWNAME diff --git a/flopy/modflow/mfmnw2.py b/flopy/modflow/mfmnw2.py index 643a6f6308..6fb657367c 100644 --- a/flopy/modflow/mfmnw2.py +++ b/flopy/modflow/mfmnw2.py @@ -168,8 +168,8 @@ class Mnw: When writing non-dataset 2d variables to MNW2 input, the first value for the well will be used. - Other variables (e.g. hlim) can be entered here as - constant for all stress periods, or by stress period below in stress_period_data. + Other variables (e.g. hlim) can be entered here as constant for all + stress periods, or by stress period below in stress_period_data. See MNW2 input instructions for more details. Columns are: @@ -1331,7 +1331,8 @@ def load(cls, f, model, nper=None, gwt=False, nsol=1, ext_unit_dict=None): # master table with all node data node_data = np.append(node_data, mnwobj.node_data).view(np.recarray) - stress_period_data = {} # stress period data table for package (flopy convention) + # stress period data table for package (flopy convention) + stress_period_data = {} itmp = [] for per in range(0, nper): # dataset 3 @@ -1668,7 +1669,9 @@ def export(self, f, **kwargs): """ todrop = {'qfrcmx', 'qfrcmn'} names = list(set(self.stress_period_data.dtype.names).difference(todrop)) - dtype = np.dtype([(k, d) for k, d in self.stress_period_data.dtype.descr if k not in todrop]) + dtype = np.dtype( + [(k, d) for k, d in self.stress_period_data.dtype.descr if k not in todrop] + ) spd = {} for k, v in self.stress_period_data.data.items(): newarr = np.array(np.zeros_like(self.stress_period_data[k][names]), diff --git a/flopy/modflow/mfnwt.py b/flopy/modflow/mfnwt.py index e859b98c90..80285b8d9d 100644 --- a/flopy/modflow/mfnwt.py +++ b/flopy/modflow/mfnwt.py @@ -136,8 +136,8 @@ class ModflowNwt(Package): (GMRES) is the number of iterations between restarts of the GMRES Solver. (default is 15). iacl : int - (XMD) is a flag for the acceleration method: 0 is conjugate gradient, 1 is ORTHOMIN, - 2 is Bi-CGSTAB. (default is 2). + (XMD) is a flag for the acceleration method: 0 is conjugate gradient, + 1 is ORTHOMIN, 2 is Bi-CGSTAB. (default is 2). norder : int (XMD) is a flag for the scheme of ordering the unknowns: 0 is original ordering, 1 is RCM ordering, 2 is Minimum Degree ordering. diff --git a/flopy/modflow/mfoc.py b/flopy/modflow/mfoc.py index 3f73ff79c5..e17b4be302 100644 --- a/flopy/modflow/mfoc.py +++ b/flopy/modflow/mfoc.py @@ -882,7 +882,8 @@ def load(cls, f, model, nper=None, nstp=None, nlay=None, ext_unit_dict=None): if line[0] == "#": continue - # added by JJS 12/12/14 to avoid error when there is a blank line in the OC file + # added by JJS 12/12/14 to avoid error when there is a + # blank line in the OC file if lnlst == []: continue # end add diff --git a/flopy/modflow/mfpar.py b/flopy/modflow/mfpar.py index eb12236354..e17bbc973f 100644 --- a/flopy/modflow/mfpar.py +++ b/flopy/modflow/mfpar.py @@ -284,8 +284,8 @@ def parameter_fill(model, shape, findkey, parm_dict, findlayer=None): for lpf and upw: - >>> data = flopy.modflow.mfpar.ModflowPar.parameter_fill(m, (nrow, ncol), 'vkcb', - >>> .....................................................parm_dict, findlayer=1) + >>> data = flopy.modflow.mfpar.ModflowPar.parameter_fill( + ... m, (nrow, ncol), 'vkcb', parm_dict, findlayer=1) """ diff --git a/flopy/modflow/mfsfr2.py b/flopy/modflow/mfsfr2.py index c6e1e53ae0..7391f73470 100644 --- a/flopy/modflow/mfsfr2.py +++ b/flopy/modflow/mfsfr2.py @@ -428,10 +428,12 @@ def __init__( 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) + # this seems to be OK, because self.segment_data is produced by the + # constructor (never 0D) self.nsfrpar = nsfrpar self.nparseg = nparseg - # conversion factor used in calculating stream depth for stream reach (icalc = 1 or 2) + # conversion factor used in calculating stream depth for stream reach + # (icalc = 1 or 2) self._const = const if const is not None else None self.dleak = dleak # tolerance level of stream depth used in computing leakage @@ -439,7 +441,8 @@ def __init__( self.istcb2 = istcb2 # if nstrm < 0 - # defines the format of the input data and whether or not unsaturated flow is simulated + # defines the format of the input data and whether or not unsaturated + # flow is simulated self.isfropt = isfropt # if isfropt > 1 @@ -893,7 +896,8 @@ def load(cls, f, model, nper=None, gwt=False, nsol=1, ext_unit_dict=None): ) # container to hold any auxiliary variables current_aux = {} - # these could also be implemented as structured arrays with a column for segment number + # these could also be implemented as structured arrays with + # a column for segment number current_6d = {} current_6e = {} for j in range(itmp): @@ -932,8 +936,9 @@ def load(cls, f, model, nper=None, gwt=False, nsol=1, ext_unit_dict=None): if icalc == 2: # ATL: not sure exactly how isfropt logic functions for this - # dataset 6d description suggests that this line isn't read for isfropt > 1 - # but description of icalc suggest that icalc=2 (8-point channel) can be used with any isfropt + # dataset 6d description suggests that this line isn't read for + # isfropt > 1 but description of icalc suggest that icalc=2 + # (8-point channel) can be used with any isfropt if i == 0 or nstrm > 0 and not reachinput or isfropt <= 1: dataset_6d = [] for _ in range(2): @@ -2037,12 +2042,14 @@ class check: Daniel Feinstein's top 10 SFR problems (7/16/2014): 1) cell gaps btw adjacent reaches in a single segment - 2) cell gaps btw routed segments. possibly because of re-entry problems at domain edge + 2) cell gaps btw routed segments. possibly because of re-entry problems at + domain edge 3) adjacent reaches with STOP sloping the wrong way 4) routed segments with end/start sloping the wrong way 5) STOP>TOP1 violations, i.e.,floaters 6) STOP< 0: - txt += "{} instances where an outlet was not found after {} consecutive segments!\n".format( - len(circular_segs), self.sfr.nss + txt += ( + f"{len(circular_segs)} instances where an outlet was " + f"not found after {self.sfr.nss} consecutive segments!\n" ) if self.level == 1: txt += " ".join(map(str, circular_segs)) + "\n" @@ -2633,8 +2642,9 @@ def elevations(self, min_strtop=-10, max_strtop=15000): reach_data = ( self.sfr.reach_data ) # inconsistent with other checks that work with - # reach_data attribute of check class. Want to have get_outreaches as a method of sfr class - # (for other uses). Not sure if other check methods should also copy reach_data directly from + # reach_data attribute of check class. Want to have get_outreaches + # as a method of sfr class (for other uses). Not sure if other + # check methods should also copy reach_data directly from # SFR package instance for consistency. rd = recfunctions.append_fields( @@ -2661,19 +2671,20 @@ def elevations(self, min_strtop=-10, max_strtop=15000): ], col1="d_strtop", col2=np.zeros(len(rd)), - level0txt="{} reaches encountered with strtop < strtop of downstream reach.", + level0txt="{} reaches encountered with strtop < strtop of downstream reach.", # noqa level1txt="Elevation rises:", ) if len(txt) == 0: passed = True else: - txt += "Reach strtop not specified for nstrm={}, reachinput={} and isfropt={}\n".format( - self.sfr.nstrm, self.sfr.reachinput, self.sfr.isfropt + txt += ( + f"Reach strtop not specified for nstrm={self.sfr.nstrm}, " + f"reachinput={self.sfr.reachinput} and isfropt={self.sfr.isfropt}\n" ) passed = True self._txt_footer(headertxt, txt, "reach elevations", passed) - headertxt = "Checking reach_data for inconsistencies between streambed elevations and the model grid...\n" + headertxt = "Checking reach_data for inconsistencies between streambed elevations and the model grid...\n" # noqa if self.verbose: print(headertxt.strip()) txt = "" @@ -2719,7 +2730,7 @@ def elevations(self, min_strtop=-10, max_strtop=15000): ], col1="layerbot", col2="strbot", - level0txt="{} reaches encountered with streambed bottom below layer bottom.", + level0txt="{} reaches encountered with streambed bottom below layer bottom.", # noqa level1txt="Layer bottom violations:", ) if len(txt) > 0: @@ -2757,8 +2768,9 @@ def elevations(self, min_strtop=-10, max_strtop=15000): if len(txt) == 0: passed = True else: - txt += "Reach strtop, strthick not specified for nstrm={}, reachinput={} and isfropt={}\n".format( - self.sfr.nstrm, self.sfr.reachinput, self.sfr.isfropt + txt += ( + f"Reach strtop, strthick not specified for nstrm={self.sfr.nstrm}, " + f"reachinput={self.sfr.reachinput} and isfropt={self.sfr.isfropt}\n" ) passed = True self._txt_footer( @@ -2844,16 +2856,17 @@ def elevations(self, min_strtop=-10, max_strtop=15000): if len(txt) == 0: passed = True else: - txt += "Segment elevup and elevdn not specified for nstrm={} and isfropt={}\n".format( - self.sfr.nstrm, self.sfr.isfropt + txt += ( + f"Segment elevup and elevdn not specified for nstrm={self.sfr.nstrm} " + f"and isfropt={self.sfr.isfropt}\n" ) passed = True self._txt_footer(headertxt, txt, "segment elevations vs. model grid", passed) def slope(self, minimum_slope=1e-4, maximum_slope=1.0): - """Checks that streambed slopes are greater than or equal to a specified minimum value. - Low slope values can cause "backup" or unrealistic stream stages with icalc options - where stage is computed. + """Checks that streambed slopes are greater than or equal to a + specified minimum value. Low slope values can cause "backup" or + unrealistic stream stages with icalc options where stage is computed. """ headertxt = f"Checking for streambed slopes of less than {minimum_slope}...\n" txt = "" @@ -2868,8 +2881,9 @@ def slope(self, minimum_slope=1e-4, maximum_slope=1.0): is_less = self.reach_data.slope < minimum_slope if np.any(is_less): below_minimum = self.reach_data[is_less] - txt += "{} instances of streambed slopes below minimum found.\n".format( - len(below_minimum) + txt += ( + f"{len(below_minimum)} instances of streambed slopes " + "below minimum found.\n" ) if self.level == 1: txt += "Reaches with low slopes:\n" @@ -2897,8 +2911,9 @@ def slope(self, minimum_slope=1e-4, maximum_slope=1.0): if np.any(is_greater): above_max = self.reach_data[is_greater] - txt += "{} instances of streambed slopes above maximum found.\n".format( - len(above_max) + txt += ( + f"{len(above_max)} instances of streambed slopes " + "above maximum found.\n" ) if self.level == 1: txt += "Reaches with high slopes:\n" @@ -3284,8 +3299,8 @@ def _parse_6bc(line, icalc, nstrm, isfropt, reachinput, per=0): thickm = line.pop(0) elevupdn = line.pop(0) if isfropt in [4, 5] and per == 0: - # table in online guide suggests that the following items should be present in this case - # but in the example + # table in online guide suggests that the following items + # should be present in this case but in the example thts = _pop_item(line) thti = _pop_item(line) eps = _pop_item(line) diff --git a/flopy/modflow/mfstr.py b/flopy/modflow/mfstr.py index 01ffa75783..f0878c551e 100644 --- a/flopy/modflow/mfstr.py +++ b/flopy/modflow/mfstr.py @@ -219,7 +219,7 @@ class ModflowStr(Package): >>> #applied to all stress periods >>> str = flopy.modflow.ModflowStr(m, stress_period_data=strd) - """ + """ # noqa def __init__( self, diff --git a/flopy/modpath/mp6.py b/flopy/modpath/mp6.py index 25f23d19a1..a21e06216e 100644 --- a/flopy/modpath/mp6.py +++ b/flopy/modpath/mp6.py @@ -152,7 +152,8 @@ def __init__( ) if self.__mf is None: - # read from nper, lay, nrow, ncol from dis file, Item 1: NLAY, NROW, NCOL, NPER, ITMUNI, LENUNI + # read from nper, lay, nrow, ncol from dis file, + # Item 1: NLAY, NROW, NCOL, NPER, ITMUNI, LENUNI read_dis = dis_file if not os.path.exists(read_dis): # path doesn't exist, probably relative to model_ws @@ -263,14 +264,17 @@ def create_mpsim( (default is 'WEL'). start_time : float or tuple Sets the value of MODPATH reference time relative to MODFLOW time. - float : value of MODFLOW simulation time at which to start the particle tracking simulation. + float : value of MODFLOW simulation time at which to start the + particle tracking simulation. Sets the value of MODPATH ReferenceTimeOption to 1. - tuple : (period, step, time fraction) MODFLOW stress period, time step and fraction + tuple : (period, step, time fraction) MODFLOW stress period, + time step and fraction between 0 and 1 at which to start the particle tracking simulation. Sets the value of MODPATH ReferenceTimeOption to 2. default_ifaces : list - List of cell faces (1-6; see MODPATH6 manual, fig. 7) on which to start particles. - (default is None, meaning ifaces will vary depending on packages argument above) + List of cell faces (1-6; see MODPATH6 manual, fig. 7) on which to + start particles. (default is None, meaning ifaces will vary + depending on packages argument above) ParticleRowCount : int Rows of particles to start on each cell index face (iface). ParticleColumnCount : int @@ -297,7 +301,8 @@ def create_mpsim( ref_time = 0 ref_time_per_stp = (0, 0, 1.0) if isinstance(start_time, tuple): - ReferenceTimeOption = 2 # 1: specify value for ref. time, 2: specify kper, kstp, rel. time pos + # 1: specify value for ref. time, 2: specify kper, kstp, rel. time pos + ReferenceTimeOption = 2 ref_time_per_stp = start_time else: ref_time = start_time diff --git a/flopy/modpath/mp6bas.py b/flopy/modpath/mp6bas.py index 50ccae6d15..f98ff6a1b3 100644 --- a/flopy/modpath/mp6bas.py +++ b/flopy/modpath/mp6bas.py @@ -34,7 +34,8 @@ class Modpath6Bas(Package): def_iface : int or list of ints Cell face (iface) on which to assign flows from MODFLOW budget file. laytyp : None, int or list of ints - MODFLOW layer type (0 is convertible, 1 is confined). If None, read from modflow model + MODFLOW layer type (0 is convertible, 1 is confined). + If None, read from modflow model ibound : None or array of ints, optional The ibound array (the default is 1). If None, pull from parent modflow model prsity : array of ints, optional diff --git a/flopy/modpath/mp6sim.py b/flopy/modpath/mp6sim.py index fc4ebcc670..361fdb14dc 100644 --- a/flopy/modpath/mp6sim.py +++ b/flopy/modpath/mp6sim.py @@ -204,7 +204,8 @@ def write_file(self): None """ - # item numbers and CamelCase variable names correspond to Modpath 6 documentation + # item numbers and CamelCase variable names correspond to + # Modpath 6 documentation nrow, ncol, nlay, nper = self.parent.nrow_ncol_nlay_nper f_sim = open(self.fn_path, "w") @@ -395,7 +396,8 @@ class StartingLocationsFile(Package): The model object (of type :class:`flopy.modpath.mp.Modpath`) to which this package will be added. inputstyle : 1 - Input style described in MODPATH6 manual (currently only input style 1 is supported) + Input style described in MODPATH6 manual + (currently only input style 1 is supported) extension : string Filename extension (default is 'loc') use_pandas: bool, default True @@ -456,7 +458,8 @@ def get_empty_starting_locations_data( Parameters ---------- npt : int - Number of particles. Particles in array will be numbered consecutively from 1 to npt. + Number of particles. + Particles in array will be numbered consecutively from 1 to npt. """ dtype = StartingLocationsFile.get_dtypes() @@ -494,7 +497,7 @@ def _write_particle_data_with_pandas(self, data, float_format): 'initialtime', 'label'] :param save_group_mapper bool, if true, save a groupnumber to group name mapper as well. :return: - """ + """ # noqa # convert float format string to pandas float format float_format = float_format.replace("{", "").replace("}", "").replace(":", "%") data = pd.DataFrame(data) @@ -507,7 +510,8 @@ def _write_particle_data_with_pandas(self, data, float_format): data.loc[:, "groupname"] = data.groupname.str.decode("UTF-8") # write loc file with pandas to save time - # simple speed test writing particles with flopy and running model took 30 min, writing with pandas took __min + # simple speed test writing particles with flopy and running model took 30 min, + # writing with pandas took __min loc_path = self.fn_path # write groups group_dict = dict(data[["particlegroup", "groupname"]].itertuples(False, None)) diff --git a/flopy/modpath/mp7.py b/flopy/modpath/mp7.py index 4e8d06c44d..07bfa354a9 100644 --- a/flopy/modpath/mp7.py +++ b/flopy/modpath/mp7.py @@ -372,7 +372,7 @@ def write_name_file(self): f.write(f"DIS {self.dis_file}\n") if self.grbdis_file is not None: f.write( - f"{self.grbtag:10s} {os.path.join(self._flowmodel_ws, self.grbdis_file)}\n" + f"{self.grbtag:10s} {os.path.join(self._flowmodel_ws, self.grbdis_file)}\n" # noqa ) if self.tdis_file is not None: f.write(f"TDIS {os.path.join(self._flowmodel_ws, self.tdis_file)}\n") diff --git a/flopy/modpath/mp7particledata.py b/flopy/modpath/mp7particledata.py index 84b78c0e1f..698513f88e 100644 --- a/flopy/modpath/mp7particledata.py +++ b/flopy/modpath/mp7particledata.py @@ -190,7 +190,8 @@ def __init__( partlocs = unstructured_to_structured(partlocs, dtype=dtype) else: raise ValueError( - f"{self.name}: partlocs must be a list or tuple with lists or tuples, or an ndarray" + f"{self.name}: partlocs must be a list or tuple with lists or " + "tuples, or an ndarray" ) # localx @@ -826,7 +827,8 @@ def get_extent(grid, k=None, i=None, j=None, nn=None, localz=False) -> Extent: ) else: raise ValueError( - "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) @@ -990,7 +992,8 @@ def get_release_points( if nn is None and (k is None or i is None or j is None): raise ValueError( - "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)" ) cellid = [k, i, j] if nn is None else [nn] diff --git a/flopy/mt3d/mtbtn.py b/flopy/mt3d/mtbtn.py index e9697ee592..3a302c366e 100644 --- a/flopy/mt3d/mtbtn.py +++ b/flopy/mt3d/mtbtn.py @@ -1155,7 +1155,7 @@ def load(cls, f, model, ext_unit_dict=None): if model.verbose: print( - " loading PERLEN, NSTP, TSMULT, TSLNGH, DT0, MXSTRN, TTSMULT, TTSMAX..." + " loading PERLEN, NSTP, TSMULT, TSLNGH, DT0, MXSTRN, TTSMULT, TTSMAX..." # noqa ) dt0, mxstrn, ttsmult, ttsmax = [], [], [], [] perlen = [] diff --git a/flopy/mt3d/mtlkt.py b/flopy/mt3d/mtlkt.py index a9f9a5f10e..7b51af32b0 100644 --- a/flopy/mt3d/mtlkt.py +++ b/flopy/mt3d/mtlkt.py @@ -422,7 +422,8 @@ def load(cls, f, model, nlak=None, nper=None, ncomp=None, ext_unit_dict=None): print(" ntmp < 0 not allowed for first stress period ") if (iper > 0) and (ntmp < 0): print( - " use lkt boundary conditions specified in last stress period " + " use lkt boundary conditions " + "specified in last stress period " ) # Item 4: Read ntmp boundary conditions diff --git a/flopy/mt3d/mtsft.py b/flopy/mt3d/mtsft.py index c66fd613ce..87ba2106dc 100644 --- a/flopy/mt3d/mtsft.py +++ b/flopy/mt3d/mtsft.py @@ -428,7 +428,8 @@ def write_file(self): f.write(line) # Items 7, 8 - # Loop through each stress period and assign source & sink concentrations to stream features + # 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: diff --git a/flopy/pakbase.py b/flopy/pakbase.py index 24233a1a36..1f04bf83d1 100644 --- a/flopy/pakbase.py +++ b/flopy/pakbase.py @@ -388,7 +388,8 @@ def _check_storage(self, chk, storage_coeff): ) if inds.any(): if self.sy.shape[1] is None: - # unstructured; build flat nodal property array slicers (by layer) + # unstructured; + # build flat nodal property array slicers (by layer) node_to = np.cumsum([s.array.size for s in self.ss]) node_from = np.array([0] + list(node_to[:-1])) node_k_slices = np.array( diff --git a/flopy/utils/binaryfile.py b/flopy/utils/binaryfile.py index 63433dd90a..10918b3695 100644 --- a/flopy/utils/binaryfile.py +++ b/flopy/utils/binaryfile.py @@ -475,7 +475,8 @@ def _build_index(self): warn_threshold = 10000000 if self.nrow > 1 and self.nrow * self.ncol > warn_threshold: warnings.warn( - f"Very large grid, ncol ({self.ncol}) * nrow ({self.nrow}) > {warn_threshold}" + f"Very large grid, ncol ({self.ncol}) * nrow ({self.nrow})" + f" > {warn_threshold}" ) self.file.seek(0, 2) self.totalbytes = self.file.tell() diff --git a/flopy/utils/check.py b/flopy/utils/check.py index 22868ad11f..47443b49d6 100644 --- a/flopy/utils/check.py +++ b/flopy/utils/check.py @@ -579,7 +579,7 @@ def summarize(self, scrub: bool = False): print("Errors and/or Warnings encountered.") if self.f is not None: print( - f" see {relpath_safe(self.summaryfile, scrub=scrub)} for details.\n" + f" see {relpath_safe(self.summaryfile, scrub=scrub)} for details.\n" # noqa ) # start of older model specific code diff --git a/flopy/utils/crs.py b/flopy/utils/crs.py index 69d7b8856f..e64f638735 100644 --- a/flopy/utils/crs.py +++ b/flopy/utils/crs.py @@ -132,7 +132,8 @@ def get_crs(prjfile=None, crs=None, **kwargs): raise ValueError( "Different coordinate reference systems " f"in crs argument and supplied projection file: {prjfile}\n" - f"\nuser supplied crs: {crs} !=\ncrs from projection file: {prjfile_crs}" + f"\nuser supplied crs: {crs} !=\n" + f"crs from projection file: {prjfile_crs}" ) else: crs = prjfile_crs diff --git a/flopy/utils/get_modflow.py b/flopy/utils/get_modflow.py index e186b1e4f8..d1a6db1175 100755 --- a/flopy/utils/get_modflow.py +++ b/flopy/utils/get_modflow.py @@ -248,7 +248,8 @@ def get_bindir_options(previous=None) -> Dict[str, Tuple[Path, str]]: def select_bindir(bindir, previous=None, quiet=False, is_cli=False) -> Path: - """Resolve an install location if provided, or prompt interactive user to select one.""" + """Resolve an install location if provided, or prompt interactive user to + select one.""" options = get_bindir_options(previous) if len(bindir) > 1: # auto-select mode diff --git a/flopy/utils/gridgen.py b/flopy/utils/gridgen.py index 2bed71fc65..59cfa51ce6 100644 --- a/flopy/utils/gridgen.py +++ b/flopy/utils/gridgen.py @@ -319,7 +319,8 @@ def set_surface_interpolation(self, isurf, type, elev=None, elev_extent=None): xmin, xmax, ymin, ymax = elev_extent except: raise ValueError( - f"Cannot unpack elev_extent as tuple (xmin, xmax, ymin, ymax): {elev_extent}" + "Cannot unpack elev_extent as tuple (xmin, xmax, ymin, ymax): " + f"{elev_extent}" ) nm = f"_gridgen.lay{isurf}.asc" @@ -335,7 +336,8 @@ def set_surface_interpolation(self, isurf, type, elev=None, elev_extent=None): self._asciigrid_dict[isurf] = elev else: raise ValueError( - "ASCIIGRID was specified but elevation was not provided as a numpy ndarray or asciigrid file." + "ASCIIGRID was specified but elevation was not provided " + "as a numpy ndarray or asciigrid file." ) def resolve_shapefile_path(self, p): diff --git a/flopy/utils/lgrutil.py b/flopy/utils/lgrutil.py index 07fc771152..1aab5ddd07 100644 --- a/flopy/utils/lgrutil.py +++ b/flopy/utils/lgrutil.py @@ -981,13 +981,15 @@ def get_disv_gridprops(self): assert ( self.lgr.ncppl.min() == self.lgr.ncppl.max() ), "Exporting disv grid properties requires ncppl to be 1." - assert ( - self.lgr.nlayp == self.lgr.nlay - ), "Exporting disv grid properties requires parent and child models to have the same number of layers." + assert self.lgr.nlayp == self.lgr.nlay, ( + "Exporting disv grid properties requires parent and child models " + "to have the same number of layers." + ) for k in range(self.lgr.nlayp - 1): - assert np.allclose( - self.lgr.idomain[k], self.lgr.idomain[k + 1] - ), "Exporting disv grid properties requires parent idomain is same for all layers." + assert np.allclose(self.lgr.idomain[k], self.lgr.idomain[k + 1]), ( + "Exporting disv grid properties requires parent idomain " + "is same for all layers." + ) # get information and build gridprops xcyc = self.get_xcyc() diff --git a/flopy/utils/mfreadnam.py b/flopy/utils/mfreadnam.py index 07625936cd..0ffc16e8cf 100644 --- a/flopy/utils/mfreadnam.py +++ b/flopy/utils/mfreadnam.py @@ -299,7 +299,8 @@ def get_entries_from_namefile( unit: int = None, extension: str = None, ) -> list[tuple]: - """Get entries from an MF6 namefile. Can select using FTYPE, UNIT, or file extension. + """Get entries from an MF6 namefile. Can select using FTYPE, UNIT, or file + extension. This function only supports MF6 namefiles. Parameters diff --git a/flopy/utils/modpathfile.py b/flopy/utils/modpathfile.py index 550db47891..efc5772e15 100644 --- a/flopy/utils/modpathfile.py +++ b/flopy/utils/modpathfile.py @@ -375,7 +375,8 @@ def write_shapefile( .get_alldata() (if None, .get_alldata() is exported). .. deprecated:: 3.7 - The ``timeseries_data`` option will be removed for FloPy 4. Use ``data`` instead. + The ``timeseries_data`` option will be removed for FloPy 4. + Use ``data`` instead. one_per_particle : boolean (default True) True writes a single LineString with a single set of attribute data for each particle. False writes a record/geometry for each @@ -701,7 +702,8 @@ def write_shapefile( (if none, EndpointFile.get_alldata() is exported). .. deprecated:: 3.7 - The ``endpoint_data`` option will be removed for FloPy 4. Use ``data`` instead. + The ``endpoint_data`` option will be removed for FloPy 4. + Use ``data`` instead. shpname : str File path for shapefile direction : str @@ -939,7 +941,8 @@ def write_shapefile( is exported). .. deprecated:: 3.7 - The ``timeseries_data`` option will be removed for FloPy 4. Use ``data`` instead. + The ``timeseries_data`` option will be removed for FloPy 4. + Use ``data`` instead. one_per_particle : boolean (default True) True writes a single LineString with a single set of attribute data for each particle. False writes a record/geometry for each diff --git a/flopy/utils/mtlistfile.py b/flopy/utils/mtlistfile.py index 5d562606e2..c39de07dfb 100644 --- a/flopy/utils/mtlistfile.py +++ b/flopy/utils/mtlistfile.py @@ -466,5 +466,6 @@ def _extract_number_between_strings(input_string, start_string, end_string): return extracted_number else: raise Exception( - f"Error extracting number between {start_string} and {end_string} in {input_string}" + "Error extracting number between " + f"{start_string} and {end_string} in {input_string}" ) diff --git a/flopy/utils/swroutputfile.py b/flopy/utils/swroutputfile.py index eed918b87f..c1091346d7 100644 --- a/flopy/utils/swroutputfile.py +++ b/flopy/utils/swroutputfile.py @@ -746,7 +746,8 @@ def __init__(self, filename, precision="double", verbose=False): class SwrExchange(SwrFile): """ - Read binary SWR surface-water groundwater exchange output from MODFLOW SWR Process binary output files + Read binary SWR surface-water groundwater exchange output from + MODFLOW SWR Process binary output files Parameters ---------- diff --git a/flopy/utils/util_array.py b/flopy/utils/util_array.py index 0000345b72..35312a8345 100644 --- a/flopy/utils/util_array.py +++ b/flopy/utils/util_array.py @@ -2341,7 +2341,8 @@ def string(self): Note: the string representation DOES NOT include the effects of the control - record multiplier - this method is used primarily for writing model input files + record multiplier - this method is used primarily for writing model + input files """ # convert array to string with specified format @@ -2388,9 +2389,9 @@ def _array(self): if value is a string or a constant, the array is loaded/built only once Note: - the return array representation DOES NOT include the effect of the multiplier - in the control record. To get the array as the model sees it (with the multiplier applied), - use the Util2d.array method. + the return array representation DOES NOT include the effect of the + multiplier in the control record. To get the array as the model + sees it (with the multiplier applied), use the Util2d.array method. """ if self.vtype == str: if self.__value_built is None: diff --git a/flopy/utils/utl_import.py b/flopy/utils/utl_import.py index 46b24fae53..51ebacad01 100644 --- a/flopy/utils/utl_import.py +++ b/flopy/utils/utl_import.py @@ -1,3 +1,4 @@ +# ruff: noqa: E501 # Vendored from https://github.com/pandas-dev/pandas/blob/master/pandas/compat/_optional.py # changeset d30aeeba0c79fb8e4b651a8f528e87c3de8cb898 # 10/11/2021 diff --git a/pyproject.toml b/pyproject.toml index db93cda2e8..f1f174bab8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -144,7 +144,6 @@ select = [ ] ignore = [ "E402", # module level import not at top of file - "E501", # line too long TODO FIXME "E712", # Avoid equality comparisons to `True` "E722", # do not use bare `except` "E721", # use `is`/`is not` for type comparisons @@ -158,4 +157,5 @@ ignore = [ ] [tool.ruff.lint.per-file-ignores] -"flopy/mf6/**/*.py" = ["ISC001"] \ No newline at end of file +".docs/**/*.py" = ["E501"] +"flopy/mf6/**/*.py" = ["E501", "ISC001"]