Skip to content
Draft
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
11 changes: 11 additions & 0 deletions changelog.d/+create-parameter-df-initial-assignments.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
`petab.v1.create_parameter_df(..., include_optional=True)` no longer includes
parameters whose initial assignment is not closed-form (e.g., refers to
model entities, function definitions, or time), since listing them in the
parameter table would replace the initial assignment. Such parameters are
still included if they are referenced in the measurement table or the
condition table, since these references require a parameter table entry;
in this case, the parameter table entry also replaces the initial
assignment. For parameters with closed-form initial assignments
(e.g., `2 * 3`), `create_parameter_df` now uses the value of the assignment
as nominal value, instead of the SBML `value` attribute
([#PR](https://github.com/PEtab-dev/libpetab-python/pull/PR))
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
In the PEtab v1 parameter mapping, a parameter table entry for a model
parameter with a non-numeric initial assignment now replaces that initial
assignment, as for numeric initial assignments and as in PEtab v2.
Previously, such entries were ignored for the model, while condition table
and measurement table references to the same parameter used the parameter
table value. **This changes the mapping, and thus the results, for problems
with such parameter table entries**
([#PR](https://github.com/PEtab-dev/libpetab-python/pull/PR))
47 changes: 47 additions & 0 deletions petab/v1/models/sbml_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import itertools
import math
from collections.abc import Iterable
from pathlib import Path

Expand Down Expand Up @@ -234,6 +235,18 @@ def get_parameter_ids_with_values(self) -> Iterable[tuple[str, float]]:
if p.getId() not in rule_targets
)

def _get_initial_assignment_values(self) -> dict[str, float | None]:
"""Get the targets of all initial assignments and their values.

The value is the result of evaluating the assignment if it is
closed-form (see :func:`_evaluate_closed_math`), otherwise ``None``.
"""
return {
ia.getSymbol(): _evaluate_closed_math(ia.getMath())
for ia in self.sbml_model.getListOfInitialAssignments()
if ia.isSetMath()
}

def has_entity_with_id(self, entity_id) -> bool:
return self.sbml_model.getElementBySId(entity_id) is not None

Expand Down Expand Up @@ -304,6 +317,40 @@ def is_state_variable(self, id_: str) -> bool:
)


# AST node types that make a formula depend on the model or on time
_AST_NON_CLOSED_TYPES = {
libsbml.AST_NAME,
libsbml.AST_NAME_TIME,
libsbml.AST_FUNCTION,
libsbml.AST_FUNCTION_DELAY,
libsbml.AST_FUNCTION_RATE_OF,
}


def _evaluate_closed_math(math_: libsbml.ASTNode) -> float | None:
"""Evaluate a closed-form SBML math expression.

An expression is closed-form if it refers to no model entities, function
definitions, or time, e.g., ``2 * 3`` or ``log(4)``. This is decided
syntactically: ``a - a`` is not closed-form.

:returns: The value of the expression, or ``None`` if it is not
closed-form or cannot be evaluated.
"""
nodes = [math_]
while nodes:
node = nodes.pop()
if node.getType() in _AST_NON_CLOSED_TYPES:
return None
nodes.extend(node.getChild(i) for i in range(node.getNumChildren()))

value = libsbml.SBMLTransforms.evaluateASTNode(math_)
# libsbml returns NaN for anything it cannot evaluate
if math.isnan(value) and not math_.isNaN():
return None
return value


def sympify_sbml(sbml_obj: libsbml.ASTNode | libsbml.SBase) -> sp.Expr:
"""Convert SBML math expression to sympy expression.

Expand Down
59 changes: 53 additions & 6 deletions petab/v1/parameter_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ def get_optimization_to_simulation_parameter_mapping(
by the environment variable with the name of
:py:data:`petab.ENV_NUM_THREADS`.

A parameter table entry for a model parameter that is the target of an
initial assignment replaces that initial assignment, i.e., the parameter
is mapped to the parameter table entry. Model parameters with
non-numeric initial assignments that are not listed in the parameter
table are not included in the mapping; their initial assignments apply.

Parameters:
condition_df, measurement_df, parameter_df, observable_df:
The dataframes in the PEtab format.
Expand Down Expand Up @@ -145,7 +151,9 @@ def get_optimization_to_simulation_parameter_mapping(
measurement_df
)

simulation_parameters = dict(model.get_free_parameter_ids_with_values())
simulation_parameters = _get_model_parameters_for_mapping(
model, parameter_df
)
# Add output parameters that are not already defined in the model
if observable_df is not None:
output_parameters = observables.get_output_parameters(
Expand Down Expand Up @@ -343,9 +351,14 @@ def get_parameter_mapping_for_condition(
model:
The model.
simulation_parameters:
Model simulation parameter IDs mapped to parameter values (output
of ``petab.v1.sbml.get_model_parameters(.., with_values=True)``).
Optional, saves time if precomputed.
Model simulation parameter IDs mapped to parameter values.
Optional, saves time if precomputed. If not provided, these are
the free model parameters with their values
(:meth:`Model.get_free_parameter_ids_with_values`), plus the
model parameters with non-numeric initial assignments that are
listed in the parameter table (see
:func:`get_optimization_to_simulation_parameter_mapping`).
If provided, it must include the latter, too.
warn_unmapped:
If ``True``, log warning regarding unmapped parameters
scaled_parameters:
Expand Down Expand Up @@ -391,9 +404,20 @@ def get_parameter_mapping_for_condition(
)

if simulation_parameters is None:
simulation_parameters = dict(
model.get_free_parameter_ids_with_values()
simulation_parameters = _get_model_parameters_for_mapping(
model, parameter_df
)
elif parameter_df is not None:
# Otherwise, the parameter table entries of these parameters would
# be silently ignored
missing = set(parameter_df.index) - simulation_parameters.keys()
if missing:
missing &= set(model.get_valid_parameters_for_parameter_table())
if missing:
raise ValueError(
"`simulation_parameters` must include all model parameters "
f"that are listed in the parameter table. Missing: {missing}."
)

# NOTE: order matters here - the former is overwritten by the latter:
# model < condition table < measurement < table parameter table
Expand Down Expand Up @@ -544,6 +568,29 @@ def _apply_condition_parameters(
scale_mapping[overridee_id] = LIN


def _get_model_parameters_for_mapping(
model: Model, parameter_df: pd.DataFrame | None
) -> dict[str, float]:
"""Get the model parameters to include in the mapping.

These are the free model parameters with their values in the model
(see :meth:`Model.get_free_parameter_ids_with_values`), plus the model
parameters that have a non-numeric initial assignment and are listed in
the parameter table. For the latter, the parameter table entry replaces
the initial assignment, and the value in the returned dict is ``NaN``,
since it will be taken from the parameter table.
"""
model_parameters = dict(model.get_free_parameter_ids_with_values())
if parameter_df is None:
return model_parameters

listed = set(parameter_df.index)
for par_id in model.get_valid_parameters_for_parameter_table():
if par_id in listed and par_id not in model_parameters:
model_parameters[par_id] = np.nan
return model_parameters


def _apply_parameter_table(
par_mapping: ParMappingDict,
scale_mapping: ScaleMappingDict,
Expand Down
69 changes: 68 additions & 1 deletion petab/v1/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,31 @@ def create_parameter_df(
All table entries can be provided as string or list-like with length
matching the number of parameters

.. note::

Listing a parameter that is the target of an initial assignment in
the parameter table replaces that assignment.
Therefore, with ``include_optional=True``, targets of initial
assignments that are not closed-form are omitted, since listing them
would discard the definition in the model (e.g., ``k_base + 1``).
Exception: such parameters are still included if they are referenced
in the measurement table (as observable or noise parameter overrides)
or in the condition table (as values), since these references require
a parameter table entry: named measurement table overrides must be
listed in the parameter table, and a condition table reference cannot
be resolved from a non-closed-form initial assignment. In these cases,
the parameter table entry also replaces the initial assignment in the
model; to keep the initial assignment, reference a separate parameter
instead.
An initial assignment is closed-form if it refers to no model
entities, function definitions, or time, and can be evaluated,
e.g., ``2 * 3``, but not ``k_base + 1`` or ``sqrt(-1)``.
This is decided syntactically, i.e., ``k - k`` is not closed-form.

For targets of closed-form initial assignments, the nominal value is
the value of the assignment. For all other model parameters,
it is the SBML ``value`` attribute.

Arguments:
sbml_model: SBML Model (deprecated, mutually exclusive with ``model``)
model: PEtab model (mutually exclusive with ``sbml_model``)
Expand All @@ -181,7 +206,7 @@ def create_parameter_df(
required to be present in the parameter table. If set to ``True``,
this returns all parameters that are allowed to be present in the
parameter table (i.e. also including parameters specified in the
model).
model), with the exception described in the note above.
parameter_scale: parameter scaling
lower_bound: lower bound for parameter value
upper_bound: upper bound for parameter value
Expand All @@ -205,6 +230,7 @@ def create_parameter_df(
"Arguments `model` and `sbml_model` are mutually exclusive."
)
model = SbmlModel(sbml_model=sbml_model)
ia_values = _get_initial_assignment_values(model)
if include_optional:
parameter_ids = list(
get_valid_parameters_for_parameter_table(
Expand All @@ -214,6 +240,29 @@ def create_parameter_df(
measurement_df=measurement_df,
)
)
# A parameter table entry for an initial assignment target replaces
# the initial assignment. If the assignment is not closed-form,
# this would discard its definition, so we omit such parameters.
# Exception: parameters that are referenced in the measurement
# table, which must be listed in the parameter table (see
# `get_required_parameters_for_parameter_table`), or in the
# condition table, where they can only be resolved via the
# parameter table, since their initial assignment has no numeric
# value.
skip = {id_ for id_, value in ia_values.items() if value is None}
if skip and measurement_df is not None:
for col in (OBSERVABLE_PARAMETERS, NOISE_PARAMETERS):
if col not in measurement_df:
continue
for value in measurement_df[col]:
skip.difference_update(
measurements.split_parameter_replacement_list(value)
)
if skip and condition_df is not None:
skip.difference_update(
conditions.get_parametric_overrides(condition_df)
)
parameter_ids = [p for p in parameter_ids if p not in skip]
else:
parameter_ids = list(
get_required_parameters_for_parameter_table(
Expand Down Expand Up @@ -244,6 +293,9 @@ def create_parameter_df(

# For model parameters, set nominal values as defined in the model
for parameter_id in df.index:
if (value := ia_values.get(parameter_id)) is not None:
df.loc[parameter_id, NOMINAL_VALUE] = value
continue
try:
df.loc[parameter_id, NOMINAL_VALUE] = model.get_parameter_value(
parameter_id
Expand All @@ -255,6 +307,21 @@ def create_parameter_df(
return df


def _get_initial_assignment_values(
model: Model | None,
) -> dict[str, float | None]:
"""Get the initial assignment targets of the model and their values.

See ``SbmlModel._get_initial_assignment_values``.
Empty for non-SBML models.
"""
from .models.sbml_model import SbmlModel

if not isinstance(model, SbmlModel):
return {}
return model._get_initial_assignment_values()


def get_required_parameters_for_parameter_table(
model: Model,
condition_df: pd.DataFrame,
Expand Down
Loading
Loading