Skip to content

Commit 3883ca9

Browse files
dweindlclaude
andcommitted
Reject improper Uniform and LogUniform distributions
`Uniform` accepted any limits, e.g., `Uniform(0, inf)`, whose pdf is 0, whose cdf is nan, and which fails only when sampled, with numpy's `OverflowError: Range exceeds valid bounds`. `Uniform` now requires finite limits with `low < high` (on the scale of the underlying uniform distribution), and `LogUniform` requires `0 < low < high < inf`. In `petab.v1`, this affects start point sampling for parameters with infinite bounds or with `lowerBound=0` and log-scaled `parameterScaleUniform` priors. These already failed during sampling; they now fail when the `Prior` is created. Estimated parameters with `lowerBound == upperBound` and no prior can no longer be sampled. In `petab.v2`, `Parameter.prior_dist` reports the original prior parameters and bounds if a `uniform` prior does not overlap the parameter bounds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7580974 commit 3883ca9

5 files changed

Lines changed: 80 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,15 @@
99
Require `numpy>=2.2`, and for the `vis` extra, `matplotlib>=3.10` and
1010
`scipy>=1.15`
1111
(by @dweindl in https://github.com/PEtab-dev/libpetab-python/pull/578)
12+
* `petab.v1.distributions.Uniform` requires finite limits with
13+
`low < high`, and `LogUniform` requires `0 < low < high < inf`.
14+
Both raise `ValueError` otherwise. In `petab.v1`, start point sampling
15+
for parameters with infinite bounds, or with `lowerBound=0` and
16+
log-scaled `parameterScaleUniform` priors, now fails when creating the
17+
`Prior` instead of when sampling. Start points can no longer be sampled
18+
for estimated parameters with `lowerBound == upperBound` and no prior
19+
(v1 and v2)
20+
(by @dweindl in https://github.com/PEtab-dev/libpetab-python/pull/604)
1221

1322
## 0.10 series
1423

‎petab/v1/distributions.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,7 @@ class Uniform(Distribution):
386386
If ``False``, no transformation is applied.
387387
If a transformation is applied, the lower and upper bounds are the
388388
lower and upper bounds of the underlying uniform distribution.
389+
The bounds must be finite with ``low < high``.
389390
Note that this differs from the usual definition of a log-uniform
390391
distribution, where the logarithm of the variable is uniformly
391392
distributed between the logarithms of the bounds (see also
@@ -403,6 +404,11 @@ def __init__(
403404
from scipy.stats import uniform
404405
except ImportError as e:
405406
raise ImportError(_SCIPY_IMPORT_ERROR) from e
407+
if not (np.isfinite(low) and np.isfinite(high) and low < high):
408+
raise ValueError(
409+
"Uniform distribution requires finite limits with low < high, "
410+
f"but got low={low}, high={high}."
411+
)
406412
self._dist = uniform
407413
self._low = low
408414
self._high = high
@@ -433,6 +439,7 @@ class LogUniform(Distribution):
433439
434440
:param low: The lower bound of the distribution.
435441
:param high: The upper bound of the distribution.
442+
The bounds must satisfy ``0 < low < high < inf``.
436443
:param trunc: The truncation limits of the distribution.
437444
"""
438445

@@ -442,6 +449,11 @@ def __init__(
442449
high: float,
443450
trunc: tuple[float, float] | None = None,
444451
):
452+
if not (0 < low < high < np.inf):
453+
raise ValueError(
454+
"Log-uniform distribution requires 0 < low < high < inf, "
455+
f"but got low={low}, high={high}."
456+
)
445457
try:
446458
from scipy.stats import uniform
447459
except ImportError as e:

‎petab/v2/core.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,6 +1209,12 @@ def prior_dist(self) -> Distribution | None:
12091209
# `Uniform.__init__` does not accept the `trunc` parameter
12101210
low = max(self.prior_parameters[0], self.lb)
12111211
high = min(self.prior_parameters[1], self.ub)
1212+
if low >= high:
1213+
raise ValueError(
1214+
f"Uniform prior parameters {self.prior_parameters} and "
1215+
f"bounds [{self.lb}, {self.ub}] of parameter `{self.id}' "
1216+
"do not define a non-empty interval."
1217+
)
12121218
return cls(low, high)
12131219

12141220
if cls == LogUniform:

‎tests/v1/test_distributions.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,30 @@ def test_log_uniform():
132132
assert dist.pdf(1) > 0
133133
assert dist.pdf(2) > 0
134134
assert dist.pdf(3) == 0
135+
136+
137+
@pytest.mark.parametrize(
138+
"low, high",
139+
[
140+
(0, np.inf),
141+
(-np.inf, 0),
142+
(-np.inf, np.inf),
143+
(np.nan, 1),
144+
(1, 1),
145+
(2, 1),
146+
],
147+
)
148+
@pytest.mark.parametrize("log", [False, True, 10])
149+
def test_uniform_invalid_limits(low, high, log):
150+
"""Uniform distributions require finite limits with low < high."""
151+
with pytest.raises(ValueError, match="finite limits"):
152+
Uniform(low, high, log=log)
153+
154+
155+
@pytest.mark.parametrize(
156+
"low, high", [(0, 1), (-1, 1), (1, np.inf), (np.nan, 1), (1, 1), (2, 1)]
157+
)
158+
def test_log_uniform_invalid_limits(low, high):
159+
"""Log-uniform distributions require 0 < low < high < inf."""
160+
with pytest.raises(ValueError, match="0 < low < high < inf"):
161+
LogUniform(low, high)

‎tests/v2/test_lint.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from copy import deepcopy
44

55
import pysb
6+
import pytest
67

78
from petab.v2 import Problem
89
from petab.v2.C import TIME_SYMBOL
@@ -218,3 +219,28 @@ def test_time_in_observable_formula_not_a_parameter(clean_pysb_exports):
218219
assert TIME_SYMBOL not in problem.get_output_parameters()
219220
check = CheckAllParametersPresentInParameterTable()
220221
assert (error := check.run(problem)) is None, error
222+
223+
224+
@pytest.mark.parametrize(
225+
"prior_parameters, lb, ub, hint",
226+
[
227+
([0, float("inf")], 0, float("inf"), "finite limits"),
228+
([0, 1], 2, 3, "do not define a non-empty interval"),
229+
],
230+
)
231+
def test_check_prior_distribution_invalid_uniform(
232+
prior_parameters, lb, ub, hint
233+
):
234+
"""Invalid uniform priors are reported with an informative hint."""
235+
problem = Problem()
236+
problem.add_parameter(
237+
"p1",
238+
estimate=True,
239+
lb=lb,
240+
ub=ub,
241+
prior_dist="uniform",
242+
prior_pars=prior_parameters,
243+
)
244+
assert (error := CheckPriorDistribution().run(problem)) is not None
245+
assert "`p1` are invalid" in error.message
246+
assert hint in error.message

0 commit comments

Comments
 (0)