Skip to content

Commit 27a6a0a

Browse files
committed
Add type annotations to forward_models
1 parent 5c8c309 commit 27a6a0a

17 files changed

Lines changed: 360 additions & 203 deletions

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ ignore = [
132132
]
133133

134134
[tool.ruff.lint.per-file-ignores]
135-
"!*/semeio/fmudesign/**.py" = ["ANN"]
135+
"!*/semeio/{fmudesign,forward_models}/**.py" = ["ANN"]
136136

137137
[tool.ruff.lint.pylint]
138138
max-args = 20

src/semeio/forward_models/__init__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414

1515
class Design2Params(ForwardModelStepPlugin):
16-
def __init__(self):
16+
def __init__(self) -> None:
1717
super().__init__(
1818
name="DESIGN2PARAMS",
1919
command=[
@@ -44,7 +44,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
4444

4545

4646
class DesignKW(ForwardModelStepPlugin):
47-
def __init__(self):
47+
def __init__(self) -> None:
4848
super().__init__(
4949
name="DESIGN_KW",
5050
command=[
@@ -86,7 +86,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
8686

8787

8888
class GenDataRFT(ForwardModelStepPlugin):
89-
def __init__(self):
89+
def __init__(self) -> None:
9090
super().__init__(
9191
name="GENDATA_RFT",
9292
command=[
@@ -160,7 +160,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
160160

161161

162162
class OTS(ForwardModelStepPlugin):
163-
def __init__(self):
163+
def __init__(self) -> None:
164164
super().__init__(
165165
name="OTS",
166166
command=["overburden_timeshift", "-c", "<CONFIG>"],
@@ -180,7 +180,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
180180

181181

182182
class Pyscal(ForwardModelStepPlugin):
183-
def __init__(self):
183+
def __init__(self) -> None:
184184
super().__init__(
185185
name="PYSCAL",
186186
command=[
@@ -223,7 +223,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
223223

224224

225225
class InsertNoSim(ForwardModelStepPlugin):
226-
def __init__(self):
226+
def __init__(self) -> None:
227227
super().__init__(
228228
name="INSERT_NOSIM",
229229
command=[
@@ -255,7 +255,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
255255

256256

257257
class RemoveNoSim(ForwardModelStepPlugin):
258-
def __init__(self):
258+
def __init__(self) -> None:
259259
super().__init__(
260260
name="REMOVE_NOSIM",
261261
command=["sed", "-i", "", "/^NOSIM/d", "<ECLBASE>.DATA"]
@@ -277,7 +277,7 @@ def documentation() -> ForwardModelStepDocumentation | None:
277277

278278

279279
class ReplaceString(ForwardModelStepPlugin):
280-
def __init__(self):
280+
def __init__(self) -> None:
281281
super().__init__(
282282
name="REPLACE_STRING",
283283
command=["replace_string", "-o", "<FROM>", "-n", "<TO>", "-f", "<FILE>"],

src/semeio/forward_models/design2params/design2params.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import logging
22
import warnings
3+
from collections.abc import Sequence
34
from pathlib import Path
5+
from typing import Literal
46

57
import numpy as np
68
import pandas as pd
@@ -24,13 +26,13 @@
2426

2527

2628
def run(
27-
realization,
28-
xlsfilename,
29-
designsheetname="DesignSheet01",
30-
defaultssheetname="DefaultValues",
31-
parametersfilename="parameters.txt",
32-
log_level=None,
33-
):
29+
realization: int,
30+
xlsfilename: str,
31+
designsheetname: str = "DesignSheet01",
32+
defaultssheetname: str = "DefaultValues",
33+
parametersfilename: str = "parameters.txt",
34+
log_level: int | str | None = None,
35+
) -> None:
3436
"""
3537
Reads out all file content from different files and create dataframes
3638
"""
@@ -68,8 +70,12 @@ def run(
6870

6971

7072
def _complete_parameters_file(
71-
realization, parameters, parametersfilename, design_matrix_sheet, default_sheet
72-
):
73+
realization: int,
74+
parameters: pd.DataFrame,
75+
parametersfilename: str,
76+
design_matrix_sheet: pd.DataFrame,
77+
default_sheet: pd.DataFrame,
78+
) -> None:
7379
"""
7480
Pick key / values from chosen realization in design matrix
7581
Append those key / values if not present into parameters.txt
@@ -184,7 +190,13 @@ def _complete_parameters_file(
184190
)
185191

186192

187-
def _read_excel(file_name, sheet_name, header=0, usecols=None, engine=None):
193+
def _read_excel(
194+
file_name: str,
195+
sheet_name: str,
196+
header: int | Sequence[int] | None = 0,
197+
usecols: list[int] | None = None,
198+
engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb", "calamine"] | None = None,
199+
) -> pd.DataFrame:
188200
"""
189201
Make dataframe from excel file
190202
:return: Dataframe
@@ -219,7 +231,7 @@ def _read_excel(file_name, sheet_name, header=0, usecols=None, engine=None):
219231
return dframe.dropna(axis=1, how="all")
220232

221233

222-
def _validate_design_matrix_header(design_matrix):
234+
def _validate_design_matrix_header(design_matrix: pd.DataFrame) -> None:
223235
"""
224236
Validate header in user inputted design matrix
225237
:raises: ValueError if design matrix contains empty headers
@@ -239,7 +251,7 @@ def _validate_design_matrix_header(design_matrix):
239251
raise ValueError(f"Column headers not present in column {column_indexes}")
240252

241253

242-
def _invalid_design_realizations(design_matrix):
254+
def _invalid_design_realizations(design_matrix: pd.DataFrame) -> set[int]:
243255
"""
244256
Build a set of realization indices where something is wrong,
245257
f.ex empty cells
@@ -263,7 +275,7 @@ def _invalid_design_realizations(design_matrix):
263275

264276
# Look for initial or trailing whitespace in column headers. This
265277
# is disallowed as it can create user confusion and has no use-case.
266-
for col_header in design_matrix:
278+
for col_header in design_matrix.columns:
267279
if col_header != col_header.strip():
268280
raise SystemExit(
269281
f'Column header "{col_header}" contains initial or trailing whitespace.'
@@ -292,7 +304,7 @@ def _invalid_design_realizations(design_matrix):
292304
return {cell_coord[0] for cell_coord in empty_cell_coords}
293305

294306

295-
def _read_defaultssheet(xlsfilename, defaultssheetname):
307+
def _read_defaultssheet(xlsfilename: str, defaultssheetname: str) -> pd.DataFrame:
296308
"""
297309
Construct a dataframe of keys and values to be used as defaults from the
298310
first two columns in a spreadsheet.
@@ -304,7 +316,10 @@ def _read_defaultssheet(xlsfilename, defaultssheetname):
304316
"""
305317
if defaultssheetname:
306318
default_df = _read_excel(
307-
xlsfilename, defaultssheetname, usecols=[0, 1], header=None
319+
xlsfilename,
320+
defaultssheetname,
321+
usecols=[0, 1],
322+
header=None,
308323
)
309324
if default_df.empty:
310325
logger.info("Empty defaultssheet provided")

src/semeio/forward_models/design_kw/design_kw.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import logging
22
import re
33
import shlex
4-
from collections.abc import Mapping
4+
from collections.abc import Iterable, Mapping, Sequence
5+
from re import Match
6+
from typing import Any
57

68
from ert import ForwardModelStepWarning
79

@@ -79,28 +81,28 @@ def find_matching_errors(
7981
return errors
8082

8183

82-
def is_perl(file_name, template):
84+
def is_perl(file_name: str, template: Sequence[str]) -> bool:
8385
return file_name.endswith(".pl") or template[0].find("perl") != -1
8486

8587

86-
def is_xml(file_name: str, template: list[str]) -> bool:
88+
def is_xml(file_name: str, template: Sequence[str]) -> bool:
8789
return file_name.endswith(".xml") or template[0].find("?xml") != -1
8890

8991

90-
def unmatched_templates(line):
92+
def unmatched_templates(line: str) -> list[str]:
9193
bracketpattern = re.compile("<.+?>")
9294
if bracketpattern.search(line):
9395
return bracketpattern.findall(line)
9496
return []
9597

9698

97-
def is_comment(line):
99+
def is_comment(line: str) -> Match[str] | None:
98100
ecl_comment_pattern = re.compile("^--")
99101
std_comment_pattern = re.compile("^#")
100102
return ecl_comment_pattern.search(line) or std_comment_pattern.search(line)
101103

102104

103-
def extract_key_value(parameters: list[str]) -> dict[str, str]:
105+
def extract_key_value(parameters: Iterable[str]) -> dict[str, Any]:
104106
"""Parses a list of strings, looking for key-value pairs pr. line
105107
separated by whitespace, into a dictionary.
106108
@@ -142,7 +144,9 @@ def extract_key_value(parameters: list[str]) -> dict[str, str]:
142144
return res
143145

144146

145-
def rm_genkw_prefix(paramsdict, ignoreprefixes="LOG10_"):
147+
def rm_genkw_prefix(
148+
paramsdict: Mapping[str, Any], ignoreprefixes: str | Iterable[str] | None = "LOG10_"
149+
) -> dict[str, Any]:
146150
"""Strip prefixes from keys in a dictionary.
147151
148152
Prefix is any string before a colon. No colon means no prefix.

0 commit comments

Comments
 (0)