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
9 changes: 9 additions & 0 deletions changelog.d/+uniform-proper.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
`petab.v1.distributions.Uniform` requires finite limits with
`low < high`, and `LogUniform` requires `0 < low < high < inf`.
Both raise `ValueError` otherwise. In `petab.v1`, start point sampling
for parameters with infinite bounds, or with `lowerBound=0` and
log-scaled `parameterScaleUniform` priors, now fails when creating the
`Prior` instead of when sampling. Start points can no longer be sampled
for estimated parameters with `lowerBound == upperBound` and no prior
(v1 and v2)
([#604](https://github.com/PEtab-dev/libpetab-python/pull/604))
14 changes: 13 additions & 1 deletion petab/v1/distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,8 @@ def scale(self) -> float:
class Uniform(Distribution):
"""A (log-)uniform distribution.

The bounds must be finite with ``low < high``.

:param low: The lower bound of the distribution.
:param high: The upper bound of the distribution.
:param log: If ``True``, the distribution is transformed to a log-uniform
Expand All @@ -406,6 +408,11 @@ def __init__(
from scipy.stats import uniform
except ImportError as e:
raise ImportError(_SCIPY_IMPORT_ERROR) from e
if not (np.isfinite(low) and np.isfinite(high) and low < high):
raise ValueError(
"Uniform distribution requires finite limits with low < high, "
f"but got low={low}, high={high}."
)
self._dist = uniform
self._low = low
self._high = high
Expand All @@ -432,7 +439,7 @@ class LogUniform(Distribution):

A random variable is log-uniformly distributed between ``low`` and ``high``
if its logarithm is uniformly distributed between ``log(low)`` and
``log(high)``.
``log(high)``. The bounds must satisfy ``0 < low < high < inf``.

:param low: The lower bound of the distribution.
:param high: The upper bound of the distribution.
Expand All @@ -445,6 +452,11 @@ def __init__(
high: float,
trunc: tuple[float, float] | None = None,
):
if not (0 < low < high < np.inf):
raise ValueError(
"Log-uniform distribution requires 0 < low < high < inf, "
f"but got low={low}, high={high}."
)
try:
from scipy.stats import uniform
except ImportError as e:
Expand Down
6 changes: 6 additions & 0 deletions petab/v2/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,12 @@ def prior_dist(self) -> Distribution | None:
# `Uniform.__init__` does not accept the `trunc` parameter
low = max(self.prior_parameters[0], self.lb)
high = min(self.prior_parameters[1], self.ub)
if low >= high:
raise ValueError(
f"Uniform prior parameters {self.prior_parameters} and "
f"bounds [{self.lb}, {self.ub}] of parameter `{self.id}' "
"do not define a non-empty interval."
)
return cls(low, high)

if cls == LogUniform:
Expand Down
27 changes: 27 additions & 0 deletions tests/v1/test_distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,30 @@ def test_trunc_sequence():
assert d._trunc == (-1, 1)
assert d.trunc_low == -1
assert d.trunc_high == 1


@pytest.mark.parametrize(
"low, high",
[
(0, np.inf),
(-np.inf, 0),
(-np.inf, np.inf),
(np.nan, 1),
(1, 1),
(2, 1),
],
)
@pytest.mark.parametrize("log", [False, True, 10])
def test_uniform_invalid_limits(low, high, log):
"""Uniform distributions require finite limits with low < high."""
with pytest.raises(ValueError, match="finite limits"):
Uniform(low, high, log=log)


@pytest.mark.parametrize(
"low, high", [(0, 1), (-1, 1), (1, np.inf), (np.nan, 1), (1, 1), (2, 1)]
)
def test_log_uniform_invalid_limits(low, high):
"""Log-uniform distributions require 0 < low < high < inf."""
with pytest.raises(ValueError, match="0 < low < high < inf"):
LogUniform(low, high)
26 changes: 26 additions & 0 deletions tests/v2/test_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from copy import deepcopy

import pysb
import pytest

from petab.v2 import Problem
from petab.v2.C import TIME_SYMBOL
Expand Down Expand Up @@ -264,3 +265,28 @@ def test_check_unused_placeholders():
assert "`obs_c`: noise placeholders `sigma` are not used" in issue.message
assert "offset" not in issue.message
assert "Consider removing them." in issue.message


@pytest.mark.parametrize(
"prior_parameters, lb, ub, hint",
[
([0, float("inf")], 0, float("inf"), "finite limits"),
([0, 1], 2, 3, "do not define a non-empty interval"),
],
)
def test_check_prior_distribution_invalid_uniform(
prior_parameters, lb, ub, hint
):
"""Invalid uniform priors are reported with an informative hint."""
problem = Problem()
problem.add_parameter(
"p1",
estimate=True,
lb=lb,
ub=ub,
prior_dist="uniform",
prior_pars=prior_parameters,
)
assert (error := CheckPriorDistribution().run(problem)) is not None
assert "`p1` are invalid" in error.message
assert hint in error.message
Loading