Skip to content

Commit

Permalink
Enable passing the base path to Problem.from_yaml
Browse files Browse the repository at this point in the history
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
  • Loading branch information
dweindl committed Dec 3, 2024
1 parent 0b77d7f commit a84e0ac
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
15 changes: 11 additions & 4 deletions petab/v1/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,21 +251,28 @@ def from_files(
)

@staticmethod
def from_yaml(yaml_config: dict | Path | str) -> Problem:
def from_yaml(
yaml_config: dict | Path | str, base_path: str | Path = None
) -> Problem:
"""
Factory method to load model and tables as specified by YAML file.
Arguments:
yaml_config: PEtab configuration as dictionary or YAML file name
base_path: Base directory or URL to resolve relative paths
"""
if isinstance(yaml_config, Path):
yaml_config = str(yaml_config)

get_path = lambda filename: filename # noqa: E731
if isinstance(yaml_config, str):
path_prefix = get_path_prefix(yaml_config)
if base_path is None:
base_path = get_path_prefix(yaml_config)
yaml_config = yaml.load_yaml(yaml_config)
get_path = lambda filename: f"{path_prefix}/{filename}" # noqa: E731

def get_path(filename):
if base_path is None:
return filename
return f"{base_path}/{filename}"

if yaml.is_composite_problem(yaml_config):
raise ValueError(
Expand Down
13 changes: 9 additions & 4 deletions tests/v1/test_petab.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,11 +862,16 @@ def test_problem_from_yaml_v1_multiple_files():
observables_df, Path(tmpdir, f"observables{i}.tsv")
)

petab_problem = petab.Problem.from_yaml(yaml_path)
petab_problem1 = petab.Problem.from_yaml(yaml_path)

assert petab_problem.measurement_df.shape[0] == 2
assert petab_problem.observable_df.shape[0] == 2
assert petab_problem.condition_df.shape[0] == 2
# test that we can load the problem from a dict with a custom base path
yaml_config = petab.v1.load_yaml(yaml_path)
petab_problem2 = petab.Problem.from_yaml(yaml_config, base_path=tmpdir)

for petab_problem in (petab_problem1, petab_problem2):
assert petab_problem.measurement_df.shape[0] == 2
assert petab_problem.observable_df.shape[0] == 2
assert petab_problem.condition_df.shape[0] == 2


def test_get_required_parameters_for_parameter_table(petab_problem):
Expand Down

0 comments on commit a84e0ac

Please sign in to comment.