qwitahead
qwitahead

Reputation: 21

Two identical boxes, each has 40, I want to simulate removing matches until either box is empty using R2OpenBUGS, but keep facing issues

I'm trying to run a simulation for R2OpenBUGS where I have two matchboxes and remove one at random, and I'll run the simulation around 8000 times to find the average result.

This is the model I use:

writeLines("
model {
  matches_box1 <- 40
  matches_box2 <- 40

  # Initialize the total matches removed
  total_matches_removed <- 0

  # Keep removing matches until one box is empty
  while (matches_box1 > 0 & matches_box2 > 0) {
    # Choose a box at random (1 or 2)
    box_chosen <- step(2)  # Randomly choose 1 or 2

    # Remove a match from the chosen box
    if (box_chosen == 1) {
      matches_box1 <- matches_box1 - 1
    } else {
      matches_box2 <- matches_box2 - 1
    }

    total_matches_removed <- total_matches_removed + 1
  }

  # Save the result
  average_matches_removed <- total_matches_removed
}
", con = "MatchesRemoval.txt")

And how I run the simulation

res <- bugs(data = NULL, inits = NULL, n.chains = 4, n.iter = 8000, n.burnin = 1000,
            parameters.to.save = c("average_matches_removed"), model.file = "MatchesRemoval.txt", DIC = FALSE, codaPkg = TRUE)

I keep either running into issues with: Error in datalist[[i]] : subscript out of bounds or other errors within my model. When trying to use the model in OpenBUGS directly I get the error message: Sorry something went wrong in the procedure ReadHEader in module BugsRectData

I have performed the simulation in R directly to get the average number to be 72-73 but because it doesn't account for the MCMC process, the number varies too much.

I'm not quite sure what I am doing wrong, any help would be greatly appreciated.

I have tried to run a vastly simplified version

writeLines("
model {
  while (n_matches_box1 > 0) {
    n_matches_box1 <- n_matches_box1 - 1
    # Increment the total matches removed
    total_matches_removed <- total_matches_removed + 1
  }

  # Save the result
  average_matches_removed <- total_matches_removed
}
", con = "MatchesRemoval.txt")

But get told that I have the same error, Error in datalist[[i]] : subscript out of bounds

Upvotes: 1

Views: 26

Answers (0)

Related Questions