I would like to fit distributions implemented in R packages in rstan
. I know that one can use custom distributions if they are implemented directly:
https://mc-stan.org/docs/2_18/stan-users-guide/custom-probability-functions-chapter.html
However, I wonder if one can use distributions from other packages. For example, I want to use the variance-gamma distribution from the VarianceGamma
package.
dvg(x, vgC , sigma , theta , nu )
How can I define the log density function, say, vg_lpdf()
using the already available implementation in dvg(x, vgC , sigma , theta , nu , log = TRUE)
in order to be able to call this command in the implementation of the likelihood in target += vg_lpdf(x | vgC , sigma , theta , nu)
?
That is not possible, except you can look at the source code of the R implementation and utilize the same logic in a Stan function that you write. It is essentially only possible to call external C++ code, and even then the external C++ code must be templated in order to accept Stan's custom scalar types that enable gradients to be calculated via automatic differentiation.
In addition, the variance-gamma distribution would be difficult to implement in Stan because its Bessel functions can only be evaluated at integer orders. Also, the absolute value operations tend to mess up the MCMC algorithm in Stan, which assumes the posterior log-kernel is differentiable everywhere.
My guess is that it will work better if you use Stan's integrate_1d
function to integrate out the latent error that has a Gamma distribution (or really any distribution).
https://mc-stan.org/docs/2_23/stan-users-guide/integrate-1d.html