Use predictor functions from other libraries with brms

I suspect this question has been asked before, but I couldn’t find it after searching.

I’m interested in using brms to fit several models provided by the rTPC package such as the following two:

> modifiedgaussian_2006
function (temp, rmax, topt, a, b) 
{
    est <- rmax * exp(-0.5 * (abs(temp - topt)/a)^b)
    return(est)
}
<bytecode: 0x55901d7b9960>
<environment: namespace:rTPC>
> lactin2_1995
function (temp, a, b, tmax, delta_t) 
{
    est <- exp(a * temp) - exp(a * tmax - ((tmax - temp)/delta_t)) + 
        b
    return(est)
}
<bytecode: 0x55901211b818>
<environment: namespace:rTPC>

Is there a straightforward way to do this? That is, I’m hoping to do something like

nlform <-  bf(song_count ~ eval(modified_gaussian_2006(temp, rmax, topt, a, b)),
             rmax ~ male,
             topt ~ 1,
             a ~ 1,
             b ~ 1,
             nl = TRUE)

model_mgauss_nb1 <- brm(formula = nlform,
                   data = data,
                   family = negbinomial(link = "identity",
                                        link_shape = "identity"),
                   prior = nlprior,
                   chains = 4, cores = 4,
                   iter = 3000)

Thanks,

Mike

  • Operating System: Ubuntu 22.04
  • brms Version: 2.18.0

Unfortunately not, since you can’t use R functions in Stan models - all functions and their gradients need to be accessible from c++. While you can call R functions from c++, they can’t be auto-differentiated to provide the gradients, and so they can’t be used as part of HMC/NUTS sampling.

Your options here would be to reimplement the function using either the non-linear or custom family frameworks for brms

I would add that if you can write your function in Stan code it can be called via the brms non-linear formula syntax easily.

See this paper (i.e., page 86) for examples:

2 Likes