Problem with Lotka-Volterra example

I am going through the Lotka-Volterra example, trying to reproduce it.


library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores(logical = FALSE))

lynx_hare_df <-
  read.csv("hudson-bay-lynx-hare.csv", comment.char="#")
head(lynx_hare_df, n = 3)

lynx_hare_melted_df <- melt(as.matrix(lynx_hare_df[, 2:3]))
colnames(lynx_hare_melted_df) <- c("year", "species", "pelts")
lynx_hare_melted_df$year <-
  lynx_hare_melted_df$year +
  rep(1899, length(lynx_hare_melted_df$year))
head(lynx_hare_melted_df, n=3)

tail(lynx_hare_melted_df, n=3)

N <- length(lynx_hare_df$Year) - 1 # num observations

ts <- 1:N # observation time

y0 <- c(lynx_hare_df$Hare[1], lynx_hare_df$Lynx[1]) # first observation

y<- as.matrix(lynx_hare_df[2:(N + 1), 2:3]) # remaining observ

y <- cbind(y[ , 2], y[ , 1]); # reverse order
lynx_hare_data <- list(N, ts, y0, y)

model <- stan_model("lotka-volterra.stan")

fit <- sampling(model, data = lynx_hare_data)

I get the following error:

> fit <- sampling(model, data = lynx_hare_data)
Error in new_CppObject_xp(fields$.module, fields$.pointer, ...) : 
  Exception: variable does not exist; processing stage=data initialization; variable name=N; base type=int  (in 'model6d34530f74d5_lotka_volterra' at line 21)

failed to create the sampler; sampling not done

But the variable N does exist, the data for the stan model is a class list with N in the first position as a num.

lynx_hare_data <- list(N, ts, y0, y)

Any help would be much appreciated, thank you.

You’ll want to add names to the list, like:

lynx_hare_data <- list(N = N,
                       ts = ts,
                       y_init = y0,
                       y = y)

These aren’t added automatically by R. The list names (the things on the left side of the equals signs) are matched to the names in the Stan model. That make sense?

Yes, adding names did the trick!
I obtained similar estimates for the parameters than those provided in the example.
However, I noticed that during the sampling process, there were some errors:

SAMPLING FOR MODEL 'lotka-volterra' NOW (CHAIN 4).
Chain 4: Rejecting initial value:
Chain 4:   Error evaluating the log probability at the initial value.
Chain 4: Exception: lognormal_lpdf: Location parameter[2] is nan, but must be finite!  (in 'model6d34530f74d5_lotka_volterra' at line 44)

Chain 4: Rejecting initial value:
Chain 4:   Error evaluating the log probability at the initial value.
Chain 4: Exception: lognormal_lpdf: Location parameter[6] is nan, but must be finite!  (in 'model6d34530f74d5_lotka_volterra' at line 44)
1 Like

Sometimes it takes a few tries before Stan can find initial conditions that work. If the chain stops complaining after a couple tries, you’re probably good to go.