Skip to content

Add MvNormal moment #5171

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Nov 16, 2021
14 changes: 13 additions & 1 deletion pymc/distributions/multivariate.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import aesara
import aesara.tensor as at
from aesara.tensor.extra_ops import broadcast_shape
import numpy as np
import scipy

Expand All @@ -46,7 +47,11 @@
from pymc.distributions.continuous import ChiSquared, Normal, assert_negative_support
from pymc.distributions.dist_math import bound, factln, logpow, multigammaln
from pymc.distributions.distribution import Continuous, Discrete
from pymc.distributions.shape_utils import broadcast_dist_samples_to, to_tuple
from pymc.distributions.shape_utils import (
broadcast_dist_samples_to,
rv_size_is_none,
to_tuple
)
from pymc.math import kron_diag, kron_dot

__all__ = [
Expand Down Expand Up @@ -224,6 +229,13 @@ def dist(cls, mu, cov=None, tau=None, chol=None, lower=True, **kwargs):
cov = quaddist_matrix(cov, chol, tau, lower)
return super().dist([mu, cov], **kwargs)

def get_moment(rv, size, mu, cov):
moment = mu
if not rv_size_is_none(size):
m_size = at.concatenate([size, mu.shape])
moment = at.full(m_size, mu)
return moment

def logp(value, mu, cov):
"""
Calculate log-probability of Multivariate Normal distribution
Expand Down
16 changes: 16 additions & 0 deletions pymc/tests/test_distributions_moments.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
ZeroInflatedBinomial,
ZeroInflatedPoisson,
)
from pymc.distributions.multivariate import MvNormal
from pymc.distributions.shape_utils import rv_size_is_none
from pymc.initial_point import make_initial_point_fn
from pymc.model import Model
Expand Down Expand Up @@ -595,3 +596,18 @@ def test_discrete_uniform_moment(lower, upper, size, expected):
with Model() as model:
DiscreteUniform("x", lower=lower, upper=upper, size=size)
assert_moment_is_expected(model, expected)


@pytest.mark.parametrize(
"mu, cov, size, expected",
[
(np.array([1.]), np.array([[1.]]), None, np.array([1.])),
(np.ones((10, )), np.identity(10), None, np.ones((10, ))),
(np.ones(2), np.identity(2), 4, np.ones((4, 2))),
(np.ones(2), np.identity(2), (4, 2), np.ones((4, 2, 2))),
]
)
def test_mv_normal_moment(mu, cov, size, expected):
with Model() as model:
MvNormal("x", mu=mu, cov=cov, size=size)
assert_moment_is_expected(model, expected)