Skip to content

Commit 71091ea

Browse files
dweindlclaude
andauthored
Reject improper Uniform and LogUniform distributions (#604)
`petab.v1.distributions.Uniform` accepted any limits. E.g., `Uniform(0, inf)` has pdf 0 and cdf nan, and 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`. Both raise a `ValueError` otherwise. Affected `petab.v1` use: start point sampling for parameters with infinite bounds, or with `lowerBound=0` and a log-scaled default `parameterScaleUniform` initialization prior. These already failed during sampling; they now fail when the `Prior` is created. `low == high` is also rejected, so an estimated parameter with `lowerBound == upperBound` and no prior can no longer be sampled (v1 and v2). None of the problems in the PEtab benchmark collection are affected. In `petab.v2`, invalid `uniform`/`log-uniform` priors are still reported by `CheckPriorDistribution`, now with a clearer hint. If a `uniform` prior range does not overlap the parameter bounds, the error names the prior parameters and bounds instead of the clipped limits. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3fd2a3f commit 71091ea

5 files changed

Lines changed: 81 additions & 1 deletion

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
`petab.v1.distributions.Uniform` requires finite limits with
2+
`low < high`, and `LogUniform` requires `0 < low < high < inf`.
3+
Both raise `ValueError` otherwise. In `petab.v1`, start point sampling
4+
for parameters with infinite bounds, or with `lowerBound=0` and
5+
log-scaled `parameterScaleUniform` priors, now fails when creating the
6+
`Prior` instead of when sampling. Start points can no longer be sampled
7+
for estimated parameters with `lowerBound == upperBound` and no prior
8+
(v1 and v2)
9+
([#604](https://github.com/PEtab-dev/libpetab-python/pull/604))

‎petab/v1/distributions.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,8 @@ def scale(self) -> float:
381381
class Uniform(Distribution):
382382
"""A (log-)uniform distribution.
383383
384+
The bounds must be finite with ``low < high``.
385+
384386
:param low: The lower bound of the distribution.
385387
:param high: The upper bound of the distribution.
386388
:param log: If ``True``, the distribution is transformed to a log-uniform
@@ -406,6 +408,11 @@ def __init__(
406408
from scipy.stats import uniform
407409
except ImportError as e:
408410
raise ImportError(_SCIPY_IMPORT_ERROR) from e
411+
if not (np.isfinite(low) and np.isfinite(high) and low < high):
412+
raise ValueError(
413+
"Uniform distribution requires finite limits with low < high, "
414+
f"but got low={low}, high={high}."
415+
)
409416
self._dist = uniform
410417
self._low = low
411418
self._high = high
@@ -432,7 +439,7 @@ class LogUniform(Distribution):
432439
433440
A random variable is log-uniformly distributed between ``low`` and ``high``
434441
if its logarithm is uniformly distributed between ``log(low)`` and
435-
``log(high)``.
442+
``log(high)``. The bounds must satisfy ``0 < low < high < inf``.
436443
437444
:param low: The lower bound of the distribution.
438445
:param high: The upper bound of the distribution.
@@ -445,6 +452,11 @@ def __init__(
445452
high: float,
446453
trunc: tuple[float, float] | None = None,
447454
):
455+
if not (0 < low < high < np.inf):
456+
raise ValueError(
457+
"Log-uniform distribution requires 0 < low < high < inf, "
458+
f"but got low={low}, high={high}."
459+
)
448460
try:
449461
from scipy.stats import uniform
450462
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
@@ -148,3 +148,30 @@ def test_trunc_sequence():
148148
assert d._trunc == (-1, 1)
149149
assert d.trunc_low == -1
150150
assert d.trunc_high == 1
151+
152+
153+
@pytest.mark.parametrize(
154+
"low, high",
155+
[
156+
(0, np.inf),
157+
(-np.inf, 0),
158+
(-np.inf, np.inf),
159+
(np.nan, 1),
160+
(1, 1),
161+
(2, 1),
162+
],
163+
)
164+
@pytest.mark.parametrize("log", [False, True, 10])
165+
def test_uniform_invalid_limits(low, high, log):
166+
"""Uniform distributions require finite limits with low < high."""
167+
with pytest.raises(ValueError, match="finite limits"):
168+
Uniform(low, high, log=log)
169+
170+
171+
@pytest.mark.parametrize(
172+
"low, high", [(0, 1), (-1, 1), (1, np.inf), (np.nan, 1), (1, 1), (2, 1)]
173+
)
174+
def test_log_uniform_invalid_limits(low, high):
175+
"""Log-uniform distributions require 0 < low < high < inf."""
176+
with pytest.raises(ValueError, match="0 < low < high < inf"):
177+
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
@@ -264,3 +265,28 @@ def test_check_unused_placeholders():
264265
assert "`obs_c`: noise placeholders `sigma` are not used" in issue.message
265266
assert "offset" not in issue.message
266267
assert "Consider removing them." in issue.message
268+
269+
270+
@pytest.mark.parametrize(
271+
"prior_parameters, lb, ub, hint",
272+
[
273+
([0, float("inf")], 0, float("inf"), "finite limits"),
274+
([0, 1], 2, 3, "do not define a non-empty interval"),
275+
],
276+
)
277+
def test_check_prior_distribution_invalid_uniform(
278+
prior_parameters, lb, ub, hint
279+
):
280+
"""Invalid uniform priors are reported with an informative hint."""
281+
problem = Problem()
282+
problem.add_parameter(
283+
"p1",
284+
estimate=True,
285+
lb=lb,
286+
ub=ub,
287+
prior_dist="uniform",
288+
prior_pars=prior_parameters,
289+
)
290+
assert (error := CheckPriorDistribution().run(problem)) is not None
291+
assert "`p1` are invalid" in error.message
292+
assert hint in error.message

0 commit comments

Comments
 (0)