diff --git a/python/celerite2/pymc/distribution.py b/python/celerite2/pymc/distribution.py index 629925b..1a5c874 100644 --- a/python/celerite2/pymc/distribution.py +++ b/python/celerite2/pymc/distribution.py @@ -18,7 +18,7 @@ def safe_celerite_normal(rng, mean, norm, t, c, U, W, d, size=None): - if size is None: + if size is None or len(size) == 0: shape = (mean.shape[0], 1) out_shape = mean.shape[0] else: @@ -58,20 +58,13 @@ def rng_fn(cls, rng, mean, norm, t, c, U, W, d, size): size = tuple(size or ()) if size: - if ( - 0 < mean.ndim - 1 <= len(size) - and size[-mean.ndim + 1 :] != mean.shape[:-1] - ): - raise ValueError( - "shape mismatch: objects cannot be broadcast to a single shape" - ) mean = np.broadcast_to(mean, size + mean.shape[-1:]) norm = np.broadcast_to(norm, size) t = np.broadcast_to(t, size + t.shape[-1:]) c = np.broadcast_to(c, size + c.shape[-1:]) U = np.broadcast_to(U, size + U.shape[-2:]) W = np.broadcast_to(W, size + W.shape[-2:]) - d = np.broadcast_to(d, size + d.shape[-2:]) + d = np.broadcast_to(d, size + d.shape[-1:]) res = np.empty(mean.shape) for idx in np.ndindex(mean.shape[:-1]): diff --git a/python/test/pymc/test_pymc_distribution_size.py b/python/test/pymc/test_pymc_distribution_size.py new file mode 100644 index 0000000..25e9707 --- /dev/null +++ b/python/test/pymc/test_pymc_distribution_size.py @@ -0,0 +1,48 @@ +import numpy as np +import pytest + +pytest.importorskip("celerite2.pymc") + +from celerite2.pymc import GaussianProcess, terms + + +@pytest.mark.parametrize("size", [(1,), (4,), (2, 3)]) +def test_marginal_sample_size(size): + pm = pytest.importorskip("pymc") + t = np.linspace(0.0, 10.0, 8) + kernel = terms.SHOTerm(sigma=1.0, rho=2.0, Q=1.5) + + with pm.Model(): + gp = GaussianProcess(kernel, t=t, diag=0.1) + sample = pm.draw(gp.marginal("obs", size=size), random_seed=40582) + + with pm.Model(): + gp = GaussianProcess(kernel, t=t, diag=0.1) + expected = pm.draw( + gp.marginal("obs"), draws=int(np.prod(size)), random_seed=40582 + ) + + assert sample.shape == size + (len(t),) + np.testing.assert_array_equal(sample, expected.reshape(sample.shape)) + + +def test_marginal_sample_size_posterior_predictive(): + pm = pytest.importorskip("pymc") + t = np.linspace(0.0, 10.0, 8) + with pm.Model(): + offset = pm.Normal("offset", 0.0, 2.0) + gp = GaussianProcess( + terms.SHOTerm(sigma=1.0, rho=2.0, Q=1.5), + t=t, + diag=0.1, + mean=offset, + ) + gp.marginal("obs", observed=np.sin(t)) + sample = pm.sample_posterior_predictive( + [{"offset": np.array(0.0)}, {"offset": np.array(0.0)}], + random_seed=40582, + return_inferencedata=False, + progressbar=False, + )["obs"] + assert sample.shape == (1, 2, len(t)) + assert np.all(np.isfinite(sample))