Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions changelog.d/+v2-petab1to2-experiment-ids.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
`petab1to2`: Different combinations of pre-equilibration and simulation
conditions no longer get the same experiment ID (e.g., pre-equilibration `a_`
with simulation `b`, and pre-equilibration `a` with simulation `_b`), and
experiment IDs no longer clash with condition, observable, or parameter IDs
([#636](https://github.com/PEtab-dev/libpetab-python/pull/636))
69 changes: 49 additions & 20 deletions petab/v2/petab1to2.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,33 +216,61 @@ def petab_files_1to2(
# records for the experiment table to be created
experiments = []

condition_df = petab_problem.condition_df
# conditions with changes
nonempty_conditions = set(
condition_df.index[condition_df.notna().any(axis=1)]
)

def v2_condition_id(cond_id: str) -> str:
"""Get the condition ID to use in the v2 experiment table.

Conditions without any changes (all-NaN rows) are not included in the
v2 condition table. Periods applying such a condition get an empty
condition ID ("use the model as is").
"""
if petab_problem.condition_df.loc[cond_id].notna().any():
if cond_id in nonempty_conditions:
return cond_id
if cond_id not in condition_df.index:
raise KeyError(cond_id)
return ""

# (simulation condition ID, pre-equilibration condition ID)
# -> experiment ID
experiment_ids = {}
# IDs that must not be used for new experiments
used_ids = (
set(condition_df.index)
| set(petab_problem.observable_df.index)
| set(petab_problem.parameter_df.index)
)

def create_experiment_id(sim_cond_id: str, preeq_cond_id: str) -> str:
if not sim_cond_id and not preeq_cond_id:
return ""
if not preeq_cond_id and not v2_condition_id(sim_cond_id):
"""Get the ID of the experiment for the given condition pair.

Returns the same ID for the same pair, unique IDs for different
pairs, or ``""`` if no experiment is needed."""
if pd.isna(preeq_cond_id):
preeq_cond_id = ""
key = (sim_cond_id, preeq_cond_id)
if (exp_id := experiment_ids.get(key)) is not None:
return exp_id

if (not sim_cond_id and not preeq_cond_id) or (
not preeq_cond_id and not v2_condition_id(sim_cond_id)
):
# without pre-equilibration and without any changes, there is
# nothing to be described by an experiment
return ""

if preeq_cond_id:
preeq_cond_id = f"{preeq_cond_id}_"
exp_id = f"experiment__{preeq_cond_id}__{sim_cond_id}"
if exp_id in experiments:
i = 1
while f"{exp_id}_{i}" in experiments:
exp_id = ""
else:
preeq_part = f"{preeq_cond_id}_" if preeq_cond_id else ""
base_id = exp_id = f"experiment__{preeq_part}__{sim_cond_id}"
i = 0
while exp_id in used_ids:
i += 1
exp_id = f"{exp_id}_{i}"
exp_id = f"{base_id}_{i}"
used_ids.add(exp_id)
experiment_ids[key] = exp_id
return exp_id

measured_experiments = (
Expand Down Expand Up @@ -330,13 +358,14 @@ def create_experiment_id(sim_cond_id: str, preeq_cond_id: str) -> str:
measurement_df.insert(
0,
v2.C.EXPERIMENT_ID,
measurement_df.apply(
lambda row: create_experiment_id(
row[v1.C.SIMULATION_CONDITION_ID],
row.get(v1.C.PREEQUILIBRATION_CONDITION_ID, ""),
),
axis=1,
),
[
create_experiment_id(sim_cond_id, preeq_cond_id)
for sim_cond_id, preeq_cond_id in zip(
measurement_df[v1.C.SIMULATION_CONDITION_ID],
measurement_df[v1.C.PREEQUILIBRATION_CONDITION_ID],
strict=True,
)
],
)
del measurement_df[v1.C.SIMULATION_CONDITION_ID]
del measurement_df[v1.C.PREEQUILIBRATION_CONDITION_ID]
Expand Down
119 changes: 119 additions & 0 deletions tests/v2/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -1182,6 +1182,125 @@ def test_petab1to2_validate(tmp_path):
assert len(problem.measurements) == 2


def test_petab1to2_experiment_id_clash(tmp_path):
"""Different condition pairs whose experiment IDs would be equal
get different experiments."""
measurements = [
{
v1.C.OBSERVABLE_ID: "obs_B",
v1.C.PREEQUILIBRATION_CONDITION_ID: preeq,
v1.C.SIMULATION_CONDITION_ID: sim,
v1.C.TIME: 1.0,
v1.C.MEASUREMENT: measurement,
}
# both `experiment__a____b`
for preeq, sim, measurement in (
("a_", "b", 0.1),
("a", "_b", 0.2),
("a_", "b", 0.3),
)
]
problem = v1.Problem(
model=SbmlModel.from_antimony(
"r1: A -> B; k1 * A; A = 1; B = 0; k1 = 0.5"
),
condition_df=v1.get_condition_df(
pd.DataFrame(
{
v1.C.CONDITION_ID: ["a", "a_", "b", "_b"],
"A": [1.0, 2.0, 3.0, 4.0],
}
)
),
observable_df=v1.get_observable_df(
pd.DataFrame(
[
{
v1.C.OBSERVABLE_ID: "obs_B",
v1.C.OBSERVABLE_FORMULA: "B",
v1.C.NOISE_FORMULA: "0.1",
}
]
)
),
measurement_df=v1.get_measurement_df(pd.DataFrame(measurements)),
parameter_df=v1.get_parameter_df(pd.DataFrame([_K1])),
)
yaml_file = problem.to_files_generic(tmp_path)

problem = petab1to2(tmp_path / yaml_file)

experiments = {
e.id: [(p.time, p.condition_ids) for p in e.sorted_periods]
for e in problem.experiments
}
assert experiments == {
"experiment__a____b": [(-np.inf, ["a"]), (0, ["_b"])],
"experiment__a____b_1": [(-np.inf, ["a_"]), (0, ["b"])],
}
assert [
(m.experiment_id, m.measurement) for m in problem.measurements
] == [
("experiment__a____b_1", 0.1),
("experiment__a____b", 0.2),
("experiment__a____b_1", 0.3),
]


def test_petab1to2_experiment_id_avoids_existing_ids(tmp_path):
"""Generated experiment IDs don't clash with condition, observable,
or parameter IDs."""
problem = v1.Problem(
model=SbmlModel.from_antimony(
"r1: A -> B; k1 * A; A = 1; B = 0; k1 = 0.5"
),
condition_df=v1.get_condition_df(
pd.DataFrame(
{
v1.C.CONDITION_ID: ["c", "experiment____c"],
"A": [1.0, 2.0],
}
)
),
observable_df=v1.get_observable_df(
pd.DataFrame(
[
{
v1.C.OBSERVABLE_ID: "experiment____c_1",
v1.C.OBSERVABLE_FORMULA: "B",
v1.C.NOISE_FORMULA: "experiment____c_2",
}
]
)
),
measurement_df=v1.get_measurement_df(
pd.DataFrame(
[
{
v1.C.OBSERVABLE_ID: "experiment____c_1",
v1.C.SIMULATION_CONDITION_ID: "c",
v1.C.TIME: 1.0,
v1.C.MEASUREMENT: 0.1,
}
]
)
),
parameter_df=v1.get_parameter_df(
pd.DataFrame(
[_K1, {**_K1, v1.C.PARAMETER_ID: "experiment____c_2"}]
)
),
)
yaml_file = problem.to_files_generic(tmp_path)

problem = petab1to2(tmp_path / yaml_file)

assert [e.id for e in problem.experiments] == ["experiment____c_3"]
assert [m.experiment_id for m in problem.measurements] == [
"experiment____c_3"
]


@pytest.mark.parametrize("clash", [False, True])
def test_petab1to2_existing_experiment_id_column(tmp_path, clash):
"""Test that a pre-existing `experimentId` column is renamed
Expand Down
Loading