Skip to content

Commit 4d2f3a8

Browse files
ricardoV94michaelosthege
authored andcommitted
Fallback to Aeppl when logp is not implemented
1 parent 7d7d07c commit 4d2f3a8

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

pymc/distributions/logprob.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,11 +269,23 @@ def joint_logpt(
269269
return logp_var
270270

271271

272-
def logp(rv, value):
272+
def logp(rv: TensorVariable, value) -> TensorVariable:
273273
"""Return the log-probability graph of a Random Variable"""
274274

275275
value = at.as_tensor_variable(value, dtype=rv.dtype)
276-
return logp_aeppl(rv, value)
276+
try:
277+
return logp_aeppl(rv, value)
278+
except NotImplementedError:
279+
try:
280+
value = rv.type.filter_variable(value)
281+
except TypeError as exc:
282+
raise TypeError(
283+
"When RV is not a pure distribution, value variable must have the same type"
284+
) from exc
285+
try:
286+
return factorized_joint_logprob({rv: value}, warn_missing_rvs=False)[value]
287+
except Exception as exc:
288+
raise NotImplementedError("PyMC could not infer logp of input variable.") from exc
277289

278290

279291
def logcdf(rv, value):

pymc/tests/test_logprob.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,13 @@
3131

3232
from pymc import DensityDist
3333
from pymc.aesaraf import floatX, walk_model
34-
from pymc.distributions.continuous import HalfFlat, Normal, TruncatedNormal, Uniform
34+
from pymc.distributions.continuous import (
35+
HalfFlat,
36+
LogNormal,
37+
Normal,
38+
TruncatedNormal,
39+
Uniform,
40+
)
3541
from pymc.distributions.discrete import Bernoulli
3642
from pymc.distributions.logprob import (
3743
_get_scaling,
@@ -235,6 +241,21 @@ def test_logp_helper():
235241
np.testing.assert_almost_equal(x_logp.eval(), sp.norm(0, 1).logpdf([0, 1]))
236242

237243

244+
def test_logp_helper_derived_rv():
245+
assert np.isclose(
246+
logp(at.exp(Normal.dist()), 5).eval(),
247+
logp(LogNormal.dist(), 5).eval(),
248+
)
249+
250+
251+
def test_logp_helper_exceptions():
252+
with pytest.raises(TypeError, match="When RV is not a pure distribution"):
253+
logp(at.exp(Normal.dist()), [1, 2])
254+
255+
with pytest.raises(NotImplementedError, match="PyMC could not infer logp of input variable"):
256+
logp(at.cos(Normal.dist()), 1)
257+
258+
238259
def test_logcdf_helper():
239260
value = at.vector("value")
240261
x = Normal.dist(0, 1)

0 commit comments

Comments
 (0)