@@ -6,6 +6,67 @@ const NO_DEFAULT = NoDefault()
66 @addlogprob!(ex)
77
88Add the result of the evaluation of `ex` to the joint log probability.
9+
10+ # Examples
11+
12+ This macro allows you to [include arbitrary terms in the likelihood](https://github.com/TuringLang/Turing.jl/issues/1332)
13+
14+ ```jldoctest; setup = :(using Distributions)
15+ julia> myloglikelihood(x, μ) = loglikelihood(Normal(μ, 1), x);
16+
17+ julia> @model function demo(x)
18+ μ ~ Normal()
19+ @addlogprob! myloglikelihood(x, μ)
20+ end;
21+
22+ julia> x = [1.3, -2.1];
23+
24+ julia> loglikelihood(demo(x), (μ=0.2,)) ≈ myloglikelihood(x, 0.2)
25+ true
26+ ```
27+
28+ and to [reject samples](https://github.com/TuringLang/Turing.jl/issues/1328):
29+
30+ ```jldoctest; setup = :(using Distributions, LinearAlgebra)
31+ julia> @model function demo(x)
32+ m ~ MvNormal(zero(x), I)
33+ if dot(m, x) < 0
34+ @addlogprob! -Inf
35+ # Exit the model evaluation early
36+ return
37+ end
38+ x ~ MvNormal(m, I)
39+ return
40+ end;
41+
42+ julia> logjoint(demo([-2.1]), (m=[0.2],)) == -Inf
43+ true
44+ ```
45+
46+ !!! note
47+ The `@addlogprob!` macro increases the accumulated log probability regardless of the evaluation context,
48+ i.e., regardless of whether you evaluate the log prior, the log likelihood or the log joint density.
49+ If you would like to avoid this behaviour you should check the evaluation context.
50+ It can be accessed with the internal variable `__context__`.
51+ For instance, in the following example the log density is not accumulated when only the log prior is computed:
52+ ```jldoctest; setup = :(using Distributions)
53+ julia> myloglikelihood(x, μ) = loglikelihood(Normal(μ, 1), x);
54+
55+ julia> @model function demo(x)
56+ μ ~ Normal()
57+ if DynamicPPL.leafcontext(__context__) !== PriorContext()
58+ @addlogprob! myloglikelihood(x, μ)
59+ end
60+ end;
61+
62+ julia> x = [1.3, -2.1];
63+
64+ julia> logprior(demo(x), (μ=0.2,)) ≈ logpdf(Normal(), 0.2)
65+ true
66+
67+ julia> loglikelihood(demo(x), (μ=0.2,)) ≈ myloglikelihood(x, 0.2)
68+ true
69+ ```
970"""
1071macro addlogprob! (ex)
1172 return quote
0 commit comments