Skip to content

Commit

Permalink
refactor: run pyupgrade and adjust a few f-strings (#1710)
Browse files Browse the repository at this point in the history
  • Loading branch information
mwtoews committed Feb 14, 2023
1 parent e2cbb25 commit 649596d
Show file tree
Hide file tree
Showing 71 changed files with 247 additions and 299 deletions.
6 changes: 3 additions & 3 deletions .docs/conf.py
Expand Up @@ -23,7 +23,7 @@
on_rtd = os.environ.get("READTHEDOCS") == "True"

# -- determine if this version is a release candidate
with open("../README.md", "r") as f:
with open("../README.md") as f:
lines = f.readlines()
rc_text = ""
for line in lines:
Expand All @@ -38,7 +38,7 @@

# -- update version number in main.rst
rst_name = "main.rst"
with open(rst_name, "r") as f:
with open(rst_name) as f:
lines = f.readlines()
with open(rst_name, "w") as f:
for line in lines:
Expand All @@ -51,7 +51,7 @@

# -- update authors in introduction.rst
rst_name = "introduction.rst"
with open(rst_name, "r") as f:
with open(rst_name) as f:
lines = f.readlines()
tag_start = "FloPy Development Team"
tag_end = "How to Cite"
Expand Down
6 changes: 3 additions & 3 deletions autotest/regression/test_mf6.py
Expand Up @@ -533,7 +533,7 @@ def test_np001(function_tmpdir, example_data_path):
mpath = sim.simulation_data.mfpath.get_model_path(model.name)
spath = sim.simulation_data.mfpath.get_sim_path()
found_cellid = False
with open(os.path.join(mpath, "np001_mod.wel"), "r") as fd:
with open(os.path.join(mpath, "np001_mod.wel")) as fd:
for line in fd:
line_lst = line.strip().split()
if (
Expand Down Expand Up @@ -561,7 +561,7 @@ def test_np001(function_tmpdir, example_data_path):
found_begin = False
found_end = False
text_between_begin_and_end = False
with open(os.path.join(mpath, "file_rename.wel"), "r") as fd:
with open(os.path.join(mpath, "file_rename.wel")) as fd:
for line in fd:
if line.strip().lower() == "begin period 2":
found_begin = True
Expand All @@ -587,7 +587,7 @@ def test_np001(function_tmpdir, example_data_path):
found_begin = False
found_end = False
text_between_begin_and_end = False
with open(os.path.join(mpath, "np001_spd_test.wel"), "r") as fd:
with open(os.path.join(mpath, "np001_spd_test.wel")) as fd:
for line in fd:
if line.strip().lower() == "begin period 2":
found_begin = True
Expand Down
2 changes: 1 addition & 1 deletion autotest/test_binarygrid_util.py
Expand Up @@ -116,7 +116,7 @@ def test_mfgrddisv_modelgrid(mfgrd_test_path):
f"does not equal {nvert}"
)

cellxy = np.column_stack((mg.xyzcellcenters[:2]))
cellxy = np.column_stack(mg.xyzcellcenters[:2])
errmsg = (
f"shape of flow.disv centroids {cellxy.shape} not equal to (218, 2)."
)
Expand Down
6 changes: 3 additions & 3 deletions autotest/test_get_modflow.py
Expand Up @@ -123,9 +123,9 @@ def test_get_release(repo):

if repo == "modflow6":
# can remove if modflow6 releases follow asset name conventions followed in executables and nightly build repos
assert set([a.rpartition("_")[2] for a in actual_assets]) >= set(
[a for a in expected_assets if not a.startswith("win")]
)
assert {a.rpartition("_")[2] for a in actual_assets} >= {
a for a in expected_assets if not a.startswith("win")
}
else:
assert set(actual_assets) >= set(expected_assets)

Expand Down
10 changes: 4 additions & 6 deletions autotest/test_grid.py
Expand Up @@ -501,7 +501,7 @@ def test_unstructured_from_gridspec(example_data_path):
spec_path = str(model_path / "freyberg.usg.gsf")
grid = UnstructuredGrid.from_gridspec(spec_path)

with open(spec_path, "r") as file:
with open(spec_path) as file:
lines = file.readlines()
split = [line.strip().split() for line in lines]

Expand Down Expand Up @@ -1019,11 +1019,9 @@ def test_get_lni_unstructured(grid):
layer, i = grid.get_lni([nn])[0]
csum = [0] + list(
np.cumsum(
(
list(grid.ncpl)
if not isinstance(grid.ncpl, int)
else [grid.ncpl for _ in range(grid.nlay)]
)
list(grid.ncpl)
if not isinstance(grid.ncpl, int)
else [grid.ncpl for _ in range(grid.nlay)]
)
)
assert csum[layer] + i == nn
2 changes: 1 addition & 1 deletion autotest/test_gridintersect.py
Expand Up @@ -1220,7 +1220,7 @@ def test_polygon_offset_rot_structured_grid_shapely(rtree):
# %% test rasters


@requires_pkg("rasterstats")
@requires_pkg("rasterstats", "scipy")
def test_rasters(example_data_path):
ws = str(example_data_path / "options")
raster_name = "dem.img"
Expand Down
24 changes: 4 additions & 20 deletions autotest/test_lake_connections.py
Expand Up @@ -255,11 +255,7 @@ def test_lake(function_tmpdir, example_data_path):
# mm = flopy.plot.PlotMapView(modelgrid=gwf.modelgrid)
# mm.plot_array(k11_tm)

(
idomain,
pakdata_dict,
connectiondata,
) = get_lak_connections(
idomain, pakdata_dict, connectiondata = get_lak_connections(
gwf.modelgrid,
lakes,
bedleak=5e-9,
Expand Down Expand Up @@ -459,11 +455,7 @@ def test_embedded_lak_ex01(function_tmpdir, example_data_path):
printrecord=[("HEAD", "ALL"), ("BUDGET", "ALL")],
)

(
idomain,
pakdata_dict,
connectiondata,
) = get_lak_connections(
idomain, pakdata_dict, connectiondata = get_lak_connections(
gwf.modelgrid,
lake_map,
bedleak=0.1,
Expand Down Expand Up @@ -559,11 +551,7 @@ def test_embedded_lak_prudic(example_data_path):
)

# flopy test
(
idomain_rev,
pakdata_dict,
connectiondata,
) = get_lak_connections(
idomain_rev, pakdata_dict, connectiondata = get_lak_connections(
model_grid,
lake_map,
idomain=idomain,
Expand Down Expand Up @@ -668,11 +656,7 @@ def test_embedded_lak_prudic_mixed(example_data_path):
)

# test mixed lakebed leakance list
(
_,
_,
connectiondata,
) = get_lak_connections(
_, _, connectiondata = get_lak_connections(
model_grid,
lake_map,
idomain=idomain,
Expand Down
21 changes: 11 additions & 10 deletions autotest/test_mf6.py
Expand Up @@ -173,8 +173,8 @@ def get_gwf_model(sim, gwfname, gwfpath, modelshape, chdspd=None, welspd=None):
# output control
oc = ModflowGwfoc(
gwf,
budget_filerecord="{}.cbc".format(gwfname),
head_filerecord="{}.hds".format(gwfname),
budget_filerecord=f"{gwfname}.cbc",
head_filerecord=f"{gwfname}.hds",
headprintrecord=[("COLUMNS", 10, "WIDTH", 15, "DIGITS", 6, "GENERAL")],
saverecord=[("HEAD", "LAST"), ("BUDGET", "LAST")],
printrecord=[("HEAD", "LAST"), ("BUDGET", "LAST")],
Expand Down Expand Up @@ -226,8 +226,8 @@ def get_gwt_model(sim, gwtname, gwtpath, modelshape, sourcerecarray=None):
# output control
oc = ModflowGwtoc(
gwt,
budget_filerecord="{}.cbc".format(gwtname),
concentration_filerecord="{}.ucn".format(gwtname),
budget_filerecord=f"{gwtname}.cbc",
concentration_filerecord=f"{gwtname}.ucn",
concentrationprintrecord=[
("COLUMNS", 10, "WIDTH", 15, "DIGITS", 6, "GENERAL")
],
Expand Down Expand Up @@ -1031,6 +1031,7 @@ def test_output_add_observation(function_tmpdir, example_data_path):
sfr_obs, Mf6Obs
), "remove and add observation test (Mf6Output) failed"

@requires_exe("mf6")
def test_sfr_connections(function_tmpdir, example_data_path):
'''MODFLOW just warns if any reaches are unconnected
flopy fails to load model if reach 1 is unconnected, fine with other unconnected'''
Expand All @@ -1039,7 +1040,7 @@ def test_sfr_connections(function_tmpdir, example_data_path):
for test in ['sfr0', 'sfr1']:
sim_name = "test_sfr"
model_name = "test_sfr"
tdis_name = "{}.tdis".format(sim_name)
tdis_name = f"{sim_name}.tdis"
sim = MFSimulation(
sim_name=sim_name, version="mf6", exe_name="mf6", sim_ws=sim_ws
)
Expand All @@ -1053,7 +1054,7 @@ def test_sfr_connections(function_tmpdir, example_data_path):
complexity="SIMPLE",
)
model = ModflowGwf(
sim, modelname=model_name, model_nam_file="{}.nam".format(model_name)
sim, modelname=model_name, model_nam_file=f"{model_name}.nam"
)

dis = ModflowGwfdis(
Expand All @@ -1077,7 +1078,7 @@ def test_sfr_connections(function_tmpdir, example_data_path):
icelltype=1,
k=50.0,
)

cnfile = f'mf6_{test}_connection.txt'
pkfile = f'mf6_{test}_package.txt'

Expand Down Expand Up @@ -1115,7 +1116,7 @@ def test_array(function_tmpdir):
sim_name = "test_array"
model_name = "test_array"
out_dir = function_tmpdir
tdis_name = "{}.tdis".format(sim_name)
tdis_name = f"{sim_name}.tdis"
sim = MFSimulation(
sim_name=sim_name, version="mf6", exe_name="mf6", sim_ws=out_dir
)
Expand All @@ -1138,7 +1139,7 @@ def test_array(function_tmpdir):
number_orthogonalizations=2,
)
model = ModflowGwf(
sim, modelname=model_name, model_nam_file="{}.nam".format(model_name)
sim, modelname=model_name, model_nam_file=f"{model_name}.nam"
)

dis = ModflowGwfdis(
Expand Down Expand Up @@ -1700,7 +1701,7 @@ def test_namefile_creation(tmpdir):
model = ModflowGwf(
sim,
modelname=test_ex_name,
model_nam_file="{}.nam".format(test_ex_name),
model_nam_file=f"{test_ex_name}.nam",
)

# try to create simulation name file
Expand Down
2 changes: 1 addition & 1 deletion autotest/test_mnw.py
Expand Up @@ -353,7 +353,7 @@ def test_mnw2_create_file(function_tmpdir):
mnwmax=len(wells),
mnw=wells,
itmp=list(
(np.ones((len(stress_period_data.index))) * len(wellids)).astype(
(np.ones(len(stress_period_data.index)) * len(wellids)).astype(
int
)
),
Expand Down
6 changes: 3 additions & 3 deletions autotest/test_modpathfile.py
Expand Up @@ -66,7 +66,7 @@ def get_nodes(locs):
)

# Create the Flopy groundwater flow (gwf) model object
model_nam_file = "{}.nam".format(name)
model_nam_file = f"{name}.nam"
gwf = ModflowGwf(
sim, modelname=name, model_nam_file=model_nam_file, save_flows=True
)
Expand Down Expand Up @@ -113,9 +113,9 @@ def get_nodes(locs):
ModflowGwfriv(gwf, stress_period_data={0: rd})

# Create the output control package
headfile = "{}.hds".format(name)
headfile = f"{name}.hds"
head_record = [headfile]
budgetfile = "{}.cbb".format(name)
budgetfile = f"{name}.cbb"
budget_record = [budgetfile]
saverecord = [("HEAD", "ALL"), ("BUDGET", "ALL")]
oc = ModflowGwfoc(
Expand Down
4 changes: 2 additions & 2 deletions autotest/test_mp6.py
Expand Up @@ -834,8 +834,8 @@ def test_mp_wpandas_wo_pandas(ml):
assert success

# read the two files and ensure they are identical
with open(mp_pandas.get_package("loc").fn_path, "r") as f:
with open(mp_pandas.get_package("loc").fn_path) as f:
particles_pandas = f.readlines()
with open(mp_no_pandas.get_package("loc").fn_path, "r") as f:
with open(mp_no_pandas.get_package("loc").fn_path) as f:
particles_no_pandas = f.readlines()
assert particles_pandas == particles_no_pandas
1 change: 0 additions & 1 deletion autotest/test_pcg.py
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
This simple script tests that the pcg load function works for both free-
and fixed-format pcg files for mf2005 models.
Expand Down
8 changes: 4 additions & 4 deletions autotest/test_zonbud_utility.py
Expand Up @@ -29,7 +29,7 @@ def zbud_f(loadpth):


def read_zonebudget_file(fname):
with open(fname, "r") as f:
with open(fname) as f:
lines = f.readlines()

rows = []
Expand Down Expand Up @@ -112,8 +112,8 @@ def test_compare2zonebudget(cbc_f, zon_f, zbud_f, rtol):
zb_arr = zba[zba["totim"] == time]
fp_arr = fpa[fpa["totim"] == time]
for name in fp_arr["name"]:
r1 = np.where((zb_arr["name"] == name))
r2 = np.where((fp_arr["name"] == name))
r1 = np.where(zb_arr["name"] == name)
r2 = np.where(fp_arr["name"] == name)
if r1[0].shape[0] < 1 or r2[0].shape[0] < 1:
continue
if r1[0].shape[0] != r2[0].shape[0]:
Expand Down Expand Up @@ -167,7 +167,7 @@ def test_zonbud_to_csv(function_tmpdir, cbc_f, zon_f):
zb = ZoneBudget(str(cbc_f), zon, kstpkper=[(0, 1094), (0, 1096)])
f_out = os.path.join(str(function_tmpdir), "test.csv")
zb.to_csv(f_out)
with open(f_out, "r") as f:
with open(f_out) as f:
lines = f.readlines()
assert len(lines) > 0, "No data written to csv file."

Expand Down
18 changes: 8 additions & 10 deletions examples/groundwater_paper/scripts/uspb_capture.py
Expand Up @@ -99,12 +99,10 @@ def cf_model(model, k, i, j, base, Q=-100):
ncol2 = ncol // nstep

# open summary file
fs = open(
os.path.join("data", "uspb", "uspb_capture_{}.out".format(nstep)), "w", 0
)
fs = open(os.path.join("data", "uspb", f"uspb_capture_{nstep}.out"), "w", 0)

# write some summary information
fs.write("Problem size: {} rows and {} columns.\n".format(nrow, ncol))
fs.write(f"Problem size: {nrow} rows and {ncol} columns.\n")
fs.write(
"Capture fraction analysis performed every {} rows and columns.\n".format(
nstep
Expand Down Expand Up @@ -141,7 +139,7 @@ def cf_model(model, k, i, j, base, Q=-100):
s0 = time.time()
cf = cf_model(ml, 3, i, j, baseQ)
s1 = time.time()
line = " model {} run time: {} seconds\n".format(idx, s1 - s0)
line = f" model {idx} run time: {s1 - s0} seconds\n"
fs.write(line)
sys.stdout.write(line)
idx += 1
Expand All @@ -158,9 +156,9 @@ def cf_model(model, k, i, j, base, Q=-100):
ets = end - start
line = (
"\n"
+ "streamflow capture analysis took {} seconds.\n".format(ets)
+ "streamflow capture analysis took {} minutes.\n".format(ets / 60.0)
+ "streamflow capture analysis took {} hours.\n".format(ets / 3600.0)
+ f"streamflow capture analysis took {ets} seconds.\n"
+ f"streamflow capture analysis took {ets / 60.0} minutes.\n"
+ f"streamflow capture analysis took {ets / 3600.0} hours.\n"
)
fs.write(line)
sys.stdout.write(line)
Expand All @@ -179,7 +177,7 @@ def cf_model(model, k, i, j, base, Q=-100):
for idx in range(10):
fn = os.path.join(
res_pth,
"USPB_capture_fraction_{:02d}_{:02d}.dat".format(nstep, idx + 1),
f"USPB_capture_fraction_{nstep:02d}_{idx + 1:02d}.dat",
)
print("saving capture fraction data to...{}".format(os.path.basename(fn)))
print(f"saving capture fraction data to...{os.path.basename(fn)}")
np.savetxt(fn, cf_array[idx, :, :], delimiter=" ")

0 comments on commit 649596d

Please sign in to comment.