external functions in user-defined Stan functions?

514 views
Skip to first unread message

Noah Motion

unread,
Jun 26, 2014, 3:47:16 PM6/26/14
to stan-...@googlegroups.com
I can't tell for sure from reading the manual whether or not one could use an external function in a user-defined Stan function. So, for example, it would be very useful if I could use a multivariate normal CDF function from the mnormt R package in a user-defined Stan function. It seems unlikely that just sticking an R (or Fortran, or whatever) function in there would work, but I want to confirm that this is the case.

Bob Carpenter

unread,
Jun 26, 2014, 5:42:47 PM6/26/14
to stan-...@googlegroups.com
Correct. The user-defined functions are user-defined in Stan's
function definition syntax.

It is possible to integrate external functions written in C++, but
you need to be able to compute their gradients with respect to every
input that is going to be a parameter. Usually R functions
don't come with gradients and are not templated in such a way
that we can use them with auto-diff.

- Bob

On Jun 26, 2014, at 9:47 PM, Noah Motion <noahs...@gmail.com> wrote:

> I can't tell for sure from reading the manual whether or not one could use an external function in a user-defined Stan function. So, for example, it would be very useful if I could use a multivariate normal CDF function from the mnormt R package in a user-defined Stan function. It seems unlikely that just sticking an R (or Fortran, or whatever) function in there would work, but I want to confirm that this is the case.
>
> --
> You received this message because you are subscribed to the Google Groups "Stan users mailing list" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to stan-users+...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

David Manheim

unread,
Aug 3, 2015, 2:54:37 PM8/3/15
to Stan users mailing list
Hi Bob,
How would one integrate such a  user defined function in C++?

I assume the function would need the gradients pre-specified; what form would this be provided in? Is there an example of this available somewhere?

Thanks,
David Manheim

Bob Carpenter

unread,
Aug 3, 2015, 5:21:26 PM8/3/15
to stan-...@googlegroups.com
See:

https://github.com/stan-dev/stan/wiki/Contributing-New-Functions-to-Stan

It probalby needs to be updated now that we separated out the math lib
as a Git submodule.

This is assuming you want to add it to the Stan language for others.
You can be sloppier if you just want to use it yourself.

Also, you can either define it in terms of existing functions using
templating (in which case autodiff will do the derivatives), or you
can write a class extending stan::math::vari with analytic derivatives.
The latter is usually much faster and can also be more precise for
iterative algorithms.

- Bob
Reply all
Reply to author
Forward
0 new messages