diff --git a/changelog.d/+v1-estimate-bounds-invalid.fix.md b/changelog.d/+v1-estimate-bounds-invalid.fix.md new file mode 100644 index 00000000..954027b7 --- /dev/null +++ b/changelog.d/+v1-estimate-bounds-invalid.fix.md @@ -0,0 +1,13 @@ +PEtab v1 validation: invalid `estimate` values and non-numeric +`lowerBound`, `upperBound`, and `nominalValue` values are now reported as +errors naming the affected parameters, instead of crashing `lint_problem` +or passing silently. +Missing bounds of estimated parameters are reported as such, instead of as +`lowerBound` greater than `upperBound`, and bound checks report all +affected parameters. +`estimate` must be the number 0 or 1, or the string `"0"` or `"1"`; +booleans and other strings, such as `"1.0"`, are rejected. +The `estimate` column is now interpreted consistently throughout +`petab.v1`; previously, the string `"1"` was treated as not estimated by, +e.g., `get_optimization_parameters` +([#650](https://github.com/PEtab-dev/libpetab-python/pull/650)) diff --git a/petab/v1/lint.py b/petab/v1/lint.py index 1ac9d375..54a3f4cf 100644 --- a/petab/v1/lint.py +++ b/petab/v1/lint.py @@ -257,24 +257,20 @@ def check_parameter_df( # nominal value is generally optional, but required for parameters # with estimate == 0 - non_estimated_par_ids = list(df.index[df[ESTIMATE].apply(int) != 1]) + non_estimated_par_ids = list(df.index[~parameters._is_estimated(df)]) + if non_estimated_par_ids and NOMINAL_VALUE not in df: + raise AssertionError( + "Parameter table contains parameters " + f"{non_estimated_par_ids} that are not " + "specified to be estimated, " + f"but column {NOMINAL_VALUE} is missing." + ) + if NOMINAL_VALUE in df: + _assert_numeric_or_missing(df, NOMINAL_VALUE) if non_estimated_par_ids: - if NOMINAL_VALUE not in df: - raise AssertionError( - "Parameter table contains parameters " - f"{non_estimated_par_ids} that are not " - "specified to be estimated, " - f"but column {NOMINAL_VALUE} is missing." - ) - try: - nominal_values = pd.to_numeric( - df.loc[non_estimated_par_ids, NOMINAL_VALUE] - ) - except (ValueError, TypeError) as e: - raise AssertionError( - f"Expected numeric values for `{NOMINAL_VALUE}` in parameter " - "table for all non-estimated parameters." - ) from e + nominal_values = parameters._parse_floats( + df.loc[non_estimated_par_ids, NOMINAL_VALUE] + ) if missing := list(nominal_values.index[nominal_values.isna()]): raise AssertionError( f"`{NOMINAL_VALUE}` is required for parameters with " @@ -636,8 +632,23 @@ def assert_parameter_bounds_are_numeric(parameter_df: pd.DataFrame) -> None: Raises: AssertionError: in case of problems """ - parameter_df[LOWER_BOUND].apply(float).all() - parameter_df[UPPER_BOUND].apply(float).all() + for column in (LOWER_BOUND, UPPER_BOUND): + _assert_numeric_or_missing(parameter_df, column) + + +def _assert_numeric_or_missing(df: pd.DataFrame, column: str) -> None: + """Check that the values of a column are numeric or missing. + + Numeric strings are accepted, see :func:`parameters._parse_floats`. + """ + values = df[column] + present = values.notna() & ~values.isin([""]) + invalid = present & parameters._parse_floats(values).isna() + if invalid.any(): + raise AssertionError( + f"Expected numeric values in `{column}` column, but got " + f"{values[invalid].to_dict()}." + ) def check_parameter_bounds(parameter_df: pd.DataFrame) -> None: @@ -653,31 +664,45 @@ def check_parameter_bounds(parameter_df: pd.DataFrame) -> None: AssertionError: in case of problems """ - for _, row in parameter_df.iterrows(): - if int(row[ESTIMATE]): - if not row[LOWER_BOUND] <= row[UPPER_BOUND]: - raise AssertionError( - f"{LOWER_BOUND} greater than {UPPER_BOUND} for " - f"{PARAMETER_ID} {row.name}." - ) - if (row[LOWER_BOUND] < 0.0 or row[UPPER_BOUND] < 0.0) and row[ - PARAMETER_SCALE - ] in [LOG, LOG10]: - raise AssertionError( - f"Bounds for {row[PARAMETER_SCALE]} scaled parameter " - f"{row.name} must be positive." - ) - if ( - row.get(PARAMETER_SCALE, LIN) in [LOG, LOG10] - and (row[LOWER_BOUND] == 0.0 or row[UPPER_BOUND] == 0.0) - and not row.get(INITIALIZATION_PRIOR_TYPE) - ): - raise AssertionError( - f"Bounds for {row[PARAMETER_SCALE]} scaled parameter " - f"{row.name} must be positive if no " - f"{INITIALIZATION_PRIOR_TYPE} is provided. " - "Cannot sample from unbounded interval." - ) + df = parameter_df[parameters._is_estimated(parameter_df)] + lb = parameters._parse_floats(df[LOWER_BOUND]) + ub = parameters._parse_floats(df[UPPER_BOUND]) + + def ids(mask: pd.Series) -> list: + return list(df.index[mask]) + + if (missing := lb.isna() | ub.isna()).any(): + raise AssertionError( + f"`{LOWER_BOUND}` and `{UPPER_BOUND}` are required for estimated " + f"parameters, but are missing for {ids(missing)}." + ) + if (invalid := lb > ub).any(): + raise AssertionError( + f"`{LOWER_BOUND}` greater than `{UPPER_BOUND}` for {ids(invalid)}." + ) + + if PARAMETER_SCALE in df: + log_scaled = df[PARAMETER_SCALE].isin([LOG, LOG10]) + else: + log_scaled = pd.Series(False, index=df.index) + if (invalid := log_scaled & ((lb < 0.0) | (ub < 0.0))).any(): + raise AssertionError( + f"Bounds for log- or log10-scaled parameters must be positive, " + f"but are negative for {ids(invalid)}." + ) + if INITIALIZATION_PRIOR_TYPE in df: + # NaN is truthy, so empty cells currently count as a provided prior + has_init_prior = df[INITIALIZATION_PRIOR_TYPE].map(bool) + else: + has_init_prior = pd.Series(False, index=df.index) + if ( + invalid := log_scaled & ((lb == 0.0) | (ub == 0.0)) & ~has_init_prior + ).any(): + raise AssertionError( + f"Bounds for log- or log10-scaled parameters must be positive if " + f"no `{INITIALIZATION_PRIOR_TYPE}` is provided, but are zero for " + f"{ids(invalid)}. Cannot sample from unbounded interval." + ) def assert_parameter_prior_type_is_valid(parameter_df: pd.DataFrame) -> None: @@ -780,11 +805,13 @@ def assert_parameter_estimate_is_boolean(parameter_df: pd.DataFrame) -> None: Raises: AssertionError: in case of problems """ - for estimate in parameter_df[ESTIMATE]: - if int(estimate) not in [True, False]: - raise AssertionError( - f"Expected 0 or 1 but got {estimate} in {ESTIMATE} column." - ) + values = parameter_df[ESTIMATE] + invalid = parameters._parse_estimate(values).isna() + if invalid.any(): + raise AssertionError( + f"Expected 0 or 1 in `{ESTIMATE}` column, but got " + f"{values[invalid].to_dict()}." + ) def is_scalar_float(x: Any): diff --git a/petab/v1/parameter_mapping.py b/petab/v1/parameter_mapping.py index 66d0a388..318d104a 100644 --- a/petab/v1/parameter_mapping.py +++ b/petab/v1/parameter_mapping.py @@ -568,14 +568,19 @@ def _apply_parameter_table( if parameter_df is None: return - for row in parameter_df.itertuples(): + if fill_fixed_parameters and ESTIMATE in parameter_df: + is_fixed = ~parameters._is_estimated(parameter_df) + else: + is_fixed = pd.Series(False, index=parameter_df.index) + + for row, fixed in zip(parameter_df.itertuples(), is_fixed, strict=True): if row.Index not in par_mapping: # The current parameter is not required for this condition continue scale = getattr(row, PARAMETER_SCALE, LIN) scale_mapping[row.Index] = scale - if fill_fixed_parameters and getattr(row, ESTIMATE) == 0: + if fixed: val = getattr(row, NOMINAL_VALUE) if scaled_parameters: val = parameters.scale(val, scale) @@ -606,11 +611,7 @@ def _apply_parameter_table( else LIN ) - if ( - fill_fixed_parameters - and ESTIMATE in parameter_df - and parameter_df.loc[sim_par, ESTIMATE] == 0 - ): + if is_fixed.get(sim_par, False): val = parameter_df.loc[sim_par, NOMINAL_VALUE] if scaled_parameters: val = parameters.scale(val, scale) diff --git a/petab/v1/parameters.py b/petab/v1/parameters.py index a5c66a09..48ff792b 100644 --- a/petab/v1/parameters.py +++ b/petab/v1/parameters.py @@ -131,7 +131,49 @@ def get_optimization_parameters(parameter_df: pd.DataFrame) -> list[str]: Returns: List of IDs of parameters selected for optimization. """ - return list(parameter_df.index[parameter_df[ESTIMATE] == 1]) + return list(parameter_df.index[_is_estimated(parameter_df)]) + + +def _parse_floats(values: pd.Series, allow_bool: bool = False) -> pd.Series: + """Convert parameter table values to float. + + Real numbers and numeric strings are converted. Anything else, + including missing values, complex numbers, and booleans (unless + ``allow_bool`` is set), gives NaN. ``values`` is not modified. + """ + if values.dtype.kind in "iuf": + return values.astype(float) + invalid = values.map( + lambda v: ( + isinstance(v, complex) + or (not allow_bool and isinstance(v, bool | np.bool_)) + ) + ) + return pd.to_numeric(values.mask(invalid), errors="coerce").astype(float) + + +def _parse_estimate(values: pd.Series, allow_bool: bool = False) -> pd.Series: + """Parse the values of the ``estimate`` column. + + Accepted are numbers equal to 0 or 1, and the strings ``"0"`` and + ``"1"``. Booleans are only accepted if ``allow_bool`` is set. Returns a + new float series with 0, 1, or NaN for invalid values. + """ + result = _parse_floats(values, allow_bool) + if values.dtype.kind not in "iufb": + is_str = values.map(lambda v: isinstance(v, str)) + result = result.mask(is_str & ~values.isin(["0", "1"])) + return result.where(result.isin([0, 1])) + + +def _is_estimated(parameter_df: pd.DataFrame) -> pd.Series: + """Get a boolean mask of the estimated parameters. + + See :func:`_parse_estimate` for the accepted values. Booleans, which + are invalid, are still interpreted as 0 or 1 for backwards + compatibility. Other invalid values count as not estimated. + """ + return _parse_estimate(parameter_df[ESTIMATE], allow_bool=True) == 1 def get_optimization_parameter_scaling( @@ -148,7 +190,7 @@ def get_optimization_parameter_scaling( Dictionary with optimization parameter IDs mapped to parameter scaling strings. """ - estimated_df = parameter_df.loc[parameter_df[ESTIMATE] == 1] + estimated_df = parameter_df.loc[_is_estimated(parameter_df)] return dict( zip(estimated_df.index, estimated_df[PARAMETER_SCALE], strict=True) ) @@ -458,7 +500,7 @@ def get_priors_from_df( List with prior information. """ # get types and parameters of priors from dataframe - par_to_estimate = parameter_df.loc[parameter_df[ESTIMATE] == 1] + par_to_estimate = parameter_df.loc[_is_estimated(parameter_df)] if parameter_ids is not None: try: diff --git a/petab/v1/priors.py b/petab/v1/priors.py index 1cdf66a9..2b996463 100644 --- a/petab/v1/priors.py +++ b/petab/v1/priors.py @@ -10,7 +10,6 @@ from ..v1.C import PREEQUILIBRATION_CONDITION_ID from . import ( - ESTIMATE, LAPLACE, LIN, LOG, @@ -37,7 +36,7 @@ Problem, ) from .distributions import * -from .parameters import scale, unscale +from .parameters import _is_estimated, scale, unscale __all__ = ["priors_to_measurements"] @@ -349,7 +348,7 @@ def priors_to_measurements(problem: Problem): new_problem = copy.deepcopy(problem) # we only need to consider parameters that are estimated - par_df_tmp = problem.parameter_df.loc[problem.parameter_df[ESTIMATE] == 1] + par_df_tmp = problem.parameter_df.loc[_is_estimated(problem.parameter_df)] if ( OBJECTIVE_PRIOR_TYPE not in par_df_tmp diff --git a/petab/v1/problem.py b/petab/v1/problem.py index 643d6cbd..af2d2cfc 100644 --- a/petab/v1/problem.py +++ b/petab/v1/problem.py @@ -164,17 +164,17 @@ def __str__(self): if self.parameter_df is not None: num_estimated_parameters = ( - sum(self.parameter_df[ESTIMATE] == 1) + parameters._is_estimated(self.parameter_df).sum() if ESTIMATE in self.parameter_df else self.parameter_df.shape[0] ) - parameters = f"{num_estimated_parameters} estimated parameters" + parameters_str = f"{num_estimated_parameters} estimated parameters" else: - parameters = "without parameter_df table" + parameters_str = "without parameter_df table" return ( f"PEtab Problem {model}, {conditions}, {observables}, " - f"{measurements}, {parameters}" + f"{measurements}, {parameters_str}" ) @staticmethod @@ -882,14 +882,14 @@ def ub_scaled(self) -> list: @property def x_free_indices(self) -> list[int]: """Parameter table estimated parameter indices.""" - estimated = list(self.parameter_df[ESTIMATE]) - return [j for j, val in enumerate(estimated) if val != 0] + estimated = parameters._is_estimated(self.parameter_df) + return [j for j, val in enumerate(estimated) if val] @property def x_fixed_indices(self) -> list[int]: """Parameter table non-estimated parameter indices.""" - estimated = list(self.parameter_df[ESTIMATE]) - return [j for j, val in enumerate(estimated) if val == 0] + estimated = parameters._is_estimated(self.parameter_df) + return [j for j, val in enumerate(estimated) if not val] def get_simulation_conditions_from_measurement_df(self): """See petab.v1.get_simulation_conditions""" diff --git a/petab/v1/sampling.py b/petab/v1/sampling.py index 49049099..bcce9bc5 100644 --- a/petab/v1/sampling.py +++ b/petab/v1/sampling.py @@ -57,12 +57,13 @@ def sample_parameter_startpoints( Array of sampled starting points with dimensions `n_startpoints` x `n_optimization_parameters` """ + from .parameters import _is_estimated from .priors import Prior if seed is not None: np.random.seed(seed) - par_to_estimate = parameter_df.loc[parameter_df[ESTIMATE] == 1] + par_to_estimate = parameter_df.loc[_is_estimated(parameter_df)] if parameter_ids is not None: try: diff --git a/petab/v2/petab1to2.py b/petab/v2/petab1to2.py index 52671312..2ff75878 100644 --- a/petab/v2/petab1to2.py +++ b/petab/v2/petab1to2.py @@ -16,7 +16,7 @@ from pandas.io.common import get_handle, is_url from .. import v1, v2 -from ..v1.parameters import scale, unscale +from ..v1.parameters import _is_estimated, scale, unscale from ..v1.yaml import get_path_prefix, load_yaml from ..v1.yaml import validate as validate_yaml from ..versions import get_major_version @@ -616,7 +616,7 @@ def _has_objective_priors(parameter_df: pd.DataFrame) -> bool: return bool( ( parameter_df[v1.C.OBJECTIVE_PRIOR_TYPE].notna() - & (parameter_df[v1.C.ESTIMATE].astype(int) == 1) + & _is_estimated(parameter_df) ).any() ) @@ -638,9 +638,9 @@ def v1v2_parameter_df( df = parameter_df.copy().reset_index() # parameter.estimate: int -> bool - df[v2.C.ESTIMATE] = df[v1.C.ESTIMATE].apply( - lambda x: str(bool(int(x))).lower() - ) + df[v2.C.ESTIMATE] = ( + _is_estimated(parameter_df).map({True: "true", False: "false"}) + ).to_numpy() has_priors = _has_objective_priors(parameter_df) @@ -745,7 +745,7 @@ def update_prior(row) -> tuple[str | None, str | None]: msg = "Parameter scales are not supported in PEtab v2." reparametrizable = ( parameter_df[v1.C.PARAMETER_SCALE].isin([v1.C.LOG, v1.C.LOG10]) - & (parameter_df[v1.C.ESTIMATE].astype(int) == 1) + & _is_estimated(parameter_df) & (parameter_df[v1.C.LOWER_BOUND] >= 0) ) if reparametrize == "none" and reparametrizable.any(): @@ -828,7 +828,10 @@ def _reparametrize_log_scaled( zero_bound = [] # non-estimated parameters whose priors cannot be converted no_prior = set() - for par_id, row in df.iterrows(): + is_estimated = _is_estimated(df) + for (par_id, row), estimate in zip( + df.iterrows(), is_estimated, strict=True + ): pscale = row[v1.C.PARAMETER_SCALE] if pscale not in (v1.C.LOG, v1.C.LOG10): continue @@ -842,7 +845,6 @@ def _reparametrize_log_scaled( # A prior over the unscaled parameter. Its conversion already # preserves the objective function. continue - estimate = int(row[v1.C.ESTIMATE]) is_selected = estimate and ( reparametrize == "all" or prior_type is not None ) diff --git a/tests/v1/test_lint.py b/tests/v1/test_lint.py index d0304f79..68d8164a 100644 --- a/tests/v1/test_lint.py +++ b/tests/v1/test_lint.py @@ -3,6 +3,7 @@ from math import nan from unittest.mock import patch +import numpy as np import pandas as pd import pytest @@ -386,6 +387,104 @@ def test_check_parameter_bounds(): ) +def test_check_parameter_bounds_string_values(): + # numeric strings are compared as numbers, not lexicographically + lint.check_parameter_bounds( + pd.DataFrame({LOWER_BOUND: ["9"], UPPER_BOUND: [10], ESTIMATE: ["1"]}) + ) + with pytest.raises(AssertionError, match="greater than"): + lint.check_parameter_bounds( + pd.DataFrame( + {LOWER_BOUND: ["20"], UPPER_BOUND: [10], ESTIMATE: ["1"]} + ) + ) + # not estimated + lint.check_parameter_bounds( + pd.DataFrame({LOWER_BOUND: ["20"], UPPER_BOUND: [10], ESTIMATE: ["0"]}) + ) + + +def test_check_parameter_bounds_reports_all(): + df = pd.DataFrame( + { + PARAMETER_ID: ["p1", "p2", "p3", "p4", "p5", "p6"], + LOWER_BOUND: ["", np.nan, 3, 3, 0, -1], + UPPER_BOUND: [1, 1, 2, 2, 1, 1], + ESTIMATE: [1, 1, 1, 0, 1, 1], + PARAMETER_SCALE: [LIN, LIN, LIN, LIN, LOG10, LOG], + } + ).set_index(PARAMETER_ID) + + with pytest.raises(AssertionError, match=r"missing for \['p1', 'p2'\]"): + lint.check_parameter_bounds(df) + + df = df.drop(["p1", "p2"]) + with pytest.raises(AssertionError, match=r"greater .* for \['p3'\]"): + lint.check_parameter_bounds(df) + + df = df.drop("p3") + with pytest.raises(AssertionError, match=r"negative for \['p6'\]"): + lint.check_parameter_bounds(df) + + df = df.drop("p6") + with pytest.raises(AssertionError, match=r"zero for \['p5'\]"): + lint.check_parameter_bounds(df) + + df[INITIALIZATION_PRIOR_TYPE] = [NORMAL, NORMAL] + lint.check_parameter_bounds(df) + + +def test_assert_parameter_estimate_is_boolean(): + valid = [0, 1, 0.0, 1.0, np.int64(1), np.float32(0), "0", "1"] + lint.assert_parameter_estimate_is_boolean( + pd.DataFrame({ESTIMATE: pd.Series(valid, dtype=object)}) + ) + + for invalid in ( + *("abc", "", "1.0", "+1", "01", " 1", "true"), + *(True, False, 1 + 0j, nan, None, pd.NA, 0.5, 2, -1, float("inf")), + ): + df = pd.DataFrame( + { + ESTIMATE: pd.Series( + [1, invalid], index=["p_valid", "p_invalid"], dtype=object + ) + } + ) + with pytest.raises(AssertionError) as excinfo: + lint.assert_parameter_estimate_is_boolean(df) + assert "p_invalid" in str(excinfo.value) + assert "p_valid" not in str(excinfo.value) + + +def test_assert_parameter_bounds_are_numeric(): + # missing values are allowed here + valid = [0, 1.5, "1e-3", "-inf", nan, None, pd.NA, ""] + df = pd.DataFrame( + { + LOWER_BOUND: pd.Series(valid, dtype=object), + UPPER_BOUND: pd.Series(valid, dtype=object), + } + ) + lint.assert_parameter_bounds_are_numeric(df) + + for column in (LOWER_BOUND, UPPER_BOUND): + df = pd.DataFrame( + { + LOWER_BOUND: [1, 1], + UPPER_BOUND: [2, 2], + }, + index=["p_valid", "p_invalid"], + dtype=object, + ) + for invalid in ("abc", "nan", "1_0", 1 + 0j, True): + df.loc["p_invalid", column] = invalid + with pytest.raises(AssertionError, match=column) as excinfo: + lint.assert_parameter_bounds_are_numeric(df) + assert "p_invalid" in str(excinfo.value) + assert "p_valid" not in str(excinfo.value) + + def test_assert_parameter_prior_type_is_valid(): """Check lint.assert_parameter_prior_type_is_valid.""" lint.assert_parameter_prior_type_is_valid( @@ -605,6 +704,12 @@ def test_check_parameter_df(): with pytest.raises(AssertionError, match="Expected numeric values"): lint.check_parameter_df(df=parameter_df) + # NOMINAL_VALUE non-numeric, for estimated parameter + parameter_df.loc["par2", NOMINAL_VALUE] = 1.0 + parameter_df.loc["par1", NOMINAL_VALUE] = "abc" + with pytest.raises(AssertionError, match=r"\{'par1': 'abc'\}"): + lint.check_parameter_df(df=parameter_df) + # NOMINAL_VALUE column missing, but non-estimated parameter del parameter_df[NOMINAL_VALUE] with pytest.raises(AssertionError): @@ -796,6 +901,29 @@ def test_lint_problem_placeholders_only_used_in_own_observable(): ) +@pytest.mark.parametrize( + "column,value,expected", + [ + (ESTIMATE, "abc", "Expected 0 or 1"), + (ESTIMATE, nan, "Expected 0 or 1"), + (LOWER_BOUND, "abc", "Expected numeric values in `lowerBound`"), + (UPPER_BOUND, "ten", "Expected numeric values in `upperBound`"), + ], +) +def test_lint_problem_invalid_parameter_values(column, value, expected): + """Invalid parameter table values are reported, not raised.""" + problem = _placeholder_problem() + problem.parameter_df[column] = pd.Series( + [value], index=problem.parameter_df.index, dtype=object + ) + with patch.object(lint.logger, "error") as error: + assert lint.lint_problem(problem) is True + assert any( + expected in str(call.args[0]) and "'p'" in str(call.args[0]) + for call in error.call_args_list + ) + + def test_condition_ids_are_unique(): condition_df = pd.DataFrame( data={ diff --git a/tests/v1/test_parameters.py b/tests/v1/test_parameters.py index 42e86165..12ac29ca 100644 --- a/tests/v1/test_parameters.py +++ b/tests/v1/test_parameters.py @@ -47,6 +47,56 @@ def test_get_optimization_parameters(): assert actual == expected +@pytest.mark.parametrize( + "estimate", + [ + [1, 0, 1], + [1.0, 0.0, 1.0], + ["1", "0", "1"], + # invalid, but accepted for backwards compatibility + [True, False, True], + pd.array([True, False, True], dtype="boolean"), + pd.array([1, pd.NA, 1], dtype="Int64"), + ], +) +def test_estimate_interpretation(estimate): + """`estimate` is interpreted the same for numeric and string values.""" + df = pd.DataFrame( + data={ + PARAMETER_ID: ["p1", "p2", "p3"], + PARAMETER_SCALE: [LOG10, LIN, LIN], + LOWER_BOUND: [0.1, 0.1, 0.1], + UPPER_BOUND: [10.0, 10.0, 10.0], + NOMINAL_VALUE: [1.0, 2.0, 3.0], + ESTIMATE: estimate, + } + ).set_index(PARAMETER_ID) + df_orig = df.copy() + + assert petab.get_optimization_parameters(df) == ["p1", "p3"] + assert petab.get_optimization_parameter_scaling(df) == { + "p1": LOG10, + "p3": LIN, + } + problem = petab.Problem(parameter_df=df) + assert problem.x_free_indices == [0, 2] + assert problem.x_fixed_indices == [1] + assert "2 estimated parameters" in str(problem) + + from petab.v1.parameter_mapping import _apply_parameter_table + + # `p1` directly from the parameter table, `q` and `r` via overrides + par_mapping = {"p1": "p1", "q": "p2", "r": "p3"} + _apply_parameter_table(par_mapping, {}, df) + assert par_mapping == {"p1": "p1", "q": 2.0, "r": "p3"} + par_mapping = {"p2": "p2"} + _apply_parameter_table(par_mapping, {}, df) + assert par_mapping == {"p2": 2.0} + + # the parameter table is not modified + pd.testing.assert_frame_equal(df, df_orig) + + def test_get_parameter_df(): """Test parameters.get_parameter_df.""" # parameter df missing ids