Skip to content
Merged
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
13 changes: 13 additions & 0 deletions changelog.d/+v1-estimate-bounds-invalid.fix.md
Original file line number Diff line number Diff line change
@@ -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))
125 changes: 76 additions & 49 deletions petab/v1/lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down Expand Up @@ -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([""])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This together with the check in line 679 could produce a misleading error when only one value is "" correct? not sure this is intended.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Old issue, but good catch. Fixed now.

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:
Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand Down
15 changes: 8 additions & 7 deletions petab/v1/parameter_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
48 changes: 45 additions & 3 deletions petab/v1/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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)
)
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 2 additions & 3 deletions petab/v1/priors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from ..v1.C import PREEQUILIBRATION_CONDITION_ID
from . import (
ESTIMATE,
LAPLACE,
LIN,
LOG,
Expand All @@ -37,7 +36,7 @@
Problem,
)
from .distributions import *
from .parameters import scale, unscale
from .parameters import _is_estimated, scale, unscale

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we import it here, should we make it a public function?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's still (package)private.


__all__ = ["priors_to_measurements"]

Expand Down Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions petab/v1/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"""
Expand Down
3 changes: 2 additions & 1 deletion petab/v1/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading