Skip to content

Commit 799768f

Browse files
dweindlclaude
andcommitted
v2: handle infinite parameter bounds (PEtab 2.0 erratum E1)
PEtab 2.0.0 erratum E1 allows `lowerBound=-inf` and `upperBound=inf`. If any estimated parameter has a prior, estimated parameters with infinite bounds require an explicit proper prior, since the default `uniform(lowerBound, upperBound)` prior would be improper. * `Parameter.lb` must be finite or `-inf`, `Parameter.ub` finite or `inf`. Errors refer to the `lowerBound`/`upperBound` columns. * `CheckPriorDistribution` reports estimated parameters with infinite bounds and no prior if the problem has a MAP objective. * `Problem.get_startpoint_distributions` raises a `ValueError` naming estimated parameters with infinite or missing bounds and no prior, instead of returning improper uniform distributions. `get_priors` delegates to it for MAP problems. * `Problem.sample_parameter_startpoints` used `get_priors`, which is empty for maximum likelihood problems, and thus failed. It now uses `get_startpoint_distributions`, returns an `(n_starts, 0)` array if no parameters are estimated, and no longer accepts and ignores arbitrary keyword arguments. * Test that prior truncation at bounds matching the prior's domain is a no-op, and that one-sided infinite bounds still truncate. Closes #565. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4329d1b commit 799768f

6 files changed

Lines changed: 268 additions & 22 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Validate infinite parameter bounds according to PEtab 2.0 erratum E1:
2+
`lowerBound=inf` and `upperBound=-inf` are rejected; if any estimated
3+
parameter has a prior, estimated parameters with infinite bounds
4+
require an explicit prior, which is now checked by `petablint`.
5+
`Problem.get_priors` and `Problem.get_startpoint_distributions` raise a
6+
`ValueError` naming estimated parameters with infinite bounds and no
7+
prior
8+
([#601](https://github.com/PEtab-dev/libpetab-python/pull/601))
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
`petab.v2.Problem.sample_parameter_startpoints` no longer fails for
2+
maximum likelihood problems or problems without estimated parameters,
3+
and no longer accepts and ignores arbitrary keyword arguments
4+
([#601](https://github.com/PEtab-dev/libpetab-python/pull/601))

‎petab/v2/core.py‎

Lines changed: 65 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -87,18 +87,30 @@
8787
logger = logging.getLogger(__name__)
8888

8989

90-
def _is_finite_or_neg_inf(v: float, info: ValidationInfo) -> float:
91-
if not np.isfinite(v) and v != -np.inf:
90+
def _field_to_column(info: ValidationInfo) -> str:
91+
"""The PEtab column name for the validated field."""
92+
return {"lb": C.LOWER_BOUND, "ub": C.UPPER_BOUND}.get(
93+
info.field_name, info.field_name
94+
)
95+
96+
97+
def _is_finite_or_neg_inf(
98+
v: float | None, info: ValidationInfo
99+
) -> float | None:
100+
if v is not None and not np.isfinite(v) and v != -np.inf:
92101
raise ValueError(
93-
f"{info.field_name} value must be finite or -inf but got {v}"
102+
f"{_field_to_column(info)} value must be finite or -inf "
103+
f"but got {v}"
94104
)
95105
return v
96106

97107

98-
def _is_finite_or_pos_inf(v: float, info: ValidationInfo) -> float:
99-
if not np.isfinite(v) and v != np.inf:
108+
def _is_finite_or_pos_inf(
109+
v: float | None, info: ValidationInfo
110+
) -> float | None:
111+
if v is not None and not np.isfinite(v) and v != np.inf:
100112
raise ValueError(
101-
f"{info.field_name} value must be finite or inf but got {v}"
113+
f"{_field_to_column(info)} value must be finite or inf but got {v}"
102114
)
103115
return v
104116

@@ -1061,13 +1073,17 @@ class Parameter(BaseModel):
10611073
alias=C.PARAMETER_NAME, default=None
10621074
)
10631075
#: Lower bound.
1064-
lb: Annotated[float | None, BeforeValidator(_convert_nan_to_none)] = Field(
1065-
alias=C.LOWER_BOUND, default=None
1066-
)
1076+
lb: Annotated[
1077+
float | None,
1078+
BeforeValidator(_convert_nan_to_none),
1079+
AfterValidator(_is_finite_or_neg_inf),
1080+
] = Field(alias=C.LOWER_BOUND, default=None)
10671081
#: Upper bound.
1068-
ub: Annotated[float | None, BeforeValidator(_convert_nan_to_none)] = Field(
1069-
alias=C.UPPER_BOUND, default=None
1070-
)
1082+
ub: Annotated[
1083+
float | None,
1084+
BeforeValidator(_convert_nan_to_none),
1085+
AfterValidator(_is_finite_or_pos_inf),
1086+
] = Field(alias=C.UPPER_BOUND, default=None)
10711087
#: Nominal value.
10721088
nominal_value: Annotated[
10731089
# PEtab SciML supports arrays via "array" nominal values
@@ -2102,6 +2118,17 @@ def has_ml_objective(self) -> bool:
21022118
"""
21032119
return not self.has_map_objective
21042120

2121+
def _get_unbounded_ids_without_prior(self) -> list[str]:
2122+
"""IDs of estimated parameters with infinite or missing bounds and
2123+
no prior."""
2124+
return [
2125+
p.id
2126+
for p in self.parameters
2127+
if p.estimate
2128+
and p.prior_distribution is None
2129+
and any(b is None or np.isinf(b) for b in (p.lb, p.ub))
2130+
]
2131+
21052132
def get_priors(self) -> dict[str, Distribution]:
21062133
"""Get prior distributions.
21072134
@@ -2110,15 +2137,13 @@ def get_priors(self) -> dict[str, Distribution]:
21102137
21112138
:returns: The prior distributions for the estimated parameters in case
21122139
the problem has a MAP objective, an empty dictionary otherwise.
2140+
:raises ValueError: If an estimated parameter without prior has an
2141+
infinite or missing bound.
21132142
"""
21142143
if not self.has_map_objective:
21152144
return {}
21162145

2117-
return {
2118-
p.id: p.prior_dist if p.prior_distribution else Uniform(p.lb, p.ub)
2119-
for p in self.parameters
2120-
if p.estimate
2121-
}
2146+
return self.get_startpoint_distributions()
21222147

21232148
def get_startpoint_distributions(self) -> dict[str, Distribution]:
21242149
"""Get distributions for sampling startpoints.
@@ -2130,17 +2155,36 @@ def get_startpoint_distributions(self) -> dict[str, Distribution]:
21302155
21312156
:returns: Mapping of parameter IDs to distributions for sampling
21322157
startpoints.
2158+
:raises ValueError: If an estimated parameter without prior has an
2159+
infinite or missing bound.
21332160
"""
2161+
if unbounded := self._get_unbounded_ids_without_prior():
2162+
raise ValueError(
2163+
"The default uniform distribution is undefined for estimated "
2164+
"parameters with infinite or missing bounds and no prior: "
2165+
f"{unbounded}."
2166+
)
2167+
21342168
return {
21352169
p.id: p.prior_dist if p.prior_distribution else Uniform(p.lb, p.ub)
21362170
for p in self.parameters
21372171
if p.estimate
21382172
}
21392173

2140-
def sample_parameter_startpoints(self, n_starts: int = 100, **kwargs):
2141-
"""Create 2D array with starting points for optimization"""
2142-
priors = self.get_priors()
2143-
return np.vstack([p.sample(n_starts) for p in priors.values()]).T
2174+
def sample_parameter_startpoints(self, n_starts: int = 100) -> np.ndarray:
2175+
"""Create 2D array with starting points for optimization.
2176+
2177+
:param n_starts: Number of starting points.
2178+
:returns: Array of shape ``(n_starts, n_estimated)`` with columns
2179+
ordered as :attr:`x_free_ids`.
2180+
:raises ValueError: See :meth:`get_startpoint_distributions`.
2181+
"""
2182+
distributions = self.get_startpoint_distributions()
2183+
if not distributions:
2184+
return np.empty((n_starts, 0))
2185+
return np.vstack(
2186+
[d.sample(n_starts) for d in distributions.values()]
2187+
).T
21442188

21452189
def sample_parameter_startpoints_dict(
21462190
self, n_starts: int = 100

‎petab/v2/lint.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,18 @@ class CheckPriorDistribution(ValidationTask):
898898

899899
def run(self, problem: Problem) -> ValidationIssue | None:
900900
messages = []
901+
902+
# The default uniform(lowerBound, upperBound) prior is improper for
903+
# infinite bounds
904+
if problem.has_map_objective and (
905+
unbounded := problem._get_unbounded_ids_without_prior()
906+
):
907+
messages.append(
908+
"If any estimated parameter has a prior, all estimated "
909+
"parameters with infinite bounds require an explicit proper "
910+
f"prior, but the following parameters have none: {unbounded}."
911+
)
912+
901913
for parameter in problem.parameters:
902914
if parameter.prior_distribution is None:
903915
continue

‎tests/v2/test_core.py‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from sympy.abc import x, y
1212

1313
import petab.v2 as petab
14+
from petab.v1.distributions import Normal
1415
from petab.v2 import C
1516
from petab.v2.C import (
1617
CONDITION_ID,
@@ -379,6 +380,17 @@ def test_parameter():
379380
with pytest.raises(ValidationError, match="less than"):
380381
Parameter(id="k1", lb=2, ub=1)
381382

383+
# infinite bounds
384+
Parameter(id="k1", lb=-np.inf, ub=np.inf)
385+
Parameter(id="k1", lb="-inf", ub="inf")
386+
with pytest.raises(ValidationError, match="lowerBound .* finite or -inf"):
387+
Parameter(id="k1", lb=np.inf, ub=np.inf)
388+
with pytest.raises(ValidationError, match="upperBound .* finite or inf"):
389+
Parameter(id="k1", lb=-np.inf, ub=-np.inf)
390+
p = Parameter(id="k1", lb=0, ub=1)
391+
with pytest.raises(ValidationError, match="finite or inf"):
392+
p.ub = -np.inf
393+
382394
assert Parameter(
383395
id="k1", estimate=True, lb=1, ub=2, prior_parameters=[1, 2]
384396
).model_dump() == {
@@ -741,6 +753,142 @@ def test_sample_startpoint_shape():
741753
assert sp.shape == (n_starts, 2)
742754

743755

756+
def test_sample_startpoints_ml():
757+
"""Test startpoint sampling for maximum likelihood problems."""
758+
problem = Problem()
759+
problem += Parameter(id="p1", estimate=True, lb=1, ub=2)
760+
problem += Parameter(id="p2", estimate=True, lb=3, ub=4)
761+
assert problem.has_ml_objective
762+
763+
sp = problem.sample_parameter_startpoints(n_starts=10)
764+
assert sp.shape == (10, 2)
765+
assert np.all((sp[:, 0] >= 1) & (sp[:, 0] <= 2))
766+
assert np.all((sp[:, 1] >= 3) & (sp[:, 1] <= 4))
767+
768+
# infinite bounds require a prior for sampling startpoints
769+
problem += Parameter(id="p3", estimate=True, lb=0, ub=np.inf)
770+
with pytest.raises(ValueError, match=r"missing bounds.*\['p3'\]"):
771+
problem.get_startpoint_distributions()
772+
with pytest.raises(ValueError, match=r"missing bounds.*\['p3'\]"):
773+
problem.sample_parameter_startpoints()
774+
# ML problem: no priors
775+
assert problem.get_priors() == {}
776+
777+
problem["p3"].prior_distribution = C.LOG_NORMAL
778+
problem["p3"].prior_parameters = [0, 1]
779+
sp = problem.sample_parameter_startpoints(n_starts=10)
780+
assert sp.shape == (10, 3)
781+
assert np.all(sp[:, 2] > 0)
782+
783+
# missing bounds (bypassing validation) are reported like infinite ones
784+
problem += Parameter.model_construct(id="p4", estimate=True)
785+
with pytest.raises(ValueError, match=r"missing bounds.*\['p4'\]"):
786+
problem.get_startpoint_distributions()
787+
788+
789+
def test_sample_startpoints_no_estimated_parameters():
790+
"""Test startpoint sampling without estimated parameters."""
791+
problem = Problem()
792+
problem += Parameter(id="p1", estimate=False, nominal_value=1)
793+
assert problem.sample_parameter_startpoints(n_starts=5).shape == (5, 0)
794+
795+
796+
def test_get_priors_infinite_bounds():
797+
"""Test that infinite bounds without prior are rejected for MAP
798+
problems."""
799+
problem = Problem()
800+
problem += Parameter(id="p1", estimate=True, lb=-np.inf, ub=np.inf)
801+
problem += Parameter(
802+
id="p2",
803+
estimate=True,
804+
lb=1,
805+
ub=2,
806+
prior_distribution=C.NORMAL,
807+
prior_parameters=[1.5, 1],
808+
)
809+
assert problem.has_map_objective
810+
with pytest.raises(ValueError, match=r"missing bounds.*\['p1'\]"):
811+
problem.get_priors()
812+
813+
problem["p1"].prior_distribution = C.NORMAL
814+
problem["p1"].prior_parameters = [0, 1]
815+
assert set(problem.get_priors()) == {"p1", "p2"}
816+
817+
818+
@pytest.mark.parametrize(
819+
"prior_distribution, prior_parameters, lb, ub",
820+
[
821+
(C.NORMAL, [0, 1], -np.inf, np.inf),
822+
(C.LOG_NORMAL, [0, 1], 0, np.inf),
823+
(C.EXPONENTIAL, [2], 0, np.inf),
824+
(C.GAMMA, [2, 1], 0, np.inf),
825+
(C.CHI_SQUARED, [2], 0, np.inf),
826+
(C.RAYLEIGH, [1], 0, np.inf),
827+
(C.LOG_LAPLACE, [0, 1], 0, np.inf),
828+
(C.CAUCHY, [0, 1], -np.inf, np.inf),
829+
(C.LAPLACE, [0, 1], -np.inf, np.inf),
830+
],
831+
)
832+
def test_prior_truncation_noop_at_domain(
833+
prior_distribution, prior_parameters, lb, ub
834+
):
835+
"""Bounds matching the prior's domain do not truncate the prior."""
836+
truncated = Parameter(
837+
id="p",
838+
lb=lb,
839+
ub=ub,
840+
prior_distribution=prior_distribution,
841+
prior_parameters=prior_parameters,
842+
).prior_dist
843+
# reference: the same distribution without truncation
844+
untruncated = type(truncated)(
845+
*prior_parameters,
846+
**({"log": True} if prior_distribution.startswith("log-") else {}),
847+
)
848+
849+
x = np.array([0.1, 0.5, 1.0, 2.0, 5.0])
850+
np.testing.assert_allclose(truncated.pdf(x), untruncated.pdf(x))
851+
np.testing.assert_allclose(truncated.cdf(x), untruncated.cdf(x))
852+
assert np.all(truncated.pdf(x) > 0)
853+
854+
855+
def test_prior_truncation_one_sided_infinite():
856+
"""A finite bound truncates the prior also if the other is infinite."""
857+
truncated = Parameter(
858+
id="p",
859+
lb=1,
860+
ub=np.inf,
861+
prior_distribution=C.LOG_NORMAL,
862+
prior_parameters=[0, 1],
863+
).prior_dist
864+
untruncated = Parameter(
865+
id="p",
866+
lb=0,
867+
ub=np.inf,
868+
prior_distribution=C.LOG_NORMAL,
869+
prior_parameters=[0, 1],
870+
).prior_dist
871+
# median of LogNormal(0, 1) is 1, so truncation at 1 doubles the density
872+
x = np.array([1.5, 2.0, 5.0])
873+
np.testing.assert_allclose(truncated.pdf(x), 2 * untruncated.pdf(x))
874+
assert truncated.pdf(0.5) == 0
875+
assert np.all(truncated.sample(100) >= 1)
876+
877+
# mirrored: finite upper bound
878+
truncated = Parameter(
879+
id="p",
880+
lb=-np.inf,
881+
ub=0,
882+
prior_distribution=C.NORMAL,
883+
prior_parameters=[0, 1],
884+
).prior_dist
885+
untruncated = Normal(0, 1)
886+
x = np.array([-2.0, -1.0, -0.5])
887+
np.testing.assert_allclose(truncated.pdf(x), 2 * untruncated.pdf(x))
888+
assert truncated.pdf(0.5) == 0
889+
assert np.all(truncated.sample(100) <= 0)
890+
891+
744892
def test_problem_config_paths():
745893
"""Test handling of URLS and local paths in ProblemConfig."""
746894

‎tests/v2/test_lint.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import pytest
77

88
from petab.v2 import Problem
9-
from petab.v2.C import TIME_SYMBOL
9+
from petab.v2.C import LOG_NORMAL, NORMAL, TIME_SYMBOL, UNIFORM
1010
from petab.v2.lint import *
1111
from petab.v2.lint import (
1212
get_required_parameters_for_parameter_table,
@@ -290,3 +290,33 @@ def test_check_prior_distribution_invalid_uniform(
290290
assert (error := CheckPriorDistribution().run(problem)) is not None
291291
assert "`p1` are invalid" in error.message
292292
assert hint in error.message
293+
294+
295+
def test_check_prior_distribution_infinite_bounds():
296+
"""Estimated parameters with infinite bounds need a prior if the problem
297+
has a MAP objective."""
298+
problem = Problem()
299+
problem.add_parameter("p1", estimate=True, lb=0, ub=float("inf"))
300+
problem.add_parameter("p2", estimate=True, lb=0, ub=1)
301+
# non-estimated parameters are irrelevant
302+
problem.add_parameter("p3", estimate=False, nominal_value=1)
303+
304+
check = CheckPriorDistribution()
305+
# ML problem: infinite bounds are fine
306+
assert check.run(problem) is None
307+
308+
problem["p2"].prior_distribution = NORMAL
309+
problem["p2"].prior_parameters = [0.5, 1]
310+
assert (error := check.run(problem)) is not None
311+
assert error.level == ValidationIssueSeverity.ERROR
312+
assert "['p1']" in error.message
313+
314+
problem["p1"].prior_distribution = LOG_NORMAL
315+
problem["p1"].prior_parameters = [0, 1]
316+
assert check.run(problem) is None
317+
318+
# improper explicit prior
319+
problem["p1"].prior_distribution = UNIFORM
320+
problem["p1"].prior_parameters = [0, float("inf")]
321+
assert (error := check.run(problem)) is not None
322+
assert "`p1` are invalid" in error.message

0 commit comments

Comments
 (0)