18.5 User-Defined Probability Functions
Probability functions are distinguished in Stan by names ending in
_lpdf
for density functions and _lpmf
for mass
functions; in both cases, they must have real
return types.
Suppose a model uses several standard normal distributions, for which there is not a specific overloaded density nor defaults in Stan. So rather than writing out the location of 0 and scale of 1 for all of them, a new density function may be defined and reused.
functions {
real unit_normal_lpdf(real y) {
return normal_lpdf(y | 0, 1);
}
}
...
model {
alpha ~ unit_normal();
beta ~ unit_normal();
...
}
The ability to use the unit_normal
function as a density is
keyed off its name ending in _lpdf
(names ending in
_lpmf
for probability mass functions work the same way).
In general, if foo_lpdf
is defined to consume \(N + 1\)
arguments, then
y ~ foo(theta1, ..., thetaN);
can be used as shorthand for
target += foo_lpdf(y | theta1, ..., thetaN);
As with the built-in functions, the suffix _lpdf
is dropped and
the first argument moves to the left of the sampling symbol (~
)
in the sampling statement.
Functions ending in _lpmf
(for probability mass functions),
behave exactly the same way. The difference is that the first
argument of a density function (_lpdf
) must be continuous (not
an integer or integer array), whereas the first argument of a mass
function (_lpmf
) must be discrete (integer or integer array).