From 2e107cce5fd27d36860cee8a2c008659cbf439f4 Mon Sep 17 00:00:00 2001 From: Daniel Weindl Date: Wed, 2 Dec 2026 11:56:18 +0100 Subject: [PATCH] v1: use initial assignments for `NaN` in the condition table `NaN` in the condition table means that the model value is used. For model parameters, `_apply_condition_parameters` used the SBML `value` attribute and ignored initial assignments; `get_model_for_condition` then also removed the initial assignment. Now, the parameter keeps the model value from the initial mapping, which takes numeric initial assignments into account. Parameters with non-numeric initial assignments remain unmapped, so that the initial assignment applies. If such a parameter is unmapped for only one of preequilibration and simulation, raise a `ValueError` instead of letting `merge_preeq_and_sim_pars_condition` silently use the other value. Closes #649. Co-Authored-By: Claude Opus 5.5 --- .../+condition-nan-initial-assignment.fix.md | 7 ++ petab/v1/parameter_mapping.py | 72 ++++++++++++++---- petab/v1/sbml.py | 2 + tests/v1/test_parameter_mapping.py | 74 +++++++++++++++++++ 4 files changed, 140 insertions(+), 15 deletions(-) create mode 100644 changelog.d/+condition-nan-initial-assignment.fix.md diff --git a/changelog.d/+condition-nan-initial-assignment.fix.md b/changelog.d/+condition-nan-initial-assignment.fix.md new file mode 100644 index 00000000..0ffa044d --- /dev/null +++ b/changelog.d/+condition-nan-initial-assignment.fix.md @@ -0,0 +1,7 @@ +v1: `NaN` in the condition table now maps a parameter to its initial +assignment, if it has one, instead of its SBML `value` attribute. For +non-numeric initial assignments, the parameter remains unmapped, and +`get_model_for_condition` keeps the initial assignment. A `ValueError` is +raised if such a parameter has a value for only one of the preequilibration +and simulation conditions. +([#656](https://github.com/PEtab-dev/libpetab-python/pull/656)) diff --git a/petab/v1/parameter_mapping.py b/petab/v1/parameter_mapping.py index ef18c3af..441fb322 100644 --- a/petab/v1/parameter_mapping.py +++ b/petab/v1/parameter_mapping.py @@ -127,6 +127,10 @@ def get_optimization_to_simulation_parameter_mapping( condition. If no preequilibration condition is defined, the respective dicts will be empty. ``NaN`` is used where no mapping exists. + A model parameter with a non-numeric initial assignment is absent + unless the parameter table lists it or the condition table assigns + it a value other than ``NaN``. An absent parameter keeps its initial + assignment. """ if sbml_model: warnings.warn( @@ -314,6 +318,35 @@ def _map_condition(packed_args): allow_timepoint_specific_numeric_noise_parameters=allow_timepoint_specific_numeric_noise_parameters, ) + # A NaN in the condition table leaves parameters with non-numeric + # initial assignments unmapped. If such a parameter is mapped for only + # one of preequilibration and simulation, merging the mappings would + # silently use that value for both. + if par_map_preeq: + for par_id in condition_df.columns: + par_id = resolve_mapping(mapping_df, par_id) + in_preeq = par_id in par_map_preeq + if in_preeq == (par_id in par_map_sim): + continue + value = (par_map_preeq if in_preeq else par_map_sim)[par_id] + if core.is_empty(value): + continue + mapped, unmapped = ( + ("preequilibration", "simulation") + if in_preeq + else ("simulation", "preequilibration") + ) + raise ValueError( + f"Parameter `{par_id}` is mapped to `{value}` for {mapped}, " + f"but to its non-numeric model value for {unmapped} " + "(preequilibration condition " + f"`{condition[PREEQUILIBRATION_CONDITION_ID]}`, simulation " + f"condition `{condition[SIMULATION_CONDITION_ID]}`). " + "Different values for preequilibration and simulation are " + "not supported for parameters with non-numeric model values " + "(e.g., initial assignments)." + ) + return par_map_preeq, par_map_sim, scale_map_preeq, scale_map_sim @@ -364,7 +397,9 @@ def get_parameter_mapping_for_condition( :func:`get_optimization_to_simulation_parameter_mapping`). If provided, it must include all model parameters that are listed in the parameter table; otherwise, a :class:`ValueError` - is raised. + is raised. Values must take numeric initial assignments into + account, since they are used for ``NaN`` entries in the + condition table. warn_unmapped: If ``True``, log warning regarding unmapped parameters scaled_parameters: @@ -386,6 +421,10 @@ def get_parameter_mapping_for_condition( of non-estimated parameters. Second dictionary mapping model parameter IDs to their scale. ``NaN`` is used where no mapping exists. + A model parameter with a non-numeric initial assignment is absent + unless the parameter table lists it or the condition table assigns + it a value other than ``NaN``. An absent parameter keeps its initial + assignment. """ if sbml_model: warnings.warn( @@ -587,25 +626,28 @@ def _apply_condition_parameters( if model.is_state_variable(overridee_id): continue - par_mapping[overridee_id] = core.to_float_if_float( + value = core.to_float_if_float( condition_df.loc[condition_id, overridee_id] ) - if isinstance(par_mapping[overridee_id], numbers.Number) and np.isnan( - par_mapping[overridee_id] - ): + if isinstance(value, numbers.Number) and np.isnan(value): # NaN in the condition table for an entity without time derivative - # indicates that the model value should be used - try: - par_mapping[overridee_id] = model.get_parameter_value( - overridee_id - ) - except ValueError as e: - raise NotImplementedError( - "Not sure how to handle NaN in condition table for " - f"{overridee_id}." - ) from e + # indicates that the model value should be used. `par_mapping` + # was initialized with the model values, taking numeric initial + # assignments into account. Parameters with non-numeric initial + # assignments are not included and remain unmapped, so that the + # initial assignment applies. + if ( + overridee_id in par_mapping + or overridee_id in model.get_parameter_ids() + ): + continue + raise NotImplementedError( + "Not sure how to handle NaN in condition table for " + f"{overridee_id}." + ) + par_mapping[overridee_id] = value scale_mapping[overridee_id] = LIN diff --git a/petab/v1/sbml.py b/petab/v1/sbml.py index ad28a912..4c634f99 100644 --- a/petab/v1/sbml.py +++ b/petab/v1/sbml.py @@ -292,6 +292,8 @@ def get_param_value(parameter_id: str): """Parameter value from mapping or nominal value""" mapped_value = parameter_map.get(parameter_id) if mapped_value is None: + if petab_problem.parameter_df is None: + return None # Handle parametric initial concentrations with contextlib.suppress(KeyError): return petab_problem.parameter_df.loc[ diff --git a/tests/v1/test_parameter_mapping.py b/tests/v1/test_parameter_mapping.py index c36e92de..3b4c623b 100644 --- a/tests/v1/test_parameter_mapping.py +++ b/tests/v1/test_parameter_mapping.py @@ -791,3 +791,77 @@ def test_parameter_table_replaces_initial_assignment(): problem.model.get_free_parameter_ids_with_values() ), ) + + +def test_nan_in_condition_table_uses_initial_assignment(): + """NaN in the condition table maps a parameter to its model value, + taking initial assignments into account.""" + model = SbmlModel.from_antimony( + """ + k_base = 1.5 + k_derived = k_base + 1 + k_num = 2 * 3 + k_plain = 4 + x = 1 + x' = -(k_derived + k_num + k_plain) * x + """ + ) + # stale `value` attributes must not be used + model.sbml_model.getParameter("k_derived").setValue(98) + model.sbml_model.getParameter("k_num").setValue(99) + problem = petab.Problem(model=model) + problem.add_condition("c1", k_derived=np.nan, k_num=np.nan, k_plain=np.nan) + problem.add_condition("c2", k_derived=1.0, k_num=2.0, k_plain=3.0) + problem.add_observable("obs", "x", noise_formula="1") + problem.add_measurement("obs", "c1", 1.0, 0.5) + problem.add_measurement("obs", "c2", 1.0, 0.5) + problem.add_parameter( + "k_base", nominal_value=1.5, scale=LIN, lb=0.1, ub=10 + ) + + (_, par_map_c1, _, _), (_, par_map_c2, _, _) = ( + problem.get_optimization_to_simulation_parameter_mapping() + ) + # numeric initial assignment + assert par_map_c1["k_num"] == 6.0 + # no initial assignment + assert par_map_c1["k_plain"] == 4.0 + # non-numeric initial assignment: unmapped, so the assignment applies + assert "k_derived" not in par_map_c1 + # non-NaN values are applied + assert par_map_c2["k_derived"] == 1.0 + assert par_map_c2["k_num"] == 2.0 + assert par_map_c2["k_plain"] == 3.0 + + _, sbml_model = petab.sbml.get_model_for_condition(problem, "c1") + assert sbml_model.getInitialAssignmentBySymbol("k_derived") is not None + assert sbml_model.getParameter("k_num").getValue() == 6.0 + assert sbml_model.getParameter("k_plain").getValue() == 4.0 + + # without parameter table + problem_no_par = petab.Problem( + model=problem.model, + condition_df=problem.condition_df, + observable_df=problem.observable_df, + measurement_df=problem.measurement_df, + ) + _, sbml_model = petab.sbml.get_model_for_condition(problem_no_par, "c1") + assert sbml_model.getInitialAssignmentBySymbol("k_derived") is not None + assert sbml_model.getParameter("k_num").getValue() == 6.0 + + # NaN for simulation of a parameter with a non-numeric initial + # assignment, but a value for preequilibration + problem.measurement_df[PREEQUILIBRATION_CONDITION_ID] = ["c2", ""] + with pytest.raises( + ValueError, match="`k_derived` is mapped to `1.0` for preeq" + ): + problem.get_optimization_to_simulation_parameter_mapping() + # ... and vice versa + problem.measurement_df[PREEQUILIBRATION_CONDITION_ID] = ["", "c1"] + with pytest.raises( + ValueError, match="`k_derived` is mapped to `1.0` for simulation" + ): + problem.get_optimization_to_simulation_parameter_mapping() + # same value (here: unmapped) for both is fine + problem.measurement_df[PREEQUILIBRATION_CONDITION_ID] = ["c1", ""] + problem.get_optimization_to_simulation_parameter_mapping()