Skip to content

Commit fe04045

Browse files
committed
Add @addlogprob! macro (#143)
This PR tries to address the inconvenience for users having to know about the internal variable `_varinfo` and writing `Turing.acclogp!(_varinfo, myvalue)` to modify the accumulated joint log probability by adding a `@addlogprob!` macro which allows to simply write `@addlogprob!(myvalue)`. In particular, it addresses TuringLang/Turing.jl#1332 (comment) (partly, the documentation still has to be updated) and might have avoided the discussion in TuringLang/Turing.jl#1328. BTW, this macro is quite different from the removed `@logprob` and `@varinfo` macros since it is a "proper" Julia macro that is not replaced or touched by the DynamicPPL compiler. It might seem natural to call it `@acclogp!` (since it just adds a call to `acclogp!`) but IMO a more descriptive name (such as `@addlogprob!`?) might be more intuitive for users.
1 parent cecfc99 commit fe04045

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

src/DynamicPPL.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ export AbstractVarInfo,
9393
@logprob_str,
9494
# Convenience functions
9595
logprior,
96-
logjoint
96+
logjoint,
97+
# Convenience macros
98+
@addlogprob!
9799

98100
# Reexport
99101
using Distributions: loglikelihood

src/utils.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,14 @@
1+
"""
2+
@addlogprob!(ex)
3+
4+
Add the result of the evaluation of `ex` to the joint log probability.
5+
"""
6+
macro addlogprob!(ex)
7+
return quote
8+
acclogp!($(esc(:(_varinfo))), $(esc(ex)))
9+
end
10+
end
11+
112
"""
213
getargs_dottilde(x)
314

test/utils.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,20 @@ using DynamicPPL: getargs_dottilde, getargs_tilde
33

44
using Test
55

6+
@testset "addlogprob!" begin
7+
@model function testmodel()
8+
global lp_before = getlogp(_varinfo)
9+
@addlogprob!(42)
10+
global lp_after = getlogp(_varinfo)
11+
end
12+
13+
model = testmodel()
14+
varinfo = DynamicPPL.VarInfo(model)
15+
model(varinfo)
16+
@test iszero(lp_before)
17+
@test getlogp(varinfo) == lp_after == 42
18+
end
19+
620
@testset "getargs_dottilde" begin
721
# Some things that are not expressions.
822
@test getargs_dottilde(:x) === nothing

0 commit comments

Comments
 (0)