Integrate_1d inside a user-defined function

Hi,

I’m trying to define a function which calls integrate_1d internally, but no matter what I try I end up with an error. Is it possible at all?

The issue seems to be with the x_r argument. Since integrate_1d is called inside a function, I don’t have any actual data to pass to it. An empty {} throws an error ("PARSER EXPECTED: ") and providing a dummy {1.0} passes the parser but gives an error later on (“Error in compileCode”). Trying to fill x_r with a local variable defined inside the function throws an error too (“fifth argument to integrate_1d, the real data, must be data only and not reference parameters”)

By contrast, filling x_i with a local variable doesn’t seem to create any issue for the parser.

Here’s a relatively minimal example of something that passes the parser but still doesn’t work (for me at least):


functions {
	real integrand(real x, real xc, real[] theta, real[] x_r, int[] x_i) {
		real a = theta[1];
		return a*x^-2;
	}
	real my_function(real ul,real a) {
		int x_i[0];
		return integrate_1d(integrand,1,ul,{a},{1.0},x_i,0.01);
	}
}

data {
  real a;
}

parameters {
  real<lower=1> ul;
}

model {
  ul ~ normal(2,1);
  target += my_function(ul,a);
}

Any suggestions welcome! I’m using rstan 2.21.2 if it’s relevant.

Update in case someone else encounters the same problem: using CmdStanR instead of rstan, the code posted above works. So it must be another rstan/RStudio specific issue, but it’s definitely possible to use integrate_1d inside a user-defined function!

1 Like