Skip to content

Commit

Permalink
chore: reformat Python code with line length = 88 (#57)
Browse files Browse the repository at this point in the history
Reformat Python code with a maximum line length of 88 characters to better represent the code.

See modflowpy/flopy#2362 for a related PR with rational and discussion.

Also change some of Ruff's configuration:

- Remove target-version, since it was outdated and is automatically evaluated from pyproject.toml
- Remove include so that Ruff will work globally in this repo
- Remove extend-include since "*.ipynb" files are already included by default
  • Loading branch information
mwtoews authored Nov 20, 2024
1 parent 7fb6b67 commit 4cee570
Show file tree
Hide file tree
Showing 13 changed files with 35 additions and 116 deletions.
13 changes: 3 additions & 10 deletions autotest/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ def pytest_generate_tests(metafunc):
# - ex-gwtgwt-mt3dms-p10: https://github.com/MODFLOW-USGS/modflow6/pull/1008
option_value = metafunc.config.option.mf6_examples_path
t = metafunc.fixturenames
if (
"mf6_example_namfiles" in metafunc.fixturenames
and option_value is not None
):
if "mf6_example_namfiles" in metafunc.fixturenames and option_value is not None:
mf6_examples_path = Path(option_value)
global __mf6_examples
__mf6_examples = str(mf6_examples_path.name)
Expand Down Expand Up @@ -97,9 +94,7 @@ def simulation_name_from_model_path(p):
model_namfiles = list(model_namfiles)
if len(model_namfiles) > 1:
# trap gwf models as first set of models
idxs = [
ix for ix, _ in enumerate(model_namfiles) if "gwf" in _
]
idxs = [ix for ix, _ in enumerate(model_namfiles) if "gwf" in _]
if len(idxs) > 0:
for ix in idxs[::-1]:
models.append(model_namfiles.pop(ix))
Expand All @@ -125,6 +120,4 @@ def simulation_name_from_model_namfiles(mnams):
namfile.parent.parent if is_nested(namfile) else namfile.parent
).name

metafunc.parametrize(
key, simulations, ids=simulation_name_from_model_namfiles
)
metafunc.parametrize(key, simulations, ids=simulation_name_from_model_namfiles)
12 changes: 3 additions & 9 deletions autotest/test_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,7 @@ def callback(sim, step):

rch = model.rch
if len(rch) != 2:
raise AssertionError(
"ApiModel object not returning multiple packages"
)
raise AssertionError("ApiModel object not returning multiple packages")

idomain = dis.idomain.values
if not isinstance(idomain, np.ndarray):
Expand Down Expand Up @@ -193,9 +191,7 @@ def callback(sim, step):

chd = model.chd
if len(chd) != 2:
raise AssertionError(
"ApiModel object not returning multiple packages"
)
raise AssertionError("ApiModel object not returning multiple packages")

top = dis.top.values
if not isinstance(top, np.ndarray):
Expand Down Expand Up @@ -347,9 +343,7 @@ def callback(sim, step):
if step == Callbacks.timestep_start:
if sim.kstp == 1:
if delt0 == sim.delt:
raise AssertionError(
"ATS routines not reducing timestep length"
)
raise AssertionError("ATS routines not reducing timestep length")

name = "ats0"
sim_pth = data_pth / name
Expand Down
4 changes: 1 addition & 3 deletions autotest/test_mf6_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ def run_models():
# (e.g. 'mf6gwf') because coupled models refer to each other with
# relative paths
wrkdir = (
Path(function_tmpdir / model_path.name)
if nested
else function_tmpdir
Path(function_tmpdir / model_path.name) if nested else function_tmpdir
)
try:
run_simulation(dll, wrkdir, callback, verbose=True)
Expand Down
4 changes: 1 addition & 3 deletions examples/notebooks/Head_Monitor_Example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,7 @@
" fig, ax = plt.subplots(figsize=(8, 8))\n",
" self.fig = fig\n",
" self.ax = ax\n",
" self.pmv = PlotMapView(\n",
" modelgrid=self.modelgrid, ax=ax, layer=self.layer\n",
" )\n",
" self.pmv = PlotMapView(modelgrid=self.modelgrid, ax=ax, layer=self.layer)\n",
" grid = self.pmv.plot_grid()\n",
" idm = self.pmv.plot_inactive()\n",
" initial = np.full(self.modelgrid.shape, np.nan)\n",
Expand Down
4 changes: 1 addition & 3 deletions examples/notebooks/MODFLOW-API_extensions_objects.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -778,9 +778,7 @@
" spd[\"recharge\"] += 0.40 * sim.kper\n",
"\n",
" if callback_step == Callbacks.timestep_start:\n",
" print(\n",
" f\"updating wel flux: stress_period={ml.kper}, timestep={ml.kstp}\"\n",
" )\n",
" print(f\"updating wel flux: stress_period={ml.kper}, timestep={ml.kstp}\")\n",
" ml.wel.stress_period_data[\"q\"] -= ml.kstp * 1.5\n",
"\n",
" if callback_step == Callbacks.iteration_start:\n",
Expand Down
4 changes: 1 addition & 3 deletions examples/notebooks/Quickstart.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,7 @@
" spd[\"recharge\"] += 0.40 * sim.kper\n",
"\n",
" if callback_step == Callbacks.timestep_start:\n",
" print(\n",
" f\"updating wel flux: stress_period={ml.kper}, timestep={ml.kstp}\"\n",
" )\n",
" print(f\"updating wel flux: stress_period={ml.kper}, timestep={ml.kstp}\")\n",
" ml.wel.stress_period_data[\"q\"] -= ml.kstp * 1.5\n",
"\n",
" if callback_step == Callbacks.iteration_start:\n",
Expand Down
21 changes: 5 additions & 16 deletions modflowapi/extensions/apimodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ def _create_package_list(self):
package = package(basepackage, self, pkg_type, adj_pkg_name)
self.package_dict[pkg_name.lower()] = package

def get_package(
self, pkg_name
) -> ListPackage or ArrayPackage or AdvancedPackage:
def get_package(self, pkg_name) -> ListPackage or ArrayPackage or AdvancedPackage:
"""
Method to get a package
Expand All @@ -115,9 +113,7 @@ def get_package(
if pkg_name in self.package_dict:
return self.package_dict[pkg_name]

raise KeyError(
f"{pkg_name} is not a valid package name for this model"
)
raise KeyError(f"{pkg_name} is not a valid package name for this model")


class ApiModel(ApiMbase):
Expand Down Expand Up @@ -148,9 +144,7 @@ def __init__(self, mf6, name):
self.dis_type = "disu"
self.dis_name = "DIS"
else:
raise AssertionError(
f"Unrecognized discretization type {grid_type}"
)
raise AssertionError(f"Unrecognized discretization type {grid_type}")

pkg_types = {
"dis": ArrayPackage,
Expand Down Expand Up @@ -192,10 +186,7 @@ def __repr__(self):
s = f"{self.name}, "
shape = self.shape
if self.dis_type == "dis":
s += (
f"{shape[0]} Layer, {shape[1]} Row, {shape[2]} "
f"Column model\n"
)
s += f"{shape[0]} Layer, {shape[1]} Row, {shape[2]} Column model\n"

elif self.dis_type == "disu":
if len(shape) == 2:
Expand Down Expand Up @@ -319,9 +310,7 @@ def shape(self):
if var_addr in ivn:
shape.append(self.mf6.get_value(var_addr)[0])
if not shape:
var_addr = self.mf6.get_var_address(
"NODES", self.name, self.dis_name
)
var_addr = self.mf6.get_var_address("NODES", self.name, self.dis_name)
shape.append(self.mf6.get_value(var_addr)[0])
self._shape = tuple(shape)
return self._shape
Expand Down
12 changes: 3 additions & 9 deletions modflowapi/extensions/apisimulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,7 @@ def get_model(self, model_id=None):
model name (ex. "GWF_1") or subcomponent id (ex. 1)
"""
if model_id is None:
model_id = int(
min([model.subcomponent_id for model in self.models])
)
model_id = int(min([model.subcomponent_id for model in self.models]))

if isinstance(model_id, int):
for model in self.models:
Expand Down Expand Up @@ -329,9 +327,7 @@ def load(mf6):

# TDIS package construction
tdis_constructor = package_factory("tdis", ScalarPackage)
tdis = tdis_constructor(
ScalarPackage, tmpmdl, "tdis", "tdis", sim_package=True
)
tdis = tdis_constructor(ScalarPackage, tmpmdl, "tdis", "tdis", sim_package=True)

ats = None
# ATS package construction
Expand All @@ -346,9 +342,7 @@ def load(mf6):
# get the exchanges
exchange_names = []
for variable in variables:
if variable.startswith("GWF-GWF") or variable.startswith(
"GWT-GWT"
):
if variable.startswith("GWF-GWF") or variable.startswith("GWT-GWT"):
exchange_name = variable.split("/")[0]
if exchange_name not in exchange_names:
exchange_names.append(exchange_name)
Expand Down
28 changes: 7 additions & 21 deletions modflowapi/extensions/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,27 +237,19 @@ def _recarray_to_ptr(self, recarray):

for name in recarray.dtype.names:
if name in self._nodevars:
multi_index = tuple(
np.array([list(i) for i in recarray[name]]).T
)
nodes = np.ravel_multi_index(
multi_index, self.parent.model.shape
)
multi_index = tuple(np.array([list(i) for i in recarray[name]]).T)
nodes = np.ravel_multi_index(multi_index, self.parent.model.shape)
recarray[name] = self.parent.model.usertonode[nodes] + 1

if name in self.parent._bound_vars:
if "bound" in self._ptrs:
# Block slated for deprecation after IDM inclusion
idx = self.parent._bound_vars.index(name)
bname = "bound"
self._ptrs[bname][0 : self._nbound[0], idx] = recarray[
name
]
self._ptrs[bname][0 : self._nbound[0], idx] = recarray[name]
elif self.parent._idm_enabled:
# new IDM simplification
self._ptrs[name][0 : self._nbound[0]] = recarray[
name
].ravel()
self._ptrs[name][0 : self._nbound[0]] = recarray[name].ravel()
else:
pass
elif name in self._auxnames:
Expand Down Expand Up @@ -569,9 +561,7 @@ def set_array(self, item, array):
if item in self._ptrs:
self._ptrs[item].values = array
else:
raise KeyError(
f"{item} is not a valid variable name for this package"
)
raise KeyError(f"{item} is not a valid variable name for this package")


class AdvancedInput(object):
Expand Down Expand Up @@ -631,13 +621,9 @@ def get_variable(self, name, model=None, package=None):
)
else:
if self.parent is not None:
var_addr = self.mf6.get_var_address(
name.upper(), self.parent.pkg_name
)
var_addr = self.mf6.get_var_address(name.upper(), self.parent.pkg_name)
else:
var_addr = self.mf6.get_var_address(
name.upper(), package.upper()
)
var_addr = self.mf6.get_var_address(name.upper(), package.upper())

try:
values = self.mf6.get_value_ptr(var_addr)
Expand Down
23 changes: 6 additions & 17 deletions modflowapi/extensions/pakbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,9 +258,7 @@ def __init__(self, model, pkg_type, pkg_name, child_type, sim_package):

if sim_package:
var_addrs.append(
self.model.mf6.get_var_address(
var.upper(), self.pkg_name
)
self.model.mf6.get_var_address(var.upper(), self.pkg_name)
)
else:
var_addrs.append(
Expand Down Expand Up @@ -335,8 +333,7 @@ def get_advanced_var(self, name):
name = name.lower()
if name not in self.advanced_vars:
raise AssertionError(
f"{name} is not accessible as an advanced "
f"variable for this package"
f"{name} is not accessible as an advanced variable for this package"
)

values = self._variables_adv.get_variable(name)
Expand Down Expand Up @@ -432,9 +429,7 @@ class ListPackage(PackageBase):
"""

def __init__(self, model, pkg_type, pkg_name, sim_package=False):
super().__init__(
model, pkg_type, pkg_name.upper(), "list", sim_package
)
super().__init__(model, pkg_type, pkg_name.upper(), "list", sim_package)

self._variables = ListInput(self)

Expand Down Expand Up @@ -497,9 +492,7 @@ class ArrayPackage(PackageBase):
"""

def __init__(self, model, pkg_type, pkg_name, sim_package=False):
super().__init__(
model, pkg_type, pkg_name.upper(), "array", sim_package
)
super().__init__(model, pkg_type, pkg_name.upper(), "array", sim_package)

self._variables = ArrayInput(self)

Expand Down Expand Up @@ -595,9 +588,7 @@ class ScalarPackage(PackageBase):
"""

def __init__(self, model, pkg_type, pkg_name, sim_package=False):
super().__init__(
model, pkg_type, pkg_name.upper(), "scalar", sim_package
)
super().__init__(model, pkg_type, pkg_name.upper(), "scalar", sim_package)

self._variables = ScalarInput(self)

Expand Down Expand Up @@ -697,9 +688,7 @@ class AdvancedPackage(PackageBase):
"""

def __init__(self, model, pkg_type, pkg_name, sim_package=False):
super().__init__(
model, pkg_type, pkg_name.upper(), "advanced", sim_package
)
super().__init__(model, pkg_type, pkg_name.upper(), "advanced", sim_package)

def __repr__(self):
s = f"{self.pkg_type.upper()} Package: {self.pkg_name} \n"
Expand Down
5 changes: 1 addition & 4 deletions modflowapi/extensions/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@ def run_simulation(dll, sim_path, callback, verbose=False, _develop=False):
mf6.prepare_time_step(dt)

if verbose:
print(
f"Solving: Stress Period {sim.kper + 1}; "
f"Timestep {sim.kstp + 1}"
)
print(f"Solving: Stress Period {sim.kper + 1}; Timestep {sim.kstp + 1}")

for sol_id, slnobj in sorted(sim.solutions.items()):
models = {}
Expand Down
13 changes: 1 addition & 12 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,7 @@ version = {attr = "modflowapi.version.__version__"}
include = ["modflowapi", "modflowapi.*"]

[tool.ruff]
target-version = "py38"
line-length = 79
include = [
"pyproject.toml",
"modflowapi/**/*.py",
"autotest/**/*.py",
"examples/**/*.py",
"scripts/**/*.py",
]
extend-include = [
"examples/**/*.ipynb"
]
line-length = 88

[tool.ruff.lint]
select = ["F", "E", "I001"]
Expand Down
8 changes: 2 additions & 6 deletions scripts/update_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def update_version_py(timestamp: datetime, version: Version):
f"# {_project_name} version file automatically "
+ f"created using...{basename(__file__)}\n"
)
f.write(
"# created on..." + f"{timestamp.strftime('%B %d, %Y %H:%M:%S')}\n"
)
f.write(f"# created on...{timestamp.strftime('%B %d, %Y %H:%M:%S')}\n")
f.write(f'__version__ = "{version}"\n')
log_update(_version_py_path, version)

Expand Down Expand Up @@ -109,7 +107,5 @@ def update_version(
else:
update_version(
timestamp=datetime.now(),
version=(
Version(args.version) if args.version else _current_version
),
version=(Version(args.version) if args.version else _current_version),
)

0 comments on commit 4cee570

Please sign in to comment.