diff --git a/tests/test_distributions.py b/tests/test_distributions.py index 5326647..d3d0c1c 100644 --- a/tests/test_distributions.py +++ b/tests/test_distributions.py @@ -1,5 +1,6 @@ r"""Tests for the zuko.distributions module.""" +import pytest import torch from torch.distributions import * @@ -59,3 +60,62 @@ def test_distributions() -> None: log_p = d.log_prob(x) assert log_p.shape == d.batch_shape, d + + +@pytest.mark.parametrize( + "base_shape,lower_shape,upper_shape,batch_shape", + [ + ((), (), (), ()), + ((), (3,), (), (3,)), + ((), (), (3,), (3,)), + ((), (2, 1), (3,), (2, 3)), + ((2, 1), (), (3,), (2, 3)), + ((2, 3), (), (), (2, 3)), + ((2, 1), (1, 3), (), (2, 3)), + ], +) +def test_truncated_batch_shape( + base_shape: tuple[int, ...], + lower_shape: tuple[int, ...], + upper_shape: tuple[int, ...], + batch_shape: tuple[int, ...], +) -> None: + base = Normal(torch.zeros(base_shape), torch.ones(base_shape)) + d = Truncated(base, -torch.ones(lower_shape), torch.ones(upper_shape)) + + assert d.batch_shape == batch_shape + + for distribution in (d, d.expand((4,) + batch_shape)): + x = distribution.rsample((5,)) + + assert x.shape == (5,) + distribution.batch_shape + assert distribution.log_prob(x).shape == x.shape + assert distribution.cdf(x).shape == x.shape + assert torch.all((-1 <= x) & (x < 1)) + + +def test_truncated_joint() -> None: + base = Normal(0.0, 1.0) + truncated = Truncated(base, torch.tensor([-1.0, 0.0]), torch.tensor([1.0, 2.0])) + joint = Joint(truncated, base) + x = joint.rsample((5,)) + + assert joint.batch_shape == (2,) + assert x.shape == (5, 2, 2) + assert torch.allclose( + joint.log_prob(x), truncated.log_prob(x[..., 0]) + base.log_prob(x[..., 1]) + ) + + +def test_truncated_mixture() -> None: + base = Normal(0.0, 1.0) + truncated = Truncated(base, torch.tensor([-1.0, 0.0]), torch.tensor([1.0, 2.0])) + mixture = Mixture(truncated, torch.zeros(2)) + x = mixture.sample((5,)) + expected = torch.logsumexp(truncated.log_prob(x.unsqueeze(-1)), dim=-1) - torch.log( + torch.tensor(2.0) + ) + + assert mixture.batch_shape == () + assert x.shape == (5,) + assert torch.allclose(mixture.log_prob(x), expected) diff --git a/zuko/distributions.py b/zuko/distributions.py index 999cb92..7a259cf 100644 --- a/zuko/distributions.py +++ b/zuko/distributions.py @@ -467,7 +467,7 @@ def __repr__(self) -> str: @property def batch_shape(self) -> Size: - return self.base.batch_shape + return self.uniform.batch_shape def expand(self, batch_shape: Size, new: Distribution | None = None) -> Distribution: new = self._get_checked_instance(Truncated, new)