Skip to content

Commit a84e0ac

Browse files
committed
Enable passing the base path to Problem.from_yaml
When passing the problem configuration as `dict` to `Problem.from_yaml`, one should be able to specify the base path for resolving relative paths. See PEtab-dev#324. Closes PEtab-dev#324
1 parent 0b77d7f commit a84e0ac

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

petab/v1/problem.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -251,21 +251,28 @@ def from_files(
251251
)
252252

253253
@staticmethod
254-
def from_yaml(yaml_config: dict | Path | str) -> Problem:
254+
def from_yaml(
255+
yaml_config: dict | Path | str, base_path: str | Path = None
256+
) -> Problem:
255257
"""
256258
Factory method to load model and tables as specified by YAML file.
257259
258260
Arguments:
259261
yaml_config: PEtab configuration as dictionary or YAML file name
262+
base_path: Base directory or URL to resolve relative paths
260263
"""
261264
if isinstance(yaml_config, Path):
262265
yaml_config = str(yaml_config)
263266

264-
get_path = lambda filename: filename # noqa: E731
265267
if isinstance(yaml_config, str):
266-
path_prefix = get_path_prefix(yaml_config)
268+
if base_path is None:
269+
base_path = get_path_prefix(yaml_config)
267270
yaml_config = yaml.load_yaml(yaml_config)
268-
get_path = lambda filename: f"{path_prefix}/{filename}" # noqa: E731
271+
272+
def get_path(filename):
273+
if base_path is None:
274+
return filename
275+
return f"{base_path}/{filename}"
269276

270277
if yaml.is_composite_problem(yaml_config):
271278
raise ValueError(

tests/v1/test_petab.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -862,11 +862,16 @@ def test_problem_from_yaml_v1_multiple_files():
862862
observables_df, Path(tmpdir, f"observables{i}.tsv")
863863
)
864864

865-
petab_problem = petab.Problem.from_yaml(yaml_path)
865+
petab_problem1 = petab.Problem.from_yaml(yaml_path)
866866

867-
assert petab_problem.measurement_df.shape[0] == 2
868-
assert petab_problem.observable_df.shape[0] == 2
869-
assert petab_problem.condition_df.shape[0] == 2
867+
# test that we can load the problem from a dict with a custom base path
868+
yaml_config = petab.v1.load_yaml(yaml_path)
869+
petab_problem2 = petab.Problem.from_yaml(yaml_config, base_path=tmpdir)
870+
871+
for petab_problem in (petab_problem1, petab_problem2):
872+
assert petab_problem.measurement_df.shape[0] == 2
873+
assert petab_problem.observable_df.shape[0] == 2
874+
assert petab_problem.condition_df.shape[0] == 2
870875

871876

872877
def test_get_required_parameters_for_parameter_table(petab_problem):

0 commit comments

Comments
 (0)