Skip to content

Commit aa8cd78

Browse files
authored
maint: fix code style, check on gha (#252)
Follow-up to #251 * Manual changes for compatibility with selected ruff rules * run pre-commit hooks on GHA instead of flake8 * run tests on python3.12
1 parent b7d6130 commit aa8cd78

24 files changed

+117
-88
lines changed

.github/workflows/ci_tests.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ jobs:
1111
strategy:
1212
matrix:
1313
platform: [windows-latest, macos-latest, ubuntu-latest]
14-
python-version: ["3.9", "3.11"]
14+
python-version: ["3.9", "3.12"]
1515
runs-on: ${{ matrix.platform }}
1616

1717
steps:

doc/conf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
# -- Project information -----------------------------------------------------
2121

2222
project = "libpetab-python"
23-
copyright = "2018-2023, the PEtab developers"
23+
copyright = "2018-2024, the PEtab developers"
2424
author = "PEtab developers"
2525

2626
# The full version, including alpha/beta/rc tags
@@ -29,7 +29,7 @@
2929
# -- Custom pre-build --------------------------------------------------------
3030

3131

32-
subprocess.run(["python", "md2rst.py"])
32+
subprocess.run([sys.executable, "md2rst.py"]) # noqa: S603
3333

3434
# -- General configuration ---------------------------------------------------
3535

petab/calculate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ def calculate_llh_for_table(
336336
noise_formulas = get_symbolic_noise_formulas(observable_df)
337337

338338
# iterate over measurements, find corresponding simulations
339-
for irow, row in measurement_df.iterrows():
339+
for _, row in measurement_df.iterrows():
340340
measurement = row[MEASUREMENT]
341341

342342
# look up in simulation df

petab/conditions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def get_condition_df(
4747
except KeyError:
4848
raise KeyError(
4949
f"Condition table missing mandatory field {CONDITION_ID}."
50-
)
50+
) from None
5151

5252
return condition_file
5353

petab/core.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,8 @@ def get_visualization_df(
102102
except pd.errors.EmptyDataError:
103103
warn(
104104
"Visualization table is empty. Defaults will be used. "
105-
"Refer to the documentation for details."
105+
"Refer to the documentation for details.",
106+
stacklevel=2,
106107
)
107108
vis_spec = pd.DataFrame()
108109
return vis_spec
@@ -226,9 +227,9 @@ def get_flattened_id_mappings(
226227

227228
mappings[OBSERVABLE_ID][observable_replacement_id] = observable_id
228229

229-
for field, hyperparameter_type, target in [
230-
(NOISE_PARAMETERS, "noiseParameter", NOISE_FORMULA),
231-
(OBSERVABLE_PARAMETERS, "observableParameter", OBSERVABLE_FORMULA),
230+
for field, hyperparameter_type in [
231+
(NOISE_PARAMETERS, "noiseParameter"),
232+
(OBSERVABLE_PARAMETERS, "observableParameter"),
232233
]:
233234
if field in measurements:
234235
mappings[field][
@@ -432,11 +433,11 @@ def create_combine_archive(
432433
# other SWIG interfaces
433434
try:
434435
import libcombine
435-
except ImportError:
436+
except ImportError as err:
436437
raise ImportError(
437438
"To use PEtab's COMBINE functionality, libcombine "
438439
"(python-libcombine) must be installed."
439-
)
440+
) from err
440441

441442
def _add_file_metadata(location: str, description: str = ""):
442443
"""Add metadata to the added file"""

petab/measurements.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ def assert_overrides_match_parameter_count(
321321
f"Mismatch of noise parameter overrides in:\n{row}\n"
322322
f"Expected {expected} but got {len(replacements)}"
323323
)
324-
except KeyError:
324+
except KeyError as err:
325325
# no overrides defined, but a numerical sigma can be provided
326326
# anyways
327327
if len(replacements) != 1 or not isinstance(
@@ -332,7 +332,7 @@ def assert_overrides_match_parameter_count(
332332
f"for observable {row[OBSERVABLE_ID]}, but parameter ID "
333333
"or multiple overrides were specified in the "
334334
"noiseParameters column."
335-
)
335+
) from err
336336

337337

338338
def measurement_is_at_steady_state(time: float) -> bool:

petab/models/model.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
class Model(abc.ABC):
1010
"""Base class for wrappers for any PEtab-supported model type"""
1111

12+
@abc.abstractmethod
1213
def __init__(self):
1314
...
1415

petab/observables.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def get_observable_df(
5555
except KeyError:
5656
raise KeyError(
5757
f"Observable table missing mandatory field {OBSERVABLE_ID}."
58-
)
58+
) from None
5959

6060
return observable_file
6161

petab/parameters.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,8 @@ def get_priors_from_df(
447447
Arguments:
448448
parameter_df: PEtab parameter table
449449
mode: ``'initialization'`` or ``'objective'``
450-
parameter_ids: A sequence of parameter IDs for which to sample starting points.
450+
parameter_ids: A sequence of parameter IDs for which to sample starting
451+
points.
451452
For subsetting or reordering the parameters.
452453
Defaults to all estimated parameters.
453454
@@ -463,7 +464,8 @@ def get_priors_from_df(
463464
except KeyError as e:
464465
missing_ids = set(parameter_ids) - set(par_to_estimate.index)
465466
raise KeyError(
466-
f"Parameter table does not contain estimated parameter(s) {missing_ids}."
467+
"Parameter table does not contain estimated parameter(s) "
468+
f"{missing_ids}."
467469
) from e
468470

469471
prior_list = []
@@ -567,7 +569,10 @@ def map_scale(
567569
"""
568570
if isinstance(scale_strs, str):
569571
scale_strs = [scale_strs] * len(parameters)
570-
return map(lambda x: scale(x[0], x[1]), zip(parameters, scale_strs))
572+
return (
573+
scale(par_val, scale_str)
574+
for par_val, scale_str in zip(parameters, scale_strs)
575+
)
571576

572577

573578
def map_unscale(
@@ -588,7 +593,10 @@ def map_unscale(
588593
"""
589594
if isinstance(scale_strs, str):
590595
scale_strs = [scale_strs] * len(parameters)
591-
return map(lambda x: unscale(x[0], x[1]), zip(parameters, scale_strs))
596+
return (
597+
unscale(par_val, scale_str)
598+
for par_val, scale_str in zip(parameters, scale_strs)
599+
)
592600

593601

594602
def normalize_parameter_df(parameter_df: pd.DataFrame) -> pd.DataFrame:

petab/problem.py

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import tempfile
66
from math import nan
77
from pathlib import Path, PurePosixPath
8-
from typing import TYPE_CHECKING, Iterable, Optional, Union
8+
from typing import TYPE_CHECKING, Iterable
99
from urllib.parse import unquote, urlparse, urlunparse
1010
from warnings import warn
1111

@@ -78,12 +78,12 @@ def __init__(
7878
mapping_df: pd.DataFrame = None,
7979
extensions_config: dict = None,
8080
):
81-
self.condition_df: Optional[pd.DataFrame] = condition_df
82-
self.measurement_df: Optional[pd.DataFrame] = measurement_df
83-
self.parameter_df: Optional[pd.DataFrame] = parameter_df
84-
self.visualization_df: Optional[pd.DataFrame] = visualization_df
85-
self.observable_df: Optional[pd.DataFrame] = observable_df
86-
self.mapping_df: Optional[pd.DataFrame] = mapping_df
81+
self.condition_df: pd.DataFrame | None = condition_df
82+
self.measurement_df: pd.DataFrame | None = measurement_df
83+
self.parameter_df: pd.DataFrame | None = parameter_df
84+
self.visualization_df: pd.DataFrame | None = visualization_df
85+
self.observable_df: pd.DataFrame | None = observable_df
86+
self.mapping_df: pd.DataFrame | None = mapping_df
8787

8888
if any(
8989
(sbml_model, sbml_document, sbml_reader),
@@ -109,7 +109,7 @@ def __init__(
109109
model_id=model_id,
110110
)
111111

112-
self.model: Optional[Model] = model
112+
self.model: Model | None = model
113113
self.extensions_config = extensions_config or {}
114114

115115
def __getattr__(self, name):
@@ -169,14 +169,12 @@ def __str__(self):
169169

170170
@staticmethod
171171
def from_files(
172-
sbml_file: Union[str, Path] = None,
173-
condition_file: Union[str, Path, Iterable[Union[str, Path]]] = None,
174-
measurement_file: Union[str, Path, Iterable[Union[str, Path]]] = None,
175-
parameter_file: Union[str, Path, Iterable[Union[str, Path]]] = None,
176-
visualization_files: Union[
177-
str, Path, Iterable[Union[str, Path]]
178-
] = None,
179-
observable_files: Union[str, Path, Iterable[Union[str, Path]]] = None,
172+
sbml_file: str | Path = None,
173+
condition_file: str | Path | Iterable[str | Path] = None,
174+
measurement_file: str | Path | Iterable[str | Path] = None,
175+
parameter_file: str | Path | Iterable[str | Path] = None,
176+
visualization_files: str | Path | Iterable[str | Path] = None,
177+
observable_files: str | Path | Iterable[str | Path] = None,
180178
model_id: str = None,
181179
extensions_config: dict = None,
182180
) -> Problem:
@@ -252,7 +250,7 @@ def from_files(
252250
)
253251

254252
@staticmethod
255-
def from_yaml(yaml_config: Union[dict, Path, str]) -> Problem:
253+
def from_yaml(yaml_config: dict | Path | str) -> Problem:
256254
"""
257255
Factory method to load model and tables as specified by YAML file.
258256
@@ -308,7 +306,7 @@ def from_yaml(yaml_config: Union[dict, Path, str]) -> Problem:
308306
f"{format_version.__format_version__}."
309307
)
310308
if yaml_config[FORMAT_VERSION] == "2.0.0":
311-
warn("Support for PEtab2.0 is experimental!")
309+
warn("Support for PEtab2.0 is experimental!", stacklevel=2)
312310

313311
problem0 = yaml_config["problems"][0]
314312

@@ -421,7 +419,7 @@ def from_yaml(yaml_config: Union[dict, Path, str]) -> Problem:
421419
)
422420

423421
@staticmethod
424-
def from_combine(filename: Union[Path, str]) -> Problem:
422+
def from_combine(filename: Path | str) -> Problem:
425423
"""Read PEtab COMBINE archive (http://co.mbine.org/documents/archive).
426424
427425
See also :py:func:`petab.create_combine_archive`.
@@ -444,8 +442,7 @@ def from_combine(filename: Union[Path, str]) -> Problem:
444442

445443
archive = libcombine.CombineArchive()
446444
if archive.initializeFromArchive(str(filename)) is None:
447-
print(f"Invalid Combine Archive: {filename}")
448-
return None
445+
raise ValueError(f"Invalid Combine Archive: {filename}")
449446

450447
with tempfile.TemporaryDirectory() as tmpdirname:
451448
archive.extractTo(tmpdirname)
@@ -458,7 +455,7 @@ def from_combine(filename: Union[Path, str]) -> Problem:
458455

459456
def to_files_generic(
460457
self,
461-
prefix_path: Union[str, Path],
458+
prefix_path: str | Path,
462459
) -> str:
463460
"""Save a PEtab problem to generic file names.
464461
@@ -510,17 +507,17 @@ def to_files_generic(
510507

511508
def to_files(
512509
self,
513-
sbml_file: Union[None, str, Path] = None,
514-
condition_file: Union[None, str, Path] = None,
515-
measurement_file: Union[None, str, Path] = None,
516-
parameter_file: Union[None, str, Path] = None,
517-
visualization_file: Union[None, str, Path] = None,
518-
observable_file: Union[None, str, Path] = None,
519-
yaml_file: Union[None, str, Path] = None,
520-
prefix_path: Union[None, str, Path] = None,
510+
sbml_file: None | str | Path = None,
511+
condition_file: None | str | Path = None,
512+
measurement_file: None | str | Path = None,
513+
parameter_file: None | str | Path = None,
514+
visualization_file: None | str | Path = None,
515+
observable_file: None | str | Path = None,
516+
yaml_file: None | str | Path = None,
517+
prefix_path: None | str | Path = None,
521518
relative_paths: bool = True,
522-
model_file: Union[None, str, Path] = None,
523-
mapping_file: Union[None, str, Path] = None,
519+
model_file: None | str | Path = None,
520+
mapping_file: None | str | Path = None,
524521
) -> None:
525522
"""
526523
Write PEtab tables to files for this problem
@@ -573,7 +570,7 @@ def to_files(
573570
if prefix_path is not None:
574571
prefix_path = Path(prefix_path)
575572

576-
def add_prefix(path0: Union[None, str, Path]) -> str:
573+
def add_prefix(path0: None | str | Path) -> str:
577574
return path0 if path0 is None else str(prefix_path / path0)
578575

579576
model_file = add_prefix(model_file)
@@ -913,7 +910,7 @@ def get_optimization_to_simulation_parameter_mapping(self, **kwargs):
913910
)
914911
)
915912

916-
def create_parameter_df(self, *args, **kwargs):
913+
def create_parameter_df(self, **kwargs):
917914
"""Create a new PEtab parameter table
918915
919916
See :py:func:`create_parameter_df`.
@@ -924,7 +921,6 @@ def create_parameter_df(self, *args, **kwargs):
924921
observable_df=self.observable_df,
925922
measurement_df=self.measurement_df,
926923
mapping_df=self.mapping_df,
927-
*args,
928924
**kwargs,
929925
)
930926

0 commit comments

Comments
 (0)