Skip to content

Commit

Permalink
Upgrade pre-commits ruff 0.8.6 -> 0.9.1
Browse files Browse the repository at this point in the history
  • Loading branch information
larsevj committed Jan 13, 2025
1 parent ea36931 commit 65f34db
Show file tree
Hide file tree
Showing 61 changed files with 168 additions and 182 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ repos:
exclude: test-data/ert/eclipse/parse/ERROR.PRT # exact format is needed for testing

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
args: [ --fix ]
Expand Down
8 changes: 4 additions & 4 deletions src/_ert/forward_model_runner/forward_model_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def _create_exited_message_based_on_exit_code(
self.job_data["error_file"]
):
return exited_message.with_error(
f'Found the error file:{self.job_data["error_file"]} - job failed.'
f"Found the error file:{self.job_data['error_file']} - job failed."
)

if target_file_mtime:
Expand All @@ -264,7 +264,7 @@ def _create_exited_msg_for_non_zero_exit_code(
f"Forward model step {self.job_data.get('name')} "
f"was killed due to out-of-memory on {socket.gethostname()}. "
"Max memory usage recorded by Ert for the "
f"realization was {max_memory_usage//1024//1024} MB. "
f"realization was {max_memory_usage // 1024 // 1024} MB. "
"Please add REALIZATION_MEMORY to your ert config together "
"with a suitable memory amount to avoid this."
)
Expand Down Expand Up @@ -322,12 +322,12 @@ def _check_job_files(self) -> list[str]:
"""
errors = []
if self.job_data.get("stdin") and not os.path.exists(self.job_data["stdin"]):
errors.append(f'Could not locate stdin file: {self.job_data["stdin"]}')
errors.append(f"Could not locate stdin file: {self.job_data['stdin']}")

if self.job_data.get("start_file") and not os.path.exists(
cast(Path, self.job_data["start_file"])
):
errors.append(f'Could not locate start_file:{self.job_data["start_file"]}')
errors.append(f"Could not locate start_file:{self.job_data['start_file']}")

if self.job_data.get("error_file") and os.path.exists(
cast(Path, self.job_data.get("error_file"))
Expand Down
3 changes: 1 addition & 2 deletions src/ert/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,7 @@ async def forward_model_ok(
)
parameters_result = LoadResult(
LoadStatus.LOAD_FAILURE,
"Failed to load results for realization "
f"{realization}, failed with: {err}",
f"Failed to load results for realization {realization}, failed with: {err}",
)

final_result = parameters_result
Expand Down
2 changes: 1 addition & 1 deletion src/ert/config/ert_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,7 @@ def _create_list_of_forward_model_steps_to_run(
)
except Exception as e: # type: ignore
ConfigWarning.warn(
f"Unexpected plugin forward model exception: " f"{e!s}",
f"Unexpected plugin forward model exception: {e!s}",
context=fm_step.name,
)

Expand Down
5 changes: 2 additions & 3 deletions src/ert/config/parsing/observations_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,8 +415,7 @@ def _validate_gen_obs_values(
filename = os.path.join(directory, filename)
if not os.path.exists(filename):
raise ObservationConfigError.with_context(
"The following keywords did not"
f" resolve to a valid path:\n {key}",
f"The following keywords did not resolve to a valid path:\n {key}",
value,
)
setattr(output, str(key).lower(), filename)
Expand Down Expand Up @@ -500,7 +499,7 @@ def _conversion_error(
token: FileContextToken, value: Any, type_name: str
) -> ObservationConfigError:
return ObservationConfigError.with_context(
f"Could not convert {value} to " f'{type_name}. Failed to validate "{value}"',
f'Could not convert {value} to {type_name}. Failed to validate "{value}"',
token,
)

Expand Down
2 changes: 1 addition & 1 deletion src/ert/ensemble_evaluator/_ensemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ async def _evaluate_inner( # pylint: disable=too-many-branches
except Exception as exc:
logger.exception(
(
"Unexpected exception in ensemble: \n" "".join(
"Unexpected exception in ensemble: \n".join(
traceback.format_exception(None, exc, exc.__traceback__)
)
),
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/ertwidgets/models/activerealizationsmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def setValueFromMask(self, mask: Collection[bool | int]) -> None:
def getDefaultValue(self) -> str | None:
if self.show_default:
size = self.ensemble_size
return f"0-{size-1:d}"
return f"0-{size - 1:d}"
return None

def getActiveRealizationsMask(self) -> list[bool]:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/experiment_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def run_experiment(self) -> None:
msg_box.setIcon(QMessageBox.Warning)
msg_box.setText("ERT could not delete the existing runpath")
msg_box.setInformativeText(
f"{e}\n\n" "Continue without deleting the runpath?"
f"{e}\n\nContinue without deleting the runpath?"
)
msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msg_box.setDefaultButton(QMessageBox.No)
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/simulation/view/progress_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def repaint_components(self) -> None:

for state, label in self._legend_map_text.items():
label.setText(
f" {state} ({self._status.get(state,0)}/{self._realization_count})"
f" {state} ({self._status.get(state, 0)}/{self._realization_count})"
)

def stop_waiting_progress_bar(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/suggestor/_suggestor_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def _expanded_text(self) -> str:
first = True
for loc in self._locations:
if first:
location_paragraphs += f'<p>{self._color_bold("location:")}{loc}</p>'
location_paragraphs += f"<p>{self._color_bold('location:')}{loc}</p>"
first = False
else:
location_paragraphs += f"<p>{loc}</p>"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,20 @@ def __init__(self) -> None:
self.addLineEdit(
"title",
"Title",
f'The title of the plot. {_label_msg("title")}',
f"The title of the plot. {_label_msg('title')}",
placeholder="Title",
)
self.addSpacing()
self.addLineEdit(
"x_label",
"x-label",
f'The label of the x-axis. {_label_msg("label")}',
f"The label of the x-axis. {_label_msg('label')}",
placeholder="x-label",
)
self.addLineEdit(
"y_label",
"y-label",
f'The label of the y-axis. {_label_msg("label")}',
f"The label of the y-axis. {_label_msg('label')}",
placeholder="y-label",
)
self.addSpacing()
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/tools/plot/plot_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def __init__(self, config_file: str, parent: QWidget | None):

self._data_type_keys_widget.selectDefault()

logger.info(f"PlotWindow __init__ done. time={time.perf_counter() -t}")
logger.info(f"PlotWindow __init__ done. time={time.perf_counter() - t}")

@Slot(int)
def currentTabChanged(self, index: int) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/ert/gui/tools/workflows/run_workflow_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def workflowFinishedWithFail(self) -> None:
(wfname, info) for wfname, info in report.items() if not info["completed"]
]

title_text = f"Workflow{'s' if len(failing_workflows) > 1 else ''} failed"
title_text = f"Workflow{'s' if len(failing_workflows) > 1 else ''} failed"
content_text = "\n\n".join(
[
f"{wfname} failed: \n {info['stderr'].strip()}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _get_rangestrings(
) -> tuple[str, str]:
if not args:
return (
f"0-{number_of_realizations-1}",
f"0-{number_of_realizations - 1}",
"0-0", # weird default behavior, kept for backwards compatability
)
if "|" not in args:
Expand Down
6 changes: 3 additions & 3 deletions src/ert/plugins/hook_specifications/forward_model_steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@

@no_type_check
@hook_specification
def installable_forward_model_steps() -> (
PluginResponse[list[type[ForwardModelStepPlugin]]]
):
def installable_forward_model_steps() -> PluginResponse[
list[type[ForwardModelStepPlugin]]
]:
"""
:return: List of forward model step plugins in the form of subclasses of the
ForwardModelStepPlugin class
Expand Down
2 changes: 1 addition & 1 deletion src/ert/plugins/plugin_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def _evaluate_config_hook(hook: pluggy.HookCaller, config_name: str) -> str | No
logger.debug(
f"Got {config_name} config path from "
f"{response.plugin_metadata.plugin_name} "
f"({response.plugin_metadata.function_name,})"
f"({(response.plugin_metadata.function_name,)})"
)
return response.data

Expand Down
7 changes: 4 additions & 3 deletions src/ert/plugins/plugin_response.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar("T")


@dataclass
class PluginMetadata:
def __init__(self, plugin_name: str, function_name: str) -> None:
self.plugin_name = plugin_name
self.function_name = function_name
plugin_name: str
function_name: str


class PluginResponse(Generic[T]):
Expand Down
3 changes: 1 addition & 2 deletions src/ert/resources/shell_scripts/copy_directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def copy_directory(src_path: str, target_path: str) -> None:
) from err
else:
raise OSError(
f"Input argument: '{src_path}' "
"does not correspond to an existing directory"
f"Input argument: '{src_path}' does not correspond to an existing directory"
)


Expand Down
2 changes: 1 addition & 1 deletion src/ert/scheduler/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ async def run(
if attempt < max_submit - 1:
message = (
f"Realization {self.iens} failed, "
f"resubmitting for attempt {attempt+2} of {max_submit}"
f"resubmitting for attempt {attempt + 2} of {max_submit}"
)
logger.warning(message)
self.returncode = asyncio.Future()
Expand Down
2 changes: 1 addition & 1 deletion src/ert/scheduler/openpbs_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def _build_resource_string(
if num_cpu > 1:
cpu_resources += [f"ncpus={num_cpu}"]
if realization_memory > 0:
cpu_resources += [f"mem={realization_memory // 1024**2 }mb"]
cpu_resources += [f"mem={realization_memory // 1024**2}mb"]
if cpu_resources:
resource_specifiers.append(":".join(cpu_resources))

Expand Down
12 changes: 6 additions & 6 deletions src/ert/storage/local_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,12 +479,12 @@ def _migrate(self, version: int) -> None:
Detected outdated storage (blockfs), which is no longer supported
by ERT. Its contents are copied to:
{self.path / '_ert_block_storage_backup'}
{self.path / "_ert_block_storage_backup"}
In order to migrate this storage, do the following:
(1) with ert version <= 10.3.*, open up the same ert config with:
ENSPATH={self.path / '_ert_block_storage_backup'}
ENSPATH={self.path / "_ert_block_storage_backup"}
(2) with current ert version, open up the same storage again.
The contents of the storage should now be up-to-date, and you may
Expand All @@ -503,7 +503,7 @@ def _migrate(self, version: int) -> None:
enumerate([to2, to3, to4, to5, to6, to7, to8, to9], start=1)
)
for from_version, migration in migrations[version - 1 :]:
print(f"* Updating storage to version: {from_version+1}")
print(f"* Updating storage to version: {from_version + 1}")
migration.migrate(self.path)
self._add_migration_information(
from_version, from_version + 1, migration.info
Expand Down Expand Up @@ -639,9 +639,9 @@ def local_storage_get_ert_config() -> ErtConfig:
The ErtConfig instance.
"""

assert (
_migration_ert_config is not None
), "Use 'local_storage_set_ert_config' before retrieving the config"
assert _migration_ert_config is not None, (
"Use 'local_storage_set_ert_config' before retrieving the config"
)
return _migration_ert_config


Expand Down
6 changes: 3 additions & 3 deletions src/ert/storage/migration/to7.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ def _migrate_response_datasets(path: Path) -> None:
with open(responses_file, encoding="utf-8") as f:
responses_obj = json.load(f)

assert (
responses_obj is not None
), f"Failed to load responses.json @ {responses_file}"
assert responses_obj is not None, (
f"Failed to load responses.json @ {responses_file}"
)

gendata_keys = responses_obj.get("gen_data", {}).get("keys", [])

Expand Down
2 changes: 1 addition & 1 deletion src/ert/validation/rangestring.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def store_range(begin: int, end: int) -> None:
if end - begin == 1:
ranges.append(f"{begin}")
else:
ranges.append(f"{begin}-{end-1}")
ranges.append(f"{begin}-{end - 1}")

start: int | None = None
for i, is_active in enumerate(mask):
Expand Down
3 changes: 1 addition & 2 deletions src/everest/config/control_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ def _all_or_no_index(variables: ControlVariable) -> ControlVariable:

if len({getattr(variable, "index", None) is None for variable in variables}) != 1:
raise ValueError(
"Index should be given either for all of the variables or for none"
" of them"
"Index should be given either for all of the variables or for none of them"
)
return variables

Expand Down
6 changes: 2 additions & 4 deletions src/everest/config/everest_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -801,13 +801,11 @@ def load_file_with_argparser(
parser.error(f"File not found: {config_path}")
except YAMLError as e:
parser.error(
f"The config file: <{config_path}> contains"
f" invalid YAML syntax: {e!s}"
f"The config file: <{config_path}> contains invalid YAML syntax: {e!s}"
)
except EverestValidationError as e:
parser.error(
f"Loading config file <{config_path}> failed with:\n"
f"{format_errors(e)}"
f"Loading config file <{config_path}> failed with:\n{format_errors(e)}"
)

def dump(self, fname: str | None = None) -> str | None:
Expand Down
5 changes: 2 additions & 3 deletions src/everest/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,15 +194,14 @@ def check_for_errors(

if config.batches == []:
export_errors.append(
"No batches selected for export. "
"Only optimization data will be exported."
"No batches selected for export. Only optimization data will be exported."
)
return export_errors, False

if not data_file_path:
export_ecl = False
export_errors.append(
"No data file found in config." "Only optimization data will be exported."
"No data file found in config.Only optimization data will be exported."
)

# If no user defined keywords are present it is no longer possible to check
Expand Down
2 changes: 1 addition & 1 deletion src/everest/jobs/well_tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def well_set(well_data_file, new_entry_file, output_file):
new_entry = everest.jobs.io.load_data(new_entry_file)

if len(new_entry) != 1:
err_msg = "Expected there to be exactly one new entry " "in {nef}, was {ne}"
err_msg = "Expected there to be exactly one new entry in {nef}, was {ne}"
raise ValueError(err_msg.format(nef=new_entry_file, ne=len(new_entry)))

entry_key = next(iter(new_entry.keys()))
Expand Down
2 changes: 1 addition & 1 deletion src/everest/simulator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
JOB_FAILURE = "Failed"


DEFAULT_DATA_SUMMARY_KEYS = ("YEAR", "YEARS" "TCPU", "TCPUDAY", "MONTH", "DAY")
DEFAULT_DATA_SUMMARY_KEYS = ("YEAR", "YEARSTCPU", "TCPUDAY", "MONTH", "DAY")


DEFAULT_FIELD_SUMMARY_KEYS = (
Expand Down
2 changes: 1 addition & 1 deletion test-data/ert/poly_example/Plot_correlations.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"plt.xlabel(\"Response\")\n",
"plt.ylabel(\"Parameter\")\n",
"plt.xticks(\n",
" range(coeffs.shape[1]), labels=[f\"Response {i+1}\" for i in range(coeffs.shape[1])]\n",
" range(coeffs.shape[1]), labels=[f\"Response {i + 1}\" for i in range(coeffs.shape[1])]\n",
")\n",
"plt.yticks(range(coeffs.shape[0]), labels=parameter_names)\n",
"\n",
Expand Down
2 changes: 1 addition & 1 deletion test-data/ert/snake_oil/forward_models/snake_oil_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
def writeDiff(filename, vector1, vector2):
with open(filename, "w", encoding="utf-8") as f:
for node1, node2 in zip(vector1, vector2, strict=False):
f.write(f"{node1-node2:f}\n")
f.write(f"{node1 - node2:f}\n")


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions tests/ert/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ def log_check():
yield
logger_after = logging.getLogger()
level_after = logger_after.getEffectiveLevel()
assert (
level_after == logging.WARNING
), f"Detected differences in log environment: Changed to {level_after}"
assert level_after == logging.WARNING, (
f"Detected differences in log environment: Changed to {level_after}"
)


@pytest.fixture(scope="session", autouse=True)
Expand Down
Loading

0 comments on commit 65f34db

Please sign in to comment.