diff --git a/changelog.d/+create-parameter-df-initial-assignments.fix.md b/changelog.d/+create-parameter-df-initial-assignments.fix.md new file mode 100644 index 00000000..60f732ac --- /dev/null +++ b/changelog.d/+create-parameter-df-initial-assignments.fix.md @@ -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)) diff --git a/changelog.d/+v1-parameter-table-replaces-initial-assignment.fix.md b/changelog.d/+v1-parameter-table-replaces-initial-assignment.fix.md new file mode 100644 index 00000000..fbcf20bd --- /dev/null +++ b/changelog.d/+v1-parameter-table-replaces-initial-assignment.fix.md @@ -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)) diff --git a/petab/v1/models/sbml_model.py b/petab/v1/models/sbml_model.py index 831a42e3..ee8431ce 100644 --- a/petab/v1/models/sbml_model.py +++ b/petab/v1/models/sbml_model.py @@ -3,6 +3,7 @@ from __future__ import annotations import itertools +import math from collections.abc import Iterable from pathlib import Path @@ -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 @@ -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. diff --git a/petab/v1/parameter_mapping.py b/petab/v1/parameter_mapping.py index 66d0a388..d3558292 100644 --- a/petab/v1/parameter_mapping.py +++ b/petab/v1/parameter_mapping.py @@ -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. @@ -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( @@ -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: @@ -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 @@ -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, diff --git a/petab/v1/parameters.py b/petab/v1/parameters.py index a5c66a09..20978014 100644 --- a/petab/v1/parameters.py +++ b/petab/v1/parameters.py @@ -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``) @@ -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 @@ -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( @@ -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( @@ -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 @@ -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, diff --git a/tests/v1/test_parameter_mapping.py b/tests/v1/test_parameter_mapping.py index ddb5ca99..410b1f5b 100644 --- a/tests/v1/test_parameter_mapping.py +++ b/tests/v1/test_parameter_mapping.py @@ -3,6 +3,7 @@ import numpy as np import pandas as pd +import pytest import petab.v1 as petab from petab import ENV_NUM_THREADS @@ -712,3 +713,110 @@ def test_fill_in_nominal_values(): assert expected_par == par_mapping assert expected_scale == scale_mapping + + +def test_parameter_table_replaces_initial_assignment(): + """A parameter table entry replaces a model parameter's initial + assignment, also if the assignment is not numeric.""" + model = SbmlModel.from_antimony( + """ + k_base = 1.5 + k_derived = k_base + 1 + k_other = k_base + 2 + k_cond = 3 + x = 1 + x' = -(k_derived + k_other + k_cond) * x + """ + ) + condition_df = pd.DataFrame( + {CONDITION_ID: ["c1"], "k_cond": ["k_derived"]} + ).set_index(CONDITION_ID) + observable_df = pd.DataFrame( + { + OBSERVABLE_ID: ["obs"], + OBSERVABLE_FORMULA: ["x"], + NOISE_FORMULA: ["noiseParameter1_obs"], + } + ).set_index(OBSERVABLE_ID) + measurement_df = pd.DataFrame( + { + OBSERVABLE_ID: ["obs"], + SIMULATION_CONDITION_ID: ["c1"], + TIME: [1.0], + MEASUREMENT: [0.5], + NOISE_PARAMETERS: ["k_derived"], + } + ) + # the nominal value differs from the initial assignment (2.5) and from + # the (unset) SBML value attribute + assert np.isnan(model.sbml_model.getParameter("k_derived").getValue()) + parameter_df = pd.DataFrame( + { + PARAMETER_ID: ["k_base", "k_derived"], + PARAMETER_SCALE: [LIN, LOG10], + LOWER_BOUND: [0.1, 0.1], + UPPER_BOUND: [100, 100], + NOMINAL_VALUE: [1.5, 7.0], + ESTIMATE: [1, 1], + } + ).set_index(PARAMETER_ID) + kwargs = { + "model": model, + "condition_df": condition_df, + "observable_df": observable_df, + "measurement_df": measurement_df, + } + + # estimated + ((_, par_map, _, scale_map),) = ( + petab.get_optimization_to_simulation_parameter_mapping( + parameter_df=parameter_df, **kwargs + ) + ) + assert par_map["k_derived"] == "k_derived" + assert scale_map["k_derived"] == LOG10 + # condition and measurement table references resolve to the same value + assert par_map["k_cond"] == "k_derived" + assert par_map["noiseParameter1_obs"] == "k_derived" + # not listed in the parameter table: the initial assignment applies + assert "k_other" not in par_map + + # fixed + parameter_df.loc["k_derived", ESTIMATE] = 0 + for scaled, expected in ((False, 7.0), (True, np.log10(7.0))): + ((_, par_map, _, _),) = ( + petab.get_optimization_to_simulation_parameter_mapping( + parameter_df=parameter_df, scaled_parameters=scaled, **kwargs + ) + ) + assert par_map["k_derived"] == expected + assert par_map["k_cond"] == expected + assert par_map["noiseParameter1_obs"] == expected + assert "k_other" not in par_map + + # same for the single-condition mapping + par_map, _ = petab.get_parameter_mapping_for_condition( + condition_id="c1", + is_preeq=False, + cur_measurement_df=measurement_df, + parameter_df=parameter_df, + model=model, + condition_df=condition_df, + ) + assert par_map["k_derived"] == 7.0 + assert par_map["k_cond"] == 7.0 + assert "k_other" not in par_map + + # precomputed simulation parameters must include listed parameters + with pytest.raises(ValueError, match="k_derived"): + petab.get_parameter_mapping_for_condition( + condition_id="c1", + is_preeq=False, + cur_measurement_df=measurement_df, + parameter_df=parameter_df, + model=model, + condition_df=condition_df, + simulation_parameters=dict( + model.get_free_parameter_ids_with_values() + ), + ) diff --git a/tests/v1/test_petab.py b/tests/v1/test_petab.py index a352fb58..e3f87b92 100644 --- a/tests/v1/test_petab.py +++ b/tests/v1/test_petab.py @@ -359,6 +359,110 @@ def test_create_parameter_df( assert parameter_df.loc["p0", NOMINAL_VALUE] == 3.0 +def test_create_parameter_df_initial_assignments(): + """Test petab.create_parameter_df with initial assignment targets.""" + model = SbmlModel.from_antimony( + """ + function f(x) + 2 * x + end + k_base = 1.5 + k_derived = k_base + 1 + k_num = 2 * 3 + k_log = ln(4) + k_fun = f(2) + k_zero = k_base - k_base + k_override = k_base * 2 + k_override_num = 2 * 4 + k_time = time + k_nan = sqrt(-1) + k_fun_unused = f(3) + k_cond = 1 + conc = 1 + conc' = -k_derived * conc + """ + ) + # all but k_base are initial assignment targets + assert { + ia.getSymbol() for ia in model.sbml_model.getListOfInitialAssignments() + } == { + "k_derived", + "k_num", + "k_log", + "k_fun", + "k_zero", + "k_override", + "k_override_num", + "k_time", + "k_nan", + "k_fun_unused", + } + + # condition table reference to a non-closed-form IA target + condition_df = pd.DataFrame( + {"k_cond": ["k_fun"]}, index=pd.Index(["c1"], name=CONDITION_ID) + ) + observable_df = pd.DataFrame( + { + OBSERVABLE_FORMULA: [ + "observableParameter1_obs * observableParameter2_obs * conc" + ], + NOISE_FORMULA: ["noiseParameter1_obs"], + }, + index=pd.Index(["obs"], name=OBSERVABLE_ID), + ) + measurement_df = pd.DataFrame( + { + OBSERVABLE_ID: ["obs", "obs"], + SIMULATION_CONDITION_ID: ["c1", "c1"], + TIME: [1.0, 2.0], + MEASUREMENT: [0.5, 0.4], + OBSERVABLE_PARAMETERS: ["k_zero;k_override_num", "1.0;2.0"], + NOISE_PARAMETERS: ["k_override", np.nan], + } + ) + parameter_df = petab.create_parameter_df( + model=model, + condition_df=condition_df, + observable_df=observable_df, + measurement_df=measurement_df, + include_optional=True, + ) + # targets of non-closed-form initial assignments are omitted, unless + # referenced in the measurement or condition table + assert parameter_df.index.tolist() == [ + "k_base", + "k_num", + "k_log", + "k_fun", + "k_zero", + "k_override", + "k_override_num", + ] + assert parameter_df.loc["k_base", NOMINAL_VALUE] == 1.5 + assert parameter_df.loc["k_override_num", NOMINAL_VALUE] == 8.0 + # closed-form initial assignments are evaluated + assert parameter_df.loc["k_num", NOMINAL_VALUE] == 6.0 + assert parameter_df.loc["k_log", NOMINAL_VALUE] == pytest.approx(np.log(4)) + + # required parameters only + parameter_df = petab.create_parameter_df( + model=model, + condition_df=condition_df, + observable_df=observable_df, + measurement_df=measurement_df, + ) + assert parameter_df.index.tolist() == [ + "k_zero", + "k_override_num", + "k_override", + ] + assert parameter_df.loc["k_override_num", NOMINAL_VALUE] == 8.0 + # not closed-form: SBML value attribute, which is unset here + assert np.isnan(parameter_df.loc["k_override", NOMINAL_VALUE]) + assert np.isnan(parameter_df.loc["k_zero", NOMINAL_VALUE]) + + def test_flatten_timepoint_specific_output_overrides(): """Test flatten_timepoint_specific_output_overrides""" observable_df = pd.DataFrame(