Using functions external to greta

Hello! I have been using greta for a few months for a few simple models. However I have been moving to more complicated models to fit, including one that requires integrals. Is there a way to model this with greta? I have tried to use the integrate function however it substitutes the arguments right away (and gives it an error) when I call the function, instead of doing so when I call the mcmc later.
Below I give an example that reproduces the error, where I try to model the integrate of x + a constant:
library(greta)
set.seed(999)

# Generate data -----------------------------------------------------------

nobs = 1000
x <- runif(nobs, 0,4)
a <- 2
xb <- c()

integrand <- function(x , c=1){ #function to integrate
  return (c-x)
} 

for (i in 1:nobs){
  xb[i] <- integrate(integrand, lower=0, upper=x[i], c=a)$value
}

y <- rnorm(nobs, xb, sd=0.5)

y <- as_data(y)
x <- as_data(x)


# priors ------------------------------------------------------------------

sigma_y<- cauchy(0,3)
alpha <- variable(dim=1)

mu <- greta_array(dim=nobs)
for(i in nobs){
  mu[i] <- integrate(integrand, lower=0, upper=x[i], c=alpha)$value
}


# likelihood --------------------------------------------------------------

distribution(y) <- normal(mu, sigma_y)

The error in question:

Error in integrate(integrand, lower = 0, upper = x[i], c = alpha) : 
non-finite function value

I only give the example for the integrate function, but I believe that this might happen with others due to the incompatibility with object types, thus the more generic title.

Thanks in advance!

1 Like