Modifying the Log Probability

Turing accumulates log probabilities internally in an internal data structure that is accessible through the internal variable __varinfo__ inside of the model definition. To avoid users having to deal with internal data structures, Turing provides the @addlogprob! macro which increases the accumulated log probability. For instance, this allows you to include arbitrary terms in the likelihood

using Turing

myloglikelihood(x, μ) = loglikelihood(Normal(μ, 1), x)

@model function demo(x)
    μ ~ Normal()
    @addlogprob! myloglikelihood(x, μ)
end
demo (generic function with 2 methods)

and to force a sampler to reject a sample:

using Turing
using LinearAlgebra

@model function demo(x)
    m ~ MvNormal(zero(x), I)
    if dot(m, x) < 0
        @addlogprob! -Inf
        # Exit the model evaluation early
        return nothing
    end

    x ~ MvNormal(m, I)
    return nothing
end
demo (generic function with 2 methods)

Note that @addlogprob! (p::Float64) adds p to the log likelihood. If instead you want to add to the log prior, you can use

@addlogprob! (; logprior=value_goes_here)
Back to top