I have been trying to implement a random walk in rethinking::ulam. I'd be interested in how to do this in general after reading discussions such as this and this on how to build random walks in Stan and its other R interfaces such as brms.
Here is a MRE for a specific case trying to model the decay parameter k of the exponential decay function f(x) = a * e^(-k * x) as a function of x using random walk:
# generate data
set.seed(10)
x <- 1:250
r <- rnorm(x, mean = 0, sd = sqrt(x^-1.5))
y <- 2 * exp(-0.04 * x) + r
require(tidyverse)
df <- tibble(x = x, y = y)
ggplot(df, aes(x, y)) +
geom_point() +
theme_minimal()
# prepare data for ulam
l <- as.list(df)
l$N <- length(l$x)
# run model
require(rethinking)
rw.mod <- ulam(
alist(
y ~ dnorm(mean = mu, sd = sigma),
mu <- a * exp(-k * x),
k <- 0.04,
for (i in 2:N) {
k[i] <- k[i - 1] + r
},
r ~ dnorm(mean = 0, sd = tau),
a ~ dlnorm(meanlog = log(2), sdlog = 0.5),
c(sigma, tau) ~ dexp(rate = 1)
), data = l, chains = 8, cores = parallel::detectCores(), iter = 1e4
)
This yields the following error: Error in get_dist_template(the_dist[1]) : No template for distribution ':'
I also tried specifying the vector 2:N in the for loop as seq(from = 2, to = N, by = 1), in which case I get the same error: Error in get_dist_template(the_dist[1]) : No template for distribution 'seq'
Any solutions or pointers would be greatly appreciated! If there is no solution in rethinking::ulam, I'd be grateful to understand how to do this in Stan, since there seems to be no vignette online and I did not understand the linked discussions on discourse.mc-stan.org.
Update
Random walk is not currently possible in rethinking::ulam and a feature request has been added. I am currently figuring out how to use Stan instead, which you can follow here. Solutions in Stan are still greatly appreciated.